Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/nice-seahorses-protect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@scaleway/use-i18n": minor
---

Add a non async loadDateLocal possibility
70 changes: 41 additions & 29 deletions packages/use-i18n/src/__tests__/usei18n.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
jest,
} from '@jest/globals'
import { act, renderHook, waitFor } from '@testing-library/react'
import { enGB, fr as frDateFns } from 'date-fns/locale'
import mockdate from 'mockdate'
import type { ReactNode } from 'react'
import I18n, { useI18n, useTranslation } from '..'
Expand Down Expand Up @@ -35,7 +36,7 @@ const defaultSupportedLocales = ['en', 'fr', 'es']

const wrapper =
({
loadDateLocale = async (locale: string) => {
loadDateLocaleAsync = async (locale: string) => {
if (locale === 'en') {
return (await import('date-fns/locale/en-GB')).enGB
}
Expand All @@ -49,6 +50,16 @@ const wrapper =

return (await import(`date-fns/locale/en-GB`)).enGB
},
loadDateLocale = (locale: string) => {
if (locale === 'en') {
return enGB
}
if (locale === 'fr') {
return frDateFns
}

return enGB
},
defaultLoad = async ({ locale }: { locale: string }) =>
import(`./locales/${locale}.json`),
defaultLocale = 'en',
Expand All @@ -61,6 +72,7 @@ const wrapper =
({ children }: { children: ReactNode }) => (
<I18n
loadDateLocale={loadDateLocale}
loadDateLocaleAsync={loadDateLocaleAsync}
defaultLoad={defaultLoad}
defaultLocale={defaultLocale}
defaultTranslations={defaultTranslations}
Expand Down Expand Up @@ -271,6 +283,33 @@ describe('i18n hook', () => {
})
})

it('should work with a component', async () => {
const { result } = renderHook(
() => useTranslation<{ 'with.identifier': 'Hello {identifier}' }>([]),
{
wrapper: wrapper({ defaultLocale: 'en' }),
},
)
const CustomComponent = ({ children }: { children: ReactNode }) => (
<p style={{ fontWeight: 'bold' }}>{children}</p>
)

await waitFor(() => {
expect(
result.current.t('with.identifier', { identifier: <b>My resource</b> }),
).toEqual(['Are you sure you want to delete ', <b>My resource</b>, '?'])
expect(
result.current.t('with.identifier', {
identifier: <CustomComponent>My resource</CustomComponent>,
}),
).toEqual([
'Are you sure you want to delete ',
<CustomComponent>My resource</CustomComponent>,
'?',
])
})
})

describe('getCurrentLocale', () => {
it('should set current locale from localStorage', async () => {
jest.spyOn(global, 'navigator', 'get').mockReturnValueOnce({
Expand Down Expand Up @@ -765,7 +804,7 @@ describe('i18n hook', () => {

await waitFor(() => {
expect(result.current.currentLocale).toEqual('fr')
expect(mockGetItem).toHaveBeenCalledTimes(2)
expect(mockGetItem).toHaveBeenCalledTimes(1)
expect(mockGetItem).toHaveBeenCalledWith(LOCALE_ITEM_STORAGE)
})

Expand All @@ -777,31 +816,4 @@ describe('i18n hook', () => {
localStorageMock.mockRestore()
})
})

it('should work with a component', async () => {
const { result } = renderHook(
() => useTranslation<{ 'with.identifier': 'Hello {identifier}' }>([]),
{
wrapper: wrapper({ defaultLocale: 'en' }),
},
)
const CustomComponent = ({ children }: { children: ReactNode }) => (
<p style={{ fontWeight: 'bold' }}>{children}</p>
)

await waitFor(() => {
expect(
result.current.t('with.identifier', { identifier: <b>My resource</b> }),
).toEqual(['Are you sure you want to delete ', <b>My resource</b>, '?'])
expect(
result.current.t('with.identifier', {
identifier: <CustomComponent>My resource</CustomComponent>,
}),
).toEqual([
'Are you sure you want to delete ',
<CustomComponent>My resource</CustomComponent>,
'?',
])
})
})
})
16 changes: 11 additions & 5 deletions packages/use-i18n/src/usei18n.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,8 @@ type LoadTranslationsFn = ({
locale: string
}) => Promise<{ default: BaseLocale }>

type LoadLocaleFn = (locale: string) => Promise<DateFnsLocale>
type LoadLocaleFn = (locale: string) => DateFnsLocale
type LoadLocaleFnAsync = (locale: string) => Promise<DateFnsLocale>
type LoadDateLocaleError = (error: Error) => void

const initialDefaultTranslations = {}
Expand All @@ -195,13 +196,15 @@ const I18nContextProvider = ({
enableDebugKey = false,
enableDefaultLocale = false,
loadDateLocale,
loadDateLocaleAsync,
localeItemStorage = LOCALE_ITEM_STORAGE,
onLoadDateLocaleError,
supportedLocales,
}: {
children: ReactNode
defaultLoad: LoadTranslationsFn
loadDateLocale: LoadLocaleFn
loadDateLocale?: LoadLocaleFn
loadDateLocaleAsync: LoadLocaleFnAsync
onLoadDateLocaleError?: LoadDateLocaleError
defaultLocale: string
defaultTranslations: TranslationsByLocales
Expand All @@ -216,14 +219,17 @@ const I18nContextProvider = ({
const [translations, setTranslations] =
useState<TranslationsByLocales>(defaultTranslations)
const [namespaces, setNamespaces] = useState<string[]>([])

const [dateFnsLocale, setDateFnsLocale] = useState<DateFnsLocale | undefined>(
undefined,
loadDateLocale?.(currentLocale) ?? undefined,
)

const loadDateFNS = loadDateLocale ?? loadDateLocaleAsync

const setDateFns = useCallback(
async (locale: string) => {
try {
const dateFns = await loadDateLocale(locale)
const dateFns = await loadDateFNS(locale)
setDateFnsLocale(dateFns)
} catch (err) {
if (err instanceof Error && onLoadDateLocaleError) {
Expand All @@ -233,7 +239,7 @@ const I18nContextProvider = ({
setDateFnsLocale(dateFnsLocale)
}
},
[loadDateLocale, setDateFnsLocale, onLoadDateLocaleError, dateFnsLocale],
[loadDateFNS, setDateFnsLocale, onLoadDateLocaleError, dateFnsLocale],
)

/**
Expand Down