Skip to content

Commit

Permalink
fix(Forms): fallback to use default locale for translations when prov…
Browse files Browse the repository at this point in the history
…iding a non-existent locale (#3817)

Fixes #3818

---------

Co-authored-by: Tobias Høegh <tobias@tujo.no>
  • Loading branch information
langz and tujoworker authored Sep 2, 2024
1 parent 8a2da43 commit f768613
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,18 @@ describe('ChildrenWithAge', () => {
)
})

it('should display default translations when providing a non-existent locale to Form.Handler', () => {
render(
<Form.Handler locale="non-existent">
<ChildrenWithAge />
</Form.Handler>
)

expect(document.querySelector('.dnb-p')).toHaveTextContent(
'Antall barn'
)
})

it('should match snapshot', () => {
const generateRef = React.createRef<GenerateRef>()

Expand Down
11 changes: 5 additions & 6 deletions packages/dnb-eufemia/src/shared/Context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,8 @@ export function prepareContext<Props>(
const context = {
...props,
updateTranslation: (locale, newTranslations) => {
context.translation = newTranslations[locale]
context.translation =
newTranslations[locale] || newTranslations[LOCALE]
context.translations = newTranslations

if (context.locales) {
Expand Down Expand Up @@ -309,12 +310,10 @@ function handleLocaleFallbacks(
locale: InternalLocale | AnyLocale,
translations: Translations = {}
) {
if (!translations[locale]) {
if (locale === 'en' || String(locale).split('-')[0] === 'en') {
return 'en-GB'
}
if (locale === 'en' || String(locale).split('-')[0] === 'en') {
return 'en-GB'
}
return locale
return translations[locale] ? locale : LOCALE
}

// If no provider is given, we use the default context from here
Expand Down
18 changes: 18 additions & 0 deletions packages/dnb-eufemia/src/shared/__tests__/Context.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,22 @@ describe('Context', () => {
rerender(<HelpButton lang="en-GB">content</HelpButton>)
expect(screen.queryByLabelText(title_gb)).toBeInTheDocument()
})

it('should support fallback "translation" for non-existent locale', () => {
let translation = undefined

render(
<Provider locale="non-existent">
<Context.Consumer>
{(context) => {
translation = context.translation
return null
}}
</Context.Consumer>
</Provider>
)

expect(translation).not.toBeUndefined()
expect(translation.DatePicker.month).toBe('måned')
})
})

0 comments on commit f768613

Please sign in to comment.