import { computed, inject } from 'vue' import { FDS_VUE_CORE_I18N_KEY, type FdsI18nLike } from './i18n' type FdsDictionary = Record type FdsInterpolationValues = Record type FdsTranslationModule = { default: FdsDictionary } const translationModules = import.meta.glob('../lang/*.json', { eager: true }) const translations = Object.entries(translationModules).reduce>((acc, [path, mod]) => { const fileName = path.split('/').pop() const languageCode = fileName?.replace('.json', '') if (languageCode) { acc[languageCode] = mod.default } return acc }, {}) export const useFdsI18n = () => { const i18n = inject(FDS_VUE_CORE_I18N_KEY, undefined) const locale = computed(() => { const locale = i18n?.global?.locale ?? i18n?.locale if (typeof locale === 'string') return locale if (locale && typeof locale === 'object' && 'value' in locale && typeof locale.value === 'string') { return locale.value } return 'sv-SE' }) const activeLanguage = computed(() => locale.value.toLowerCase().split('-')[0]) const dictionary = computed(() => { const currentDictionary = translations[activeLanguage.value] return currentDictionary ?? translations.sv ?? {} }) const interpolate = (message: string, values?: FdsInterpolationValues): string => { if (!values) return message return Object.entries(values).reduce((acc, [name, value]) => acc.split(`{${name}}`).join(String(value)), message) } /** Suppress intlify "Not found key" when falling back to fds-vue-core bundled messages. */ const silentTranslateOptions = { missingWarn: false, fallbackWarn: false } as const const translateFromDictionary = (key: string, values?: FdsInterpolationValues): string | undefined => { const value = dictionary.value[key] if (typeof value !== 'string') return undefined return interpolate(value, values) } const t = (key: string, values?: FdsInterpolationValues): string => { const translateFn = i18n?.global?.t ?? i18n?.t const hasKeyFn = i18n?.global?.te ?? i18n?.te if (typeof translateFn === 'function') { let translated: unknown if (values != null && Object.keys(values).length > 0) { translated = translateFn(key, values as Record, silentTranslateOptions) } else { // Second arg is default when missing; empty default + silent opts avoids console noise. translated = translateFn(key, '', silentTranslateOptions) } if (typeof translated === 'string' && translated !== '') { // If key exists in i18n, translated value is authoritative (even when value === key in "show keys" mode). if (typeof hasKeyFn === 'function' && hasKeyFn(key)) { return translated } } if (typeof translated === 'string' && translated !== key && translated !== '') { return translated } } return translateFromDictionary(key, values) ?? key } const tCore = (key: string, values?: FdsInterpolationValues): string => translateFromDictionary(key, values) ?? key return { i18n, locale, t, tCore, } }