nekrochan/static/js/live.js

68 řádky
2.2 KiB
JavaScript
Surový Normální zobrazení Historie

$(function () {
2024-03-02 23:19:48 +00:00
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);
ws.addEventListener("open", function (_) {
$("#live-indicator").css("background-color", "lime");
$("#live-status").text("Připojeno pro nové příspěvky");
});
ws.addEventListener("message", function (msg) {
let data = JSON.parse(msg.data);
switch (data.type) {
case "created":
$(".thread").append(data.html + "<br>");
2024-03-02 23:19:48 +00:00
$(window).trigger({
type: "setup_post_events",
id: data.id,
});
break;
case "updated":
$(`#${data.id}`).replaceWith(data.html);
2024-03-02 23:19:48 +00:00
$(window).trigger({
type: "setup_post_events",
id: data.id,
});
break;
case "removed":
$(`#${data.id}`).next("br").remove();
$(`#${data.id}`).remove();
break;
2024-03-02 23:19:48 +00:00
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");
});
});