wallet-core/packages/web-util/src/live-reload.ts

81 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-12-06 13:21:17 +01:00
/* eslint-disable no-undef */
function setupLiveReload(): void {
2023-03-10 05:21:28 +01:00
const protocol = window.location.protocol === "http:" ? "ws:" : "wss:";
2023-04-03 17:14:25 +02:00
const port = window.location.protocol === "http:" ? "8080" : "8081";
const ws = new WebSocket(`${protocol}//localhost:${port}/ws`);
2022-12-06 13:21:17 +01:00
ws.addEventListener("message", (message) => {
try {
const event = JSON.parse(message.data);
if (event.type === "file-updated-start") {
showReloadOverlay();
return;
}
if (event.type === "file-updated-done") {
window.location.reload();
return;
}
if (event.type === "file-updated-failed") {
2022-12-14 19:17:15 +01:00
const h1 = document.getElementById("overlay-text");
if (h1) {
2022-12-14 19:17:15 +01:00
h1.innerHTML = "compilation failed";
h1.style.color = "red";
h1.style.margin = "";
}
2022-12-14 19:17:15 +01:00
const div = document.getElementById("overlay");
if (div) {
2022-12-14 19:17:15 +01:00
const content = JSON.stringify(event.data, undefined, 2);
const pre = document.createElement("pre");
2022-12-14 19:17:15 +01:00
pre.id = "error-text";
pre.style.margin = "";
pre.textContent = content;
div.style.backgroundColor = "rgba(0,0,0,0.8)";
2022-12-14 19:17:15 +01:00
div.style.flexDirection = "column";
div.appendChild(pre);
}
2022-12-14 19:17:15 +01:00
console.error(event.data.error);
return;
}
if (event.type === "file-updated") {
window.location.reload();
return;
}
2022-12-06 13:21:17 +01:00
} catch (e) {
2022-12-06 19:24:36 +01:00
return;
2022-12-06 13:21:17 +01:00
}
console.log("unsupported", message);
2022-12-06 13:21:17 +01:00
});
ws.addEventListener("error", (error) => {
console.error(error);
});
ws.addEventListener("close", (message) => {
setTimeout(setupLiveReload, 1500);
});
}
setupLiveReload();
function showReloadOverlay(): void {
const d = document.createElement("div");
2022-12-14 19:17:15 +01:00
d.id = "overlay";
2022-12-06 13:21:17 +01:00
d.style.position = "absolute";
d.style.width = "100%";
d.style.height = "100%";
d.style.color = "white";
d.style.backgroundColor = "rgba(0,0,0,0.5)";
d.style.display = "flex";
2022-12-14 19:17:15 +01:00
d.style.zIndex = String(Number.MAX_SAFE_INTEGER);
2022-12-06 13:21:17 +01:00
d.style.justifyContent = "center";
const h = document.createElement("h1");
2022-12-14 19:17:15 +01:00
h.id = "overlay-text";
2022-12-06 13:21:17 +01:00
h.style.margin = "auto";
h.innerHTML = "reloading...";
d.appendChild(h);
if (document.body.firstChild) {
document.body.insertBefore(d, document.body.firstChild);
} else {
document.body.appendChild(d);
}
}