Files
descrybe/apps/web/src/lib/i18n/i18n.svelte.ts
T
greeneclipse 8580c996c3 Initial commit of Descrybe v2 without local scratch artifacts.
Drop one-shot tmp/axe scripts and agent i18n scratch so the Gitea tree is deployable.
2026-08-09 22:47:43 +02:00

96 lines
2.2 KiB
TypeScript

import { browser } from "$app/environment";
import {
DEFAULT_UI_LOCALE,
UI_LOCALE_KEY,
htmlLangFor,
isUILocale,
normalizeUILocale,
persistUILocale
} from "./locales.ts";
import { loadMessages } from "./messages/catalog.ts";
import { resolveMessage } from "./resolve.ts";
export { UI_LOCALE_KEY } from "./locales.ts";
function readStoredLocale(): string {
if (!browser) return DEFAULT_UI_LOCALE;
try {
const fromWindow = window.__UI_LOCALE__;
if (isUILocale(fromWindow)) return normalizeUILocale(fromWindow);
return normalizeUILocale(localStorage.getItem(UI_LOCALE_KEY));
} catch {
return DEFAULT_UI_LOCALE;
}
}
function paintHtmlLang(code: string): void {
if (!browser) return;
document.documentElement.lang = htmlLangFor(code);
}
function persistLocale(code: string): void {
if (!browser) return;
persistUILocale(code);
}
function createI18n() {
// SSR always starts on English (static pack). Client applies preferred locale after load.
let locale = $state(DEFAULT_UI_LOCALE);
let loadGeneration = 0;
function applyLocale(code: string): void {
locale = code;
if (!browser) return;
persistLocale(locale);
paintHtmlLang(locale);
}
/**
* Switch UI locale after the pack is loaded (dynamic import).
* Until then resolveMessage falls back to English.
*/
function setLocale(next: string): Promise<void> {
const code = normalizeUILocale(next);
const gen = ++loadGeneration;
return loadMessages(code).then(() => {
if (gen !== loadGeneration) return;
applyLocale(code);
});
}
/**
* Resolve a message key for the active UI locale.
* Falls back to English, then to the key itself.
* Interpolated vars are HTML-escaped so t() is safe in text bindings
* even if a future caller uses {@html} with translated strings.
*/
function t(key: string, vars?: Record<string, string | number>): string {
return resolveMessage(locale, key, vars);
}
function syncFromStorage(): Promise<void> {
return setLocale(readStoredLocale());
}
if (browser) {
void setLocale(readStoredLocale());
}
return {
get locale() {
return locale;
},
setLocale,
syncFromStorage,
t
};
}
export const i18n = createI18n();
declare global {
interface Window {
__UI_LOCALE__?: string;
}
}