-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
82 lines (69 loc) · 1.94 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { createDefineTranslationsConfig } from "@wluwd/t";
import { NoLocaleSet, NoTranslationsSet } from "@wluwd/t-utils";
import delve from "dlv";
import { atom, getDefaultStore, useAtomValue } from "jotai";
import { useMemo } from "react";
const $locale = atom<string | undefined>(undefined);
const defaultStore = getDefaultStore();
export const defineTranslationsConfig = createDefineTranslationsConfig(false, {
locale: {
// biome-ignore lint/style/noNonNullAssertion: the value should be set
fn: ["getLocale", () => () => defaultStore.get($locale)!],
// biome-ignore lint/style/noNonNullAssertion: the value should be set
hook: ["useLocale", () => () => useAtomValue($locale)!],
setter: [
"setLocale",
() => (locale) => {
defaultStore.set($locale, locale);
},
],
},
resources: {
cache: new Map(),
loaders: new Map(),
},
translations: {
fn: [
"getTranslations",
(loader, resources) => async (prefix) => {
const locale = defaultStore.get($locale);
return delve(await loader(locale, resources), prefix);
},
],
hook: [
"useTranslations",
(loader, resources) => {
const $translations = atom((get) => {
const locale = get($locale);
return loader(locale, resources);
});
return (prefix) => {
const translations = useAtomValue($translations);
return useMemo(
() => delve(translations, prefix),
[prefix, translations],
);
};
},
],
loader: async (locale, { cache, loaders }) => {
if (locale === undefined) {
throw new NoLocaleSet();
}
let translations = cache.get(locale);
if (translations !== undefined) {
return translations;
}
const loader = loaders.get(locale);
if (loader === undefined) {
throw new NoTranslationsSet({
availableLocales: Array.from(loaders.keys()),
desiredLocale: locale,
});
}
translations = await loader();
cache.set(locale, translations);
return translations;
},
},
});