pixrick / web /i18n.js
Algorick's picture
43349f16d3a2
b48b1fc verified
Raw History Blame Contribute Delete
10.4 kB
/* Lingua dell'interfaccia: italiano di base, inglese tradotto al volo.
I testi restano scritti in italiano nel codice; qui li sostituisco nel DOM man mano che compaiono. */
(() => {
"use strict";
const KEY = "pixrick.lingua";
const ATTRS = ["placeholder", "title", "aria-label", "alt"];
const SKIP = new Set(["SCRIPT", "STYLE", "TEXTAREA", "CODE", "PRE"]);
let dict = {};
let lang = pick();
const original = new WeakMap();
function pick() {
try {
const saved = localStorage.getItem(KEY);
if (saved === "it" || saved === "en") return saved;
} catch { /* storage bloccato */ }
return (navigator.language || "it").toLowerCase().startsWith("it") ? "it" : "en";
}
const PATTERNS = [
[/^(\d+) immagini$/, (m) => `${m[1]} images`],
[/^ · (\d+) immagini$/, (m) => ` · ${m[1]} images`],
[/^Al massimo (\d+) foto in questa modalità$/, (m) => `At most ${m[1]} photos in this mode`],
[/^Al massimo (\d+) stili insieme$/, (m) => `At most ${m[1]} styles together`],
[/^Con Entrambi: (\d+) per modello, (\d+) in tutto, su due righe\.$/, (m) => `With Both: ${m[1]} per model, ${m[2]} in total, on two rows.`],
[/^Foto (\d+)$/, (m) => `Photo ${m[1]}`],
[/^Giro la figura: (.*)$/, (m) => `Turning the figure: ${tr(m[1])}`],
[/^Immagine (\d+) di (\d+)$/, (m) => `Image ${m[1]} of ${m[2]}`],
[/^In coda: (\d+) prima di te$/, (m) => `Queued: ${m[1]} ahead of you`],
[/^Circa (\d+) s$/, (m) => `About ${m[1]} s`],
[/^Preparo (.+)$/, (m) => `Preparing ${m[1]}`],
[/^Klein prepara (.+)$/, (m) => `Klein prepares ${tr(m[1])}`],
[/^Z-Image rifinisce (.+)$/, (m) => `Z-Image refines ${tr(m[1])}`],
[/^l'immagine (\d+) di (\d+)$/, (m) => `image ${m[1]} of ${m[2]}`],
[/^Modifica lo stile (.+)$/, (m) => `Edit the style ${m[1]}`],
[/^Modifica «(.+)»$/, (m) => `Edit “${m[1]}”`],
[/^Eliminare «(.+)»\?$/, (m) => `Delete “${m[1]}”?`],
[/^Ogni immagine passa da Klein e poi da Z-Image: ricevi (\d+) immagin[ei] finit[ae]\.$/, (m) => `Each image goes through Klein and then Z-Image: you get ${m[1]} finished image${m[1] === "1" ? "" : "s"}.`],
[/^Pronta in ([\d.]+) s$/, (m) => `Ready in ${m[1]} s`],
[/^Prova con (.+)$/, (m) => `Try ${m[1]}`],
[/^Stai per eliminare (.+) dal cestino\. Non si può annullare\.$/, (m) => `You're about to delete ${tr(m[1])} from the trash. This can't be undone.`],
[/^Stile «(.+)» salvato e selezionato$/, (m) => `Style “${m[1]}” saved and selected`],
[/^«(.+)» ha impostato anche (modello e )?qualità$/, (m) => `“${m[1]}” also set ${m[2] ? "model and " : ""}quality`],
[/^Ricorda anche modello e qualità \((.+)\)$/, (m) => `Also remember model and quality (${tr(m[1])})`],
[/^Vista (\d+) di (\d+) · ([\d.]+) s$/, (m) => `View ${m[1]} of ${m[2]} · ${m[3]} s`],
[/^fedeltà ([\d.]+)( auto)?$/, (m) => `fidelity ${m[1]}${m[2] || ""}`],
[/^passo (\d+) di (\d+) · (\d+) s$/, (m) => `step ${m[1]} of ${m[2]} · ${m[3]} s`],
[/^(.+) · passo (\d+) di (\d+) · (\d+) s$/, (m) => `${m[1]} · step ${m[2]} of ${m[3]} · ${m[4]} s`],
[/^(.+), (\d+) di (\d+)$/, (m) => `${m[1]}, ${m[2]} of ${m[3]}`],
[/^Vista (\d+) di (\d+)$/, (m) => `View ${m[1]} of ${m[2]}`],
[/^(\d+) immagini eliminate per sempre$/, (m) => `${m[1]} images deleted forever`],
[/^(\d+) immagini nel cestino$/, (m) => `${m[1]} images moved to trash`],
[/^(\d+) immagini pronte in ([\d.]+) s: salva quelle che ti piacciono$/, (m) => `${m[1]} images ready in ${m[2]} s: save the ones you like`],
[/^(\d+) immagini ripristinate$/, (m) => `${m[1]} images restored`],
[/^(\d+) immagini salvate in galleria$/, (m) => `${m[1]} images saved to gallery`],
[/^(\d+) bozze eliminate$/, (m) => `${m[1]} drafts deleted`],
[/^(\d+) selezionat[ae]$/, (m) => `${m[1]} selected`],
[/^Altri (\d+)$/, (m) => `${m[1]} more`],
[/^Errore (\d+)$/, (m) => `Error ${m[1]}`],
[/^(.+), da una foto$/, (m) => `${tr(m[1])}, from a photo`],
[/^(.+)\. Il primo decide il tipo di immagine, gli altri aggiungono il loro stile\.$/, (m) => `${tr(m[1])}. The first decides the kind of image, the others add their style.`],
[/^Qualcosa è andato storto durante la generazione\. Riprova\.(.*)$/, (m) => `Something went wrong while generating. Try again.${m[1]}`],
[/^Accesso con Hugging Face: (.+)$/, (m) => `Signed in with Hugging Face: ${m[1]}`],
[/^Accesso con Hugging Face come @(\S+)\. Le generazioni usano la tua quota personale\.$/, (m) => `Signed in with Hugging Face as @${m[1]}. Generations use your personal quota.`],
[/^Ciao @(\S+): da ora le generazioni usano la tua quota personale di Hugging Face\.$/, (m) => `Hi @${m[1]}: from now on generations use your personal Hugging Face quota.`],
[/^Si riparte (oggi|domani) alle (\d{1,2}:\d{2})\.$/, (m) => `You can start again ${m[1] === "oggi" ? "today" : "tomorrow"} at ${m[2]}.`],
[/^«(.+)» cambia forme e proporzioni: l'ha fatta Klein, che capisce la foto$/, (m) => `“${m[1]}” changes shapes and proportions: Klein made it, since it understands the photo`],
[/^Da (un disegno|una foto) a (una foto vera|un disegno|un modello 3D|una grafica): l'ha fatta Klein, che capisce cosa c'è nell'immagine$/, (m) => {
const what = { "una foto vera": "a real photo", "un disegno": "a drawing", "un modello 3D": "a 3D model", "una grafica": "a graphic" };
return `From ${m[1] === "un disegno" ? "a drawing" : "a photo"} to ${what[m[2]]}: Klein made it, since it understands what's in the image`;
}],
];
const QUALITY = { rapida: "fast", bilanciata: "balanced", massima: "max" };
const steps = (text) => text.replace(/(\d+) passi/g, "$1 steps");
PATTERNS.push(
[/^(.+?\.) ((?:[\w.\- ]+ \d+ passi(?:, )?)+)\.?$/, (m) => `${tr(m[1])} ${steps(m[2])}.`],
[/^(rapida|bilanciata|massima), (\d+) passi$/, (m) => `${QUALITY[m[1]]}, ${m[2]} steps`],
);
const LOWER = { "lato sinistro": "left side", retro: "back", "lato destro": "right side", "questa immagine": "this image" };
function tr(text) {
if (lang === "it" || !text) return text;
if (dict[text] !== undefined) return dict[text];
const trimmed = text.trim();
if (trimmed !== text && dict[trimmed] !== undefined) return text.replace(trimmed, dict[trimmed]);
if (LOWER[trimmed]) return LOWER[trimmed];
for (const [re, fn] of PATTERNS) {
const m = trimmed.match(re);
if (m) return text.replace(trimmed, fn(m));
}
const joined = trimmed.split(" · ");
if (joined.length > 1 && joined.some((p) => dict[p] !== undefined)) return joined.map((p) => dict[p] ?? p).join(" · ");
return text;
}
function translateNode(node) {
if (node.nodeType === Node.TEXT_NODE) {
const parent = node.parentElement;
if (!parent || SKIP.has(parent.tagName) || parent.closest("[data-no-i18n], .tile-title, .card-name, .session-list, .pp-layer-name")) return;
const value = node.nodeValue;
if (!value || !value.trim()) return;
let rec = original.get(node);
if (!rec || (rec.shown !== value)) rec = { it: value };
const shown = lang === "it" ? rec.it : tr(rec.it);
rec.shown = shown;
original.set(node, rec);
if (shown !== value) node.nodeValue = shown;
return;
}
if (node.nodeType !== Node.ELEMENT_NODE || SKIP.has(node.tagName) && node.tagName !== "TEXTAREA") return;
translateAttrs(node);
if (node.closest?.("[data-no-i18n]")) return;
for (const child of node.childNodes) translateNode(child);
}
function translateAttrs(el) {
if (el.closest?.("[data-no-i18n]")) return;
let store = original.get(el);
for (const attr of ATTRS) {
if (!el.hasAttribute(attr)) continue;
const value = el.getAttribute(attr);
store ||= {};
const rec = store[attr];
const base = rec && rec.shown === value ? rec.it : value;
const shown = lang === "it" ? base : tr(base);
store[attr] = { it: base, shown };
if (shown !== value) el.setAttribute(attr, shown);
}
if (store) original.set(el, store);
}
function translateAll() {
translateNode(document.body);
const title = document.querySelector("title");
if (title) {
const rec = original.get(title) || { it: title.textContent };
original.set(title, rec);
document.title = lang === "it" ? rec.it : tr(rec.it);
}
}
const observer = new MutationObserver((list) => {
if (lang === "it") return;
for (const m of list) {
if (m.type === "characterData") translateNode(m.target);
else if (m.type === "attributes") translateAttrs(m.target);
else m.addedNodes.forEach(translateNode);
}
});
async function load() {
if (lang === "it") return;
try {
const res = await fetch("/web/i18n/en.json", { cache: "no-cache" });
dict = await res.json();
} catch {
dict = {};
}
}
async function set(next) {
lang = next === "en" ? "en" : "it";
try { localStorage.setItem(KEY, lang); } catch { /* storage bloccato */ }
if (lang === "en" && !Object.keys(dict).length) {
const res = await fetch("/web/i18n/en.json", { cache: "no-cache" }).catch(() => null);
dict = res ? await res.json().catch(() => ({})) : {};
}
document.documentElement.lang = lang;
translateAll();
syncButton();
document.dispatchEvent(new CustomEvent("pixrick:lang", { detail: { lang } }));
}
function syncButton() {
const btn = document.getElementById("lang-btn");
if (!btn) return;
btn.textContent = lang === "it" ? "EN" : "IT";
btn.setAttribute("aria-label", lang === "it" ? "Lingua: italiano. Passa all'inglese" : "Language: English. Switch to Italian");
}
const ready = (async () => {
await load();
document.documentElement.lang = lang;
const start = () => {
translateAll();
syncButton();
observer.observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ATTRS });
document.getElementById("lang-btn")?.addEventListener("click", () => set(lang === "it" ? "en" : "it"));
};
if (document.body) start();
else document.addEventListener("DOMContentLoaded", start, { once: true });
})();
window.PixI18n = { t: tr, get lang() { return lang; }, set, ready };
})();