nineskeletor/templates/Home/publishsample.html.twig

98 lines
3.4 KiB
Twig
Executable File

{% if app.user %}
{% set idwidget=uniqueId() %}
<div id="chat{{idwidget}}">
<textarea class="form-control mb-2" id="pushmessage" rows="3"></textarea>
<button class="btn btn-primary" onClick="send{{idwidget}}()" class="mt-2">Send</button>
<div id="aliveusers" class="mt-3 mb-3"></div>
<div id="chat"></div>
</div>
<script>
function connect{{idwidget}}() {
channel="chat";
id{{idwidget}}={{id}};
const eventSource = new EventSource("{{ mercure('chat-'~id)|escape('js') }}");
eventSource.onopen = function(e) {
console.log("== ONOPEN chat"+id{{idwidget}});
console.log("== SEND alive");
sendMessage{{idwidget}}(channel,id{{idwidget}},{command: "alive"});
};
eventSource.onclose = function(e) {
console.log("== ONCLOSE");
sendMessage{{idwidget}}(channel,id,{command: "dead"});
setTimeout(function() { connect{{idwidget}}(); }, 5000);
};
eventSource.onmessage = event => {
data=JSON.parse(event.data);
ret=data.ret;
console.log("== ONMESSAGE = "+ret.command);
console.log(ret);
switch (ret.command) {
case "alive":
sendMessage{{idwidget}}(channel,id{{idwidget}},{command: "meto"});
break;
case "meto":
if(!$("#chat{{idwidget}} #aliveuser"+ret.from.id).length) {
html='<img id="aliveuser'+ret.from.id+'" src="'+ret.from.avatar+'" title="'+ret.from.displayname+'"class="avatar me-1">';
$("#chat{{idwidget}} #aliveusers").append(html);
}
break;
case "dead":
sendMessage{{idwidget}}(channel,id{{idwidget}},{command: "alive"});
if($("#aliveuser"+ret.from.id).length) {
$("#aliveuser"+ret.from.id).remove();
}
break;
case "push":
html ='<div class="card mt-1"><div class="card-body d-flex">';
html+='<img id="msguser'+ret.from.id+'" src="'+ret.from.avatar+'" title="'+ret.from.displayname+'"class="avatar me-1">';
html+='<div class="ps-2"><small>'+ret.message.replace(/\n/g,"<br>")+'</small></div>';
html+='</div></div>';
$("#chat{{idwidget}} #chat").prepend(html);
break;
}
}
$(window).on("beforeunload", function() {
sendMessage{{idwidget}}(channel,id{{idwidget}},{command: "dead"});
})
}
connect{{idwidget}}();
function sendMessage{{idwidget}}(channel,id,msg) {
url="{{path("app_publish",{channel:'xxx',id:'yyy'})}}";
url=url.replace('xxx',channel);
url=url.replace('yyy',id{{idwidget}});
$.ajax({
method: "POST",
url: url,
data: {
msg: msg
},
success: function(data, dataType)
{
},
});
}
function send{{idwidget}}() {
if($("#chat{{idwidget}} #pushmessage").val()) {
console.log("SEND push")
sendMessage{{idwidget}}('chat',1,{command: "push", message:$("#chat{{idwidget}} #pushmessage").val()});
$("#chat{{idwidget}} #pushmessage").val("");
}
}
</script>
{% endif %}