diff --git a/__tests__/transCore.test.js b/__tests__/transCore.test.js index 18fcbe0..736f69e 100644 --- a/__tests__/transCore.test.js +++ b/__tests__/transCore.test.js @@ -25,6 +25,11 @@ const nsWithEmpty = { emptyKey: '', } +const nsWithPlurals = { + key_one: 'one', + key_other: 'other', +} + describe('transCore', () => { test('should return an object of root keys', async () => { const t = transCore({ @@ -153,4 +158,26 @@ describe('transCore', () => { expect(typeof t).toBe('function') expect(t('nsWithEmpty:emptyKey')).toEqual('nsWithEmpty:emptyKey') }) + + test('should use the plural form fallback', () => { + const fallback = 'other' + const pluralRules = new Intl.PluralRules('ro') + + const t = transCore({ + config: { + plurals: { + fallbackForm: fallback, + }, + }, + pluralRules, + allNamespaces: { nsWithPlurals }, + lang: 'ro', + }) + + expect(typeof t).toBe('function') + expect(pluralRules.select(1)).toBe('one') + expect(t('nsWithPlurals:key', { count: 1 })).toBe('one') + expect(pluralRules.select(2)).toBe('few') + expect(t('nsWithPlurals:key', { count: 2 })).toBe(fallback) // Uses `other` instead of `few` since `few` doesn't exist as key + }) }) diff --git a/src/index.tsx b/src/index.tsx index a0cbdce..0f10afb 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -74,7 +74,11 @@ export interface I18nConfig extends NextI18nConfig { revalidate?: number pagesInDir?: string interpolation?: { - format?: (value: TranslationQuery[string], format: any, lang: string | undefined) => string + format?: ( + value: TranslationQuery[string], + format: any, + lang: string | undefined + ) => string prefix?: string suffix?: string } @@ -82,6 +86,9 @@ export interface I18nConfig extends NextI18nConfig { nsSeparator?: string | false defaultNS?: string allowEmptyStrings?: boolean + plurals?: { + fallbackForm?: Intl.LDMLPluralRule + } } export interface LoaderConfig extends I18nConfig { diff --git a/src/transCore.tsx b/src/transCore.tsx index 9f06cdd..8ee42c0 100644 --- a/src/transCore.tsx +++ b/src/transCore.tsx @@ -187,7 +187,8 @@ function plural( options?: { returnObjects?: boolean fallback?: string | string[] - } + }, + retry = false ): string { if (!query || typeof query.count !== 'number') return key @@ -207,6 +208,19 @@ function plural( if (getDicValue(dic, nestedKey, config, options) !== undefined) return nestedKey + if (config.plurals?.fallbackForm && !retry) { + const fallbackForm = config.plurals.fallbackForm + return plural( + Object.assign(pluralRules, { select: () => fallbackForm }), + dic, + key, + config, + query, + options, + true + ) + } + return key }