(namespaces: string | Array<string>)
| 4 | // The idea of this component is to mimic a popular i18n library (i18next) |
| 5 | // so that we can set ourselves up to transition to it (or a similar library) in the future |
| 6 | export const useTranslation = (namespaces: string | Array<string>) => { |
| 7 | const { data } = useMainContext() |
| 8 | |
| 9 | // this can eventually be an object constructed from the input namespaces param above, but for now everything is already loaded |
| 10 | const loadedData: any = data.ui |
| 11 | |
| 12 | return { |
| 13 | // The compiled string supports prefixing with a namespace such as `my-namespace:path.to.value` |
| 14 | t: (strings: TemplateStringsArray | string, ...values: Array<any>) => { |
| 15 | const key = typeof strings === 'string' ? strings : String.raw(strings, ...values) |
| 16 | |
| 17 | const splitKey = key.split(':') |
| 18 | if (splitKey.length > 2) { |
| 19 | throw new Error('Multiple ":" not allowed in translation lookup path') |
| 20 | } |
| 21 | |
| 22 | if (splitKey.length === 2) { |
| 23 | const [namespace, path] = splitKey |
| 24 | return get(loadedData[namespace], path) |
| 25 | } |
| 26 | |
| 27 | const [path] = splitKey |
| 28 | if (Array.isArray(namespaces)) { |
| 29 | for (const namespace of namespaces) { |
| 30 | const val = get(loadedData[namespace], path) |
| 31 | if (val !== undefined) { |
| 32 | return val |
| 33 | } |
| 34 | } |
| 35 | return undefined |
| 36 | } else { |
| 37 | return get(loadedData[namespaces], path) |
| 38 | } |
| 39 | }, |
| 40 | } |
| 41 | } |
no test coverage detected