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, { getDateFnLocale } from './dateFnLocales';
8 import { getClosestLocaleMatch, getLangAttribute, getLanguageCode } from './helper';
9 import { setDateLocales, setLocales } from './index';
11 export const willLoadLocale = (localeCode: string) => {
12 return localeCode !== DEFAULT_LOCALE;
15 export const loadLocale = async (localeCode: string, locales: TtagLocaleMap) => {
16 const languageCode = getLanguageCode(localeCode);
18 if (localeCode !== DEFAULT_LOCALE) {
19 const getLocaleData = locales[localeCode];
21 throw new Error('No locale data for requested localeCode');
23 const data = await getLocaleData();
24 ttagAddLocale(localeCode, data);
26 ttagUseLocale(localeCode);
33 if (typeof document !== 'undefined') {
34 document.documentElement.lang = getLangAttribute(localeCode);
38 export const loadDateLocale = async (localeCode: string, browserLocaleCode?: string, options?: Options) => {
39 const closestLocaleCode = getClosestLocaleMatch(localeCode, dateFnLocales) || DEFAULT_LOCALE;
40 const closestBrowserLocaleCode = getClosestLocaleMatch(browserLocaleCode, dateFnLocales) || DEFAULT_LOCALE;
41 const [dateFnLocale, browserDateFnLocale] = await Promise.all([
42 getDateFnLocale(closestLocaleCode),
43 getDateFnLocale(closestBrowserLocaleCode),
45 const mergedDateLocale = getDateFnLocaleWithLongFormat(dateFnLocale, browserDateFnLocale);
46 const updatedDateFnLocale = getDateFnLocaleWithSettings(mergedDateLocale, options);
49 defaultDateLocale: dateFnLocale,
50 browserDateLocale: browserDateFnLocale,
51 browserLocaleCode: closestBrowserLocaleCode,
52 dateLocale: updatedDateFnLocale,
53 dateLocaleCode: closestLocaleCode,
56 return updatedDateFnLocale;