nineskeletor/templates/Home/home.html.twig

82 lines
2.1 KiB
Twig

{% extends "base.html.twig" %}
{% block body %}
{% if app.user %}
<button class="btn btn-primary" onClick="send()">Send</button>
<div id="chat"></div>
{% endif %}
{% endblock %}
{% block localscript %}
{% if app.user %}
<script>
function connect() {
channel="chat";
id=1;
const eventSource = new EventSource("{{ mercure('chat-1')|escape('js') }}");
eventSource.onopen = function(e) {
console.log("== ONOPEN");
sendMessage(channel,id,{command: "alive"});
};
eventSource.onclose = function(e) {
console.log("== ONCLOSE");
sendMessage(channel,id,{command: "dead"});
setTimeout(function() { connect(); }, 1000);
};
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(channel,id,{command: "meto"});
break;
case "meto":
break;
case "dead":
break;
case "push":
$("#chat").prepend('<div class="card mt-3"><div class="card-body">'+ret.message+'</div></div>');
break;
}
}
$(window).on("beforeunload", function() {
sendMessage(channel,id,{command: "dead"});
})
}
connect();
function sendMessage(channel,id,msg) {
url="{{path("app_publish",{channel:'xxx',id:'yyy'})}}";
url=url.replace('xxx',channel);
url=url.replace('yyy',id);
$.ajax({
method: "POST",
url: url,
data: {
msg: msg
},
success: function(data, dataType)
{
},
});
}
function send() {
sendMessage('chat',1,{command: "push", message:"pouet"});
}
</script>
{% endif %}
{% endblock %}