From 9138dc28206875372da4fb74c64716437cd11b95 Mon Sep 17 00:00:00 2001 From: Johan Linderoth Date: Mon, 28 Feb 2022 13:31:35 +0100 Subject: [PATCH] feat: Fallback to language only locale + support uppercase locales (#1524) * Support uppercase region as in xx-ZZ + fallback to xx if xx-yy does not exist * code review fix, split preset just once * review fixes + don't recurse if split length is 1 Co-authored-by: Johan Linderoth --- src/index.js | 13 +++++++++---- test/plugin/localizedFormat.test.js | 10 ++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/index.js b/src/index.js index 8c919b0d8..c965dd004 100644 --- a/src/index.js +++ b/src/index.js @@ -12,12 +12,17 @@ const parseLocale = (preset, object, isLocal) => { let l if (!preset) return L if (typeof preset === 'string') { - if (Ls[preset]) { - l = preset + const presetLower = preset.toLowerCase() + if (Ls[presetLower]) { + l = presetLower } if (object) { - Ls[preset] = object - l = preset + Ls[presetLower] = object + l = presetLower + } + const presetSplit = preset.split('-') + if (!l && presetSplit.length > 1) { + return parseLocale(presetSplit[0]) } } else { const { name } = preset diff --git a/test/plugin/localizedFormat.test.js b/test/plugin/localizedFormat.test.js index 1c7a89e14..da5b219e0 100644 --- a/test/plugin/localizedFormat.test.js +++ b/test/plugin/localizedFormat.test.js @@ -96,6 +96,16 @@ it('Uses the localized lowercase formats if defined', () => { ['l', 'll', 'lll', 'llll'].forEach(option => expect(znDate.format(option)).toBe(znDate.format(znCn.formats[option]))) }) +it('Uses fallback to xx if xx-yy not available', () => { + expect(dayjs('2019-02-01').locale('en-yy').format('MMMM')) + .toBe('February') +}) + +it('Uses xx-yy if xx-YY is provided', () => { + expect(dayjs('2019-02-01').locale('es-US').format('MMMM')) + .toBe('febrero') +}) + it('Uses the localized uppercase formats as a base for lowercase formats, if not defined', () => { const date = new Date() const spanishDate = dayjs(date, { locale: es });