2023-12-24 03:05:20 +01:00
|
|
|
// [x-locale-key="<key>"]
|
|
|
|
// html[x1-locale-file] -
|
|
|
|
// html[x1-locale-watch] - watch document for changes and update
|
|
|
|
(async () => {
|
|
|
|
if (!document.querySelector("html").hasAttribute("x1-locale-file")) return;
|
|
|
|
let backupElements = window.x0?.registerStorage("locale") ?? {};
|
|
|
|
let locale = (await (await fetch(document.querySelector("html").getAttribute("x1-locale-file"))).json()) ?? {};
|
|
|
|
|
|
|
|
const getValueFromPath = (obj, path) => path.split(".").reduce((obj, key) => obj && obj[key], obj);
|
|
|
|
|
|
|
|
function updateLocale() {
|
|
|
|
document.querySelectorAll("[x-locale-key]:not([x1-locale-uuid])")
|
|
|
|
.forEach(e => {
|
2023-12-24 03:17:39 +01:00
|
|
|
let uuid = (Math.random() + new Date().getTime()).toString(36);
|
2023-12-24 03:05:20 +01:00
|
|
|
e.setAttribute("x1-locale-uuid", uuid);
|
2023-12-24 03:17:39 +01:00
|
|
|
backupElements[uuid] = e.outerHTML;
|
2023-12-24 03:05:20 +01:00
|
|
|
e.innerHTML = getValueFromPath(locale, e.getAttribute("x-locale-key"));
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
updateLocale();
|
|
|
|
|
|
|
|
if (document.querySelector("html").hasAttribute("x1-locale-watch"))
|
|
|
|
document.querySelector("html").onchange = updateLocale;
|
|
|
|
|
|
|
|
window.x0?.registerModuleUpdateHook("locale", updateLocale);
|
|
|
|
|
|
|
|
window.x0?.registerModuleRemoveHook("locale", (s) => {
|
|
|
|
Object.keys(s)
|
|
|
|
.forEach(uuid => {
|
2023-12-24 03:17:39 +01:00
|
|
|
document.querySelector(`[x1-locale-uuid="${uuid}"]`).outerHTML = s[uuid];
|
2023-12-24 03:05:20 +01:00
|
|
|
})
|
|
|
|
})
|
|
|
|
})()
|