Mara-Li
2024-02-04 dbbc672c67aa5ac0a915d22af5cf44c4e7011aae
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
import en from "./locales/en.json"
import fr from "./locales/fr.json"
 
const TRANSLATION = {
  "en-US": en,
  "fr-FR": fr,
} as const
 
type TranslationOptions = {
  [key: string]: string
}
 
export const i18n = (lang = "en-US", key: string, options?: TranslationOptions) => {
  const locale =
    Object.keys(TRANSLATION).find(
      (key) =>
        key.toLowerCase() === lang.toLowerCase() || key.toLowerCase().includes(lang.toLowerCase()),
    ) ?? "en-US"
  const getTranslation = (key: string) => {
    const keys = key.split(".")
    let translationString: string | Record<string, unknown> =
      TRANSLATION[locale as keyof typeof TRANSLATION]
    keys.forEach((key) => {
      // @ts-ignore
      translationString = translationString[key]
    })
    return translationString
  }
  if (options) {
    let translationString = getTranslation(key).toString()
    Object.keys(options).forEach((key) => {
      translationString = translationString.replace(`{{${key}}}`, options[key])
    })
    return translationString
  }
  return getTranslation(key).toString()
}