Skip to content
Open
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
27 changes: 27 additions & 0 deletions __tests__/transCore.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down Expand Up @@ -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
})
})
9 changes: 8 additions & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,21 @@ 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
}
keySeparator?: string | false
nsSeparator?: string | false
defaultNS?: string
allowEmptyStrings?: boolean
plurals?: {
fallbackForm?: Intl.LDMLPluralRule
}
}

export interface LoaderConfig extends I18nConfig {
Expand Down
16 changes: 15 additions & 1 deletion src/transCore.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,8 @@ function plural(
options?: {
returnObjects?: boolean
fallback?: string | string[]
}
},
retry = false
): string {
if (!query || typeof query.count !== 'number') return key

Expand All @@ -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
}

Expand Down