74 řádky
2.3 KiB
JavaScript
74 řádky
2.3 KiB
JavaScript
$(function () {
|
|
let main = $(".thread + hr + .pagination + hr");
|
|
|
|
main.after(
|
|
'<div id="live-info" class="box inline-block"><span id="live-indicator"></span> <span id="live-status"></span></div><br>'
|
|
);
|
|
|
|
$("#live-indicator").css("background-color", "orange");
|
|
$("#live-status").text("Připojování...");
|
|
|
|
let thread = window.location.pathname.split("/").slice(-2);
|
|
let protocol;
|
|
|
|
if (window.location.protocol === "https:") {
|
|
protocol = "wss:";
|
|
} else {
|
|
protocol = "ws:";
|
|
}
|
|
|
|
let last_post = $(".thread").find(".post").last().attr("id");
|
|
|
|
let ws_location = `${protocol}//${window.location.host}/live/${thread[0]}/${thread[1]}/${last_post}`;
|
|
let ws = new WebSocket(ws_location);
|
|
let interval;
|
|
|
|
ws.addEventListener("open", function (_) {
|
|
$("#live-indicator").css("background-color", "lime");
|
|
$("#live-status").text("Připojeno pro nové příspěvky");
|
|
|
|
interval = setInterval(function () {
|
|
ws.send('{"type":"ping"}');
|
|
}, 10000);
|
|
});
|
|
|
|
ws.addEventListener("message", function (msg) {
|
|
let data = JSON.parse(msg.data);
|
|
|
|
switch (data.type) {
|
|
case "created":
|
|
$(".thread").append(data.html + "<br>");
|
|
$(window).trigger({
|
|
type: "setup_post_events",
|
|
id: data.id,
|
|
});
|
|
break;
|
|
case "updated":
|
|
$(`#${data.id}`).replaceWith(data.html);
|
|
$(window).trigger({
|
|
type: "setup_post_events",
|
|
id: data.id,
|
|
});
|
|
break;
|
|
case "removed":
|
|
$(`#${data.id}`).next("br").remove();
|
|
$(`#${data.id}`).remove();
|
|
break;
|
|
case "thread_removed":
|
|
setTimeout(function () {
|
|
$("#live-indicator").css("background-color", "red");
|
|
$("#live-status").text("Vlákno bylo odstraněno");
|
|
}, 100);
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
});
|
|
|
|
ws.addEventListener("close", function (_) {
|
|
$("#live-indicator").css("background-color", "red");
|
|
$("#live-status").text("Odpojeno, obnov stránku");
|
|
clearInterval(interval);
|
|
});
|
|
});
|