forked from anomalyco/opencode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathi18n.tsx
More file actions
38 lines (30 loc) · 1.02 KB
/
Copy pathi18n.tsx
File metadata and controls
38 lines (30 loc) · 1.02 KB
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
import { createContext, useContext, type Accessor, type ParentProps } from "solid-js"
import { dict as en } from "../i18n/en"
export type UiI18nKey = keyof typeof en
export type UiI18nParams = Record<string, string | number | boolean>
export type UiI18n = {
locale: Accessor<string>
t: (key: UiI18nKey, params?: UiI18nParams) => string
}
function resolveTemplate(text: string, params?: UiI18nParams) {
if (!params) return text
return text.replace(/{{\s*([^}]+?)\s*}}/g, (_, rawKey) => {
const key = String(rawKey)
const value = params[key]
return value === undefined ? "" : String(value)
})
}
const fallback: UiI18n = {
locale: () => "en",
t: (key, params) => {
const value = en[key] ?? String(key)
return resolveTemplate(value, params)
},
}
const Context = createContext<UiI18n>(fallback)
export function I18nProvider(props: ParentProps<{ value: UiI18n }>) {
return <Context.Provider value={props.value}>{props.children}</Context.Provider>
}
export function useI18n() {
return useContext(Context)
}