// Strings come from /api/v1/i18n/{culture}, generated from the same .resx catalog as the desktop apps. const LANGUAGE_KEY = "titano.admin.language"; let strings = {}; /** Loads the strings of the chosen language (remembered per browser), else of the browser's language. */ export async function loadStrings(requested) { let preferred = requested; try { preferred ??= localStorage.getItem(LANGUAGE_KEY); } catch { // Storage may be blocked; the browser language is used. } try { const res = await fetch(`/api/v1/i18n/${encodeURIComponent(preferred || navigator.language || "en")}`); strings = await res.json(); } catch { strings = {}; } document.documentElement.lang = strings.$culture || "en"; document.documentElement.dir = strings.$rtl === "true" ? "rtl" : "ltr"; } export async function setLanguage(code) { try { localStorage.setItem(LANGUAGE_KEY, code); } catch { // Only this session uses the language then. } await loadStrings(code); } /** The current culture (e.g. "it"), used for numbers, dates and the Accept-Language of API calls. */ export function culture() { return strings.$culture || "en"; } /** Languages with translated strings, as codes. */ export function languages() { return (strings.$languages || "en").split(","); } /** Localized string for key with {0}, {1}… placeholders filled from args. */ export function t(key, ...args) { const s = strings[key]; if (s === undefined) return `⟦${key}⟧`; return s.replace(/\{(\d+)(?:[,:][^}]*)?\}/g, (_, i) => String(args[Number(i)] ?? "")); } /** True when the catalog has the key (for keys built from data, e.g. audit actions). */ export function has(key) { return strings[key] !== undefined; } /** Fills data-i18n (text), data-i18n-title (tooltip, also the accessible name of icon buttons) and data-i18n-placeholder. */ export function applyStrings(root) { root.querySelectorAll("[data-i18n]").forEach((el) => { el.textContent = t(el.dataset.i18n); }); root.querySelectorAll("[data-i18n-title]").forEach((el) => { el.title = t(el.dataset.i18nTitle); if (el.classList.contains("icon")) el.setAttribute("aria-label", el.title); }); root.querySelectorAll("[data-i18n-placeholder]").forEach((el) => { el.placeholder = t(el.dataset.i18nPlaceholder); }); }