1 import { addLocale as ttagAddLocale, useLocale as ttagUseLocale } from 'ttag';
3 import { DEFAULT_LOCALE } from '../constants';
4 import type { TtagLocaleMap } from '../interfaces/Locale';
5 import type { Options } from './dateFnLocale';
6 import { getDateFnLocaleWithLongFormat, getDateFnLocaleWithSettings } from './dateFnLocale';
7 import dateFnLocales from './dateFnLocales';
8 import { getClosestLocaleMatch, getLangAttribute, getLanguageCode } from './helper';
9 import { setDateLocales, setLocales } from './index';
11 export const loadLocale = async (localeCode: string, locales: TtagLocaleMap) => {
12 const languageCode = getLanguageCode(localeCode);
14 if (localeCode !== DEFAULT_LOCALE) {
15 const getLocaleData = locales[localeCode];
17 throw new Error('No locale data for requested localeCode');
19 const data = await getLocaleData();
20 ttagAddLocale(localeCode, data);
22 ttagUseLocale(localeCode);
29 if (typeof document !== 'undefined') {
30 document.documentElement.lang = getLangAttribute(localeCode);
34 export const loadDateLocale = async (localeCode: string, browserLocaleCode?: string, options?: Options) => {
35 const closestLocaleCode = getClosestLocaleMatch(localeCode, dateFnLocales) || DEFAULT_LOCALE;
36 const closestBrowserLocaleCode = getClosestLocaleMatch(browserLocaleCode, dateFnLocales) || DEFAULT_LOCALE;
37 const [dateFnLocale, browserDateFnLocale] = await Promise.all([
38 dateFnLocales[closestLocaleCode](),
39 dateFnLocales[closestBrowserLocaleCode](),
41 const mergedDateLocale = getDateFnLocaleWithLongFormat(dateFnLocale, browserDateFnLocale);
42 const updatedDateFnLocale = getDateFnLocaleWithSettings(mergedDateLocale, options);
45 defaultDateLocale: dateFnLocale,
46 browserDateLocale: browserDateFnLocale,
47 browserLocaleCode: closestBrowserLocaleCode,
48 dateLocale: updatedDateFnLocale,
49 dateLocaleCode: closestLocaleCode,
52 return updatedDateFnLocale;