diff --git a/react/providers/I18n/format.jsx b/react/providers/I18n/format.jsx index bb11a0f80..4837b825e 100644 --- a/react/providers/I18n/format.jsx +++ b/react/providers/I18n/format.jsx @@ -6,18 +6,38 @@ import { DEFAULT_LANG } from '.' const locales = {} let lang = DEFAULT_LANG +/** + * Ensure that the locale is in the correct format for date-fns (see 2.0.0 BC https://github.com/date-fns/date-fns/blob/main/CHANGELOG.md#200---2019-08-20) + * @param {string} lang + */ +const ensureLocaleFormat = lang => { + switch (lang) { + case 'en': + return 'en-US' + case 'zh_cn': + return 'zh-CN' + case 'zh_tw': + return 'zh-TW' + default: + return lang + } +} + const getWarningMessage = lang => `The "${lang}" locale isn't supported by date-fns. or has not been included in the build. Check if you have configured a ContextReplacementPlugin that is too restrictive.` export const provideDateFnsLocale = (userLang, defaultLang = DEFAULT_LANG) => { - lang = userLang + lang = ensureLocaleFormat(userLang) + const ensureDefaultLang = ensureLocaleFormat(defaultLang) try { - locales[defaultLang] = require(`date-fns/locale/${defaultLang}/index.js`) + locales[ + ensureDefaultLang + ] = require(`date-fns/locale/${ensureDefaultLang}/index.js`) } catch (err) { - console.warn(getWarningMessage(defaultLang)) + console.warn(getWarningMessage(ensureDefaultLang)) } - if (lang && lang !== defaultLang) { + if (lang && lang !== ensureDefaultLang) { try { locales[lang] = require(`date-fns/locale/${lang}/index.js`) } catch (e) { diff --git a/react/providers/I18n/format.spec.jsx b/react/providers/I18n/format.spec.jsx index 7fed59c4a..2430feb1b 100644 --- a/react/providers/I18n/format.spec.jsx +++ b/react/providers/I18n/format.spec.jsx @@ -10,6 +10,18 @@ describe('initFormat', () => { it('should not throw if a date-fns locale can not be found', () => { expect(() => initFormat('unknown-lang', 'unknown-default')).not.toThrow() }) + + it('should use the correct locale', () => { + const f = initFormat('fr', 'en') + const date = f(0, 'yyyy-LLLL-dd') + expect(date).toBe('1970-janvier-01') + }) + + it('should fallback english if a date-fns locale can not be found', () => { + const f = initFormat('unknown-lang', 'unknown-default') + const date = f(0, 'yyyy-LLLL-dd') + expect(date).toBe('1970-January-01') + }) }) describe('formatLocallyDistanceToNow', () => {