ranui
Version:
A framework-agnostic Web Components UI library built on native custom elements, with TypeScript types, light/dark theming, SSR and PWA support.
90 lines (89 loc) • 2.41 kB
JavaScript
var n = "ran-locale", i = Object.freeze({}), o = (e) => {
if (typeof localStorage > "u") return null;
try {
return localStorage.getItem(e);
} catch {
return null;
}
}, _ = (e, t) => {
if (!(typeof localStorage > "u"))
try {
localStorage.setItem(e, t);
} catch {
}
}, c = (e) => {
if (typeof navigator > "u" || !navigator.language) return null;
const t = navigator.language.toLowerCase();
return e.find((s) => s.toLowerCase() === t) ?? e.find((s) => t.startsWith(s.toLowerCase())) ?? e.find((s) => t.startsWith(`${s.toLowerCase()}-`)) ?? null;
}, h = class {
_locale;
_fallback;
_messages;
_persist;
_storageKey;
_handlers = /* @__PURE__ */ new Set();
constructor(e = {}) {
this._messages = { ...e.messages }, this._fallback = e.fallbackLocale ?? "en", this._persist = e.persist ?? !1, this._storageKey = e.storageKey ?? n, this._locale = this._resolveInitialLocale(e);
}
_resolveInitialLocale(e) {
const t = Object.keys(this._messages), s = this._persist ? o(this._storageKey) : null;
if (s && (this._messages[s] || t.length === 0)) return s;
if (e.locale) return e.locale;
if (e.detectNavigator) {
const r = c(t);
if (r) return r;
}
return this._fallback;
}
get locale() {
return this._locale;
}
getLocale() {
return this._locale;
}
setLocale(e) {
e !== this._locale && (this._locale = e, this._persist && _(this._storageKey, e), this._notify());
}
addMessages(e, t) {
this._messages[e] = {
...this._messages[e],
...t
};
}
getMessages(e = this._locale) {
return this._messages[e] ?? {};
}
get availableLocales() {
return Object.keys(this._messages);
}
t(e, t) {
const s = this._messages[this._locale]?.[e] ?? this._messages[this._fallback]?.[e] ?? e;
return this._interpolate(s, t);
}
_interpolate(e, t) {
const s = t ?? i;
return e.replace(/\{\{|\}\}|\{(\w+)\}/g, (r, l) => r === "{{" ? "{" : r === "}}" ? "}" : s[l] != null ? String(s[l]) : r);
}
onChange(e) {
return this._handlers.add(e), () => {
this._handlers.delete(e);
};
}
_notify() {
for (const e of this._handlers) e(this._locale);
}
destroy() {
this._handlers.clear();
}
}, a = null;
function u(e = {}) {
return a = new h(e), a;
}
function g() {
return a;
}
export {
h as I18nCore,
u as createI18n,
g as useI18n
};