htmgo/framework/assets/js/htmxextensions/livereload.ts

62 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-09-17 17:13:22 +00:00
import htmx from "htmx.org";
import {createWebSocketClient} from "../util/ws";
let lastVersion = "";
htmx.defineExtension("livereload", {
init: function () {
const host = window.location.host;
2024-09-21 03:59:07 +00:00
let enabled = false
for (const element of Array.from(htmx.findAll("[hx-ext]"))) {
const value = element.getAttribute("hx-ext");
if(value?.split(" ").includes("livereload")) {
enabled = true
break;
}
}
if(!enabled) {
return
}
2024-09-17 17:13:22 +00:00
console.log('livereload extension initialized.');
2024-09-21 03:59:07 +00:00
2024-09-17 17:13:22 +00:00
createWebSocketClient({
2024-09-21 03:59:07 +00:00
url: `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${host}/dev/livereload`,
2024-09-17 17:13:22 +00:00
onOpen: () => {
},
onMessage: (message) => {
if(lastVersion === "") {
lastVersion = message;
}
if(lastVersion !== message) {
2024-09-17 18:35:44 +00:00
lastVersion = message;
reload()
2024-09-17 17:13:22 +00:00
}
},
onError: (error) => {
},
onClose: () => {
}
})
},
// @ts-ignore
onEvent: function (name, evt) {
},
2024-09-17 18:35:44 +00:00
});
function reload() {
window.location.reload()
// fetch(window.location.href).then(response => {
// return response.text();
// }).then(html => {
// document.open();
// document.write(html);
// document.close();
// }).catch(err => {
// console.log('failed to fetch live reload', err)
// setTimeout(reload, 100)
// })
2024-09-17 18:35:44 +00:00
}