Skip to content

Commit

Permalink
fix: Ensure use correct format locales
Browse files Browse the repository at this point in the history
Following version 115.0.0, the format of 3 locales has changed:
- `en -> en-US`
- `zh_cn -> zh-CN`
- `zh_tw -> zh-TW`

More details here:
https://github.com/date-fns/date-fns/blob/main/CHANGELOG.md#200---2019-08-20

The constant `DEFAULT_LANG=“en”` is not changed
because it is used by Polyglot, which must not change.
This is directly related to the folder names in our apps..
  • Loading branch information
Merkur39 committed Dec 20, 2024
1 parent 8b5fb70 commit 5d078db
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
28 changes: 24 additions & 4 deletions react/providers/I18n/format.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
12 changes: 12 additions & 0 deletions react/providers/I18n/format.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down

0 comments on commit 5d078db

Please sign in to comment.