Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Ensure use correct format locales #2731

Merged
merged 1 commit into from
Dec 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading