Files
Life-OS/public/i18n.js
T

23 lines
1.2 KiB
JavaScript

/* Translation lookup and locale-aware formatting. Copy lives in /locales/*.json. */
(() => {
const dictionaries = window.LifeOSLocales || {};
const en = dictionaries.en || {};
const zh = dictionaries['zh-CN'] || {};
const lookup = (object, path) => path.split('.').reduce((value, part) => value?.[part], object);
const current = () => typeof window.lang === 'function' && window.lang() === 'zh' ? 'zh' : 'en';
function t(key, values = {}) {
const selected = current() === 'zh' ? zh : en;
const template = lookup(selected, key) ?? lookup(en, key) ?? key;
return String(template).replace(/\{(\w+)\}/g, (_, name) => values[name] ?? `{${name}}`);
}
function locale() { return current() === 'zh' ? 'zh-CN' : 'en-US'; }
function date(value, options) {
const parsed = value instanceof Date ? value : new Date(typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T12:00:00` : value);
return new Intl.DateTimeFormat(locale(), options).format(parsed);
}
function number(value, options) { return new Intl.NumberFormat(locale(), options).format(value); }
window.LifeI18n = { t, date, number, locale, dictionaries: { en, zh } };
})();