w-aura/src/locales/index.ts
2024-08-28 17:08:52 +00:00

87 lines
2.8 KiB
TypeScript

import { Translation } from '@/api/resources/Translations.ts'
import { createApi, Translations } from '../api'
import dev from './dev.ts'
import locales from './locales.ts'
// export const getClientLocale = () => {
// return navigator.language
// }
export const getClientLocale = async () => {
const api = createApi();
try {
const resp = await api.getLocale(undefined)
if (resp?.error || !resp?.languages?.length) {
return navigator.language
}
if (resp.country_code === "IN") {
return "hi"
}
return resp.languages.split(',')[0]
} catch (error) {
return navigator.language
}
}
export const getClientTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone
export const language = await getClientLocale()
export const fallbackLng = 'en'
const omitKeys = ['href', 'title', 'url_slug', 'type']
// const isWeb = (group: Elements.ElementGroup) => group.name === 'web'
const cleanUp = (translation: Partial<Translation[]> = []) => {
return translation
.filter((trans) => !omitKeys.includes(trans?.key || ''))
.reduce((acc, trans) => ({ ...acc, [trans?.key || '']: trans?.value || '' }), {})
}
export const getDefaultLocaleByLanguage = (locale: string) => {
const language = locale.split('-')[0];
if (locale in locales) {
return locale;
}
if (language in locales) {
return language;
}
return fallbackLng;
}
export enum ELocalesPlacement {
V0 = "v0", // Main site version
V1 = "v1",
}
interface ITranslationJSON {
male: { [key: string]: string }
female: { [key: string]: string }
default: { [key: string]: string }
}
export const getTranslationJSON = async (placement: ELocalesPlacement | undefined, language: string): Promise<ITranslationJSON> => {
const protocol = window.location.protocol;
const host = window.location.host;
const defaultLanguage = getDefaultLocaleByLanguage(language).toLowerCase();
const localePlacement = placement || ELocalesPlacement.V1
let result;
try {
const responseMale = await fetch(`${protocol}//${host}/locales/${localePlacement}/${defaultLanguage}/male_${defaultLanguage}.json`)
const resultMale = await responseMale.json()
const responseFemale = await fetch(`${protocol}//${host}/locales/${localePlacement}/${defaultLanguage}/female_${defaultLanguage}.json`)
const resultFemale = await responseFemale.json()
result = { male: resultMale, female: resultFemale, default: resultMale }
} catch (error) {
result = await getTranslationJSON(localePlacement, fallbackLng)
}
return result;
}
export const buildResources = (resp: Translations.Response, translationJSON: ITranslationJSON) => {
const element = resp.translations
const translation = cleanUp(element)
return {
[getDefaultLocaleByLanguage(language)]: {
translation: {
...translation, ...dev.translation, ...translationJSON
}
},
}
}