UNPKG

react-box-tools

Version:

Box tools react components, utils and hooks

74 lines (73 loc) 2.07 kB
var f = Object.defineProperty; var d = (r, t, e) => t in r ? f(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e; var i = (r, t, e) => d(r, typeof t != "symbol" ? t + "" : t, e); import { useSyncExternalStore as C } from "react"; const M = () => ({ culture: C( (e) => l.subscribe(e), () => l.getCulture(), () => l.getCulture() ), setCulture: (e) => l.setCulture(e) }); class g { constructor() { i(this, "defaultCulture", ""); i(this, "cultures", []); i(this, "cache", /* @__PURE__ */ new Map()); i(this, "translationCache", /* @__PURE__ */ new Map()); i(this, "listeners", /* @__PURE__ */ new Set()); } def(t, e) { this.mod("_def", t, e); } mod(t, e, u) { let s = this.cache.get(u), n = t; s ? s.get(n) || s.set(n, e) : (s = /* @__PURE__ */ new Map(), s.set(n, e), this.cache.set(u, s)); } translateDef(t, e) { return this.translateMod("_def", t, e); } translateMod(t, e, u) { const s = `${this.defaultCulture}-${t}-${e}`, n = `t:${e}`; if (this.translationCache.has(s)) return this.translationCache.get(s); const a = this.cache.get(this.defaultCulture); if (a) { const c = a.get(t); if (c) { const o = c[e] || n, h = this.applyParams(o, u); return this.translationCache.set(s, h), h; } } return n; } getResourceDef() { const t = this.cache.get(this.defaultCulture); return t == null ? void 0 : t.get("_def"); } getResourceMod(t) { const e = this.cache.get(this.defaultCulture); return e == null ? void 0 : e.get(t); } applyParams(t, e) { return e ? (typeof e == "string" && (e = [e]), t.replace(/{(\d+)}/g, (u, s) => typeof e[s] < "u" ? e[s] : u)) : t; } notify() { this.listeners.forEach((t) => t()); } setCulture(t) { this.defaultCulture = t, this.notify(); } getCulture() { return this.defaultCulture; } subscribe(t) { return this.listeners.add(t), () => this.listeners.delete(t); } } const l = new g(); export { l as i, M as u };