Skip to content

Commit

Permalink
fix: put list format in try/catch block
Browse files Browse the repository at this point in the history
  • Loading branch information
cngonzalez committed Mar 28, 2024
1 parent 9a2d009 commit f17270d
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 10 deletions.
13 changes: 11 additions & 2 deletions packages/sanity/src/core/hooks/useListFormat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ export interface UseListFormatOptions {
* @public
*/
export function useListFormat(options: UseListFormatOptions = {}): Intl.ListFormat {
const currentLocale = useCurrentLocale().id
return intlCache.listFormat(currentLocale, options)
/*
* Certain components using this hook (such as the <Translate/> in toasts)
* may not have access to the LocaleProvider that lets us use useCurrentLocale.
* In that case, we fall back to a default, unobstrusive list format.
*/
try {
const currentLocale = useCurrentLocale().id
return intlCache.listFormat(currentLocale, options)
} catch {
return new Intl.ListFormat('en-US', {...options, style: 'narrow'})
}
}
9 changes: 2 additions & 7 deletions packages/sanity/src/core/i18n/Translate.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {type TFunction} from 'i18next'
import {type ComponentType, createElement, type ReactNode, useMemo} from 'react'

import {useListFormat} from '../hooks/useListFormat'
import {type CloseTagToken, simpleParser, type TextToken, type Token} from './simpleParser'

const COMPONENT_NAME_RE = /^[A-Z]/
Expand Down Expand Up @@ -108,13 +109,7 @@ export function Translate(props: TranslationProps) {
})

const tokens = useMemo(() => simpleParser(translated), [translated])

/*
* defaulting to en-US for now, since invoking useListFormat (which would be aware of locale)
* in certain contexts will throw an error. In the future, we can consider passing the locale
* or changing the provider order to allow for this.
*/
const listFormat = new Intl.ListFormat('en-US', {style: 'narrow'})
const listFormat = useListFormat()
const formatters: FormatterFns = {
list: (listValues) => listFormat.format(listValues),
}
Expand Down
2 changes: 1 addition & 1 deletion packages/sanity/src/core/i18n/__tests__/Translate.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ describe('Translate component', () => {
{wrapper},
)
expect(await findByTestId('output')).toHaveTextContent(
'3 people signed up: Bjørge, Rita, Espen',
'3 people signed up: Bjørge, Rita, and Espen',
)
})
})

0 comments on commit f17270d

Please sign in to comment.