Repository URL to install this package:
|
Version:
5.0.0-rc.9 ▾
|
import { importIntl, importLocaleData, importMessages } from './import';
import cookie from './cookie';
import { normalizeLocale, getLanguageCodeFromLocale, getNavigatorLocale } from './utils';
/**
* Get a locale for the user that is supported
*
* It considers normalized locales from
* - the cookie (first full locale, then extracted language)
* - the navigator locale (first full, then extracted language)
* - default: 'en'
*
* and returns the first match in the normalized supported locales
*
* @param {string[]} supportedLocales
* @returns {string} normalized locale which is supported (or 'en')
*/
export const getLocale = supportedLocales => {
const cookieLocale = normalizeLocale(cookie.get('locale'));
const navigatorLocale = normalizeLocale(getNavigatorLocale());
const normalizedSuppportedLocales = supportedLocales.map(locale => normalizeLocale(locale));
const desiredLocales = [
cookieLocale,
getLanguageCodeFromLocale(cookieLocale),
navigatorLocale,
getLanguageCodeFromLocale(navigatorLocale),
'en',
];
const matchedLocale = desiredLocales.reduce((result, desiredLocale) => {
if (!result && normalizedSuppportedLocales.includes(desiredLocale)) {
return desiredLocale;
}
return result;
}, false);
return matchedLocale || 'en';
};
/**
* Initialise I18n asynchronously
* - determine locale
* - load Intl polyfill (only executed when window.Intl is not present)
* - load `react-intl` locale data if not english locale
* - load translation messages if not english
*
* It returns a promise that will always resolve: errors are caught internally, and a default language is returned
*
* @async
* @returns {Promise<object>} Resolves to an object with locale, locale data (optional) and translation messages (optional)
*/
export default async function initI18n({ supportedLocales = ['en'] } = {}) {
try {
const locale = getLocale(supportedLocales);
const imports = [importIntl()];
if (locale !== 'en') {
imports.push(importLocaleData(locale), importMessages(locale));
}
const [, localeData, messages] = await Promise.all(imports);
return {
locale,
localeData,
messages,
};
} catch (error) {
return {
locale: 'en',
};
}
}