1 import { addLocale as ttagAddLocale, useLocale as ttagUseLocale } from 'ttag';
3 import { DEFAULT_LOCALE } from '../constants';
4 import type { Options } from './dateFnLocale';
5 import { getBrowserLocale, getClosestLocaleCode } from './helper';
15 import { loadDateLocale } from './loadLocale';
16 import { locales } from './locales';
18 export const relocalizeText = async ({
24 getLocalizedText: () => string;
25 newLocaleCode?: string;
26 relocalizeDateFormat?: boolean;
27 userSettings?: Options;
29 const currentLocaleCode = localeCode;
31 currentDefaultDateLocale,
32 currentBrowserDateLocale,
33 currentBrowserLocaleCode,
35 currentDateLocaleCode,
36 ] = [defaultDateLocale, browserDateLocale, browserLocaleCode, dateLocale, dateLocaleCode];
37 if (!newLocaleCode || newLocaleCode === currentLocaleCode) {
38 return getLocalizedText();
41 const newSafeLocaleCode = getClosestLocaleCode(newLocaleCode, locales);
42 const useDefaultLocale = newSafeLocaleCode === DEFAULT_LOCALE;
43 const [newTtagLocale] = await Promise.all([
44 useDefaultLocale ? undefined : locales[newSafeLocaleCode]?.(),
45 relocalizeDateFormat ? loadDateLocale(newSafeLocaleCode, getBrowserLocale(), userSettings) : undefined,
47 if (!useDefaultLocale && !newTtagLocale) {
48 throw new Error('No locale data for requested localeCode');
51 ttagAddLocale(newSafeLocaleCode, newTtagLocale);
53 ttagUseLocale(newSafeLocaleCode);
54 return getLocalizedText();
56 return getLocalizedText();
58 ttagUseLocale(currentLocaleCode);
60 defaultDateLocale: currentDefaultDateLocale,
61 browserDateLocale: currentBrowserDateLocale,
62 browserLocaleCode: currentBrowserLocaleCode,
63 dateLocale: currentDateLocale,
64 dateLocaleCode: currentDateLocaleCode,