|
|
import { defaultI18n } from '@wordpress/i18n'; |
|
|
import { I18nProvider as WPI18nProvider } from '@wordpress/react-i18n'; |
|
|
import { useEffect, useState, type PropsWithChildren } from 'react'; |
|
|
import { useAuth } from './auth'; |
|
|
|
|
|
async function fetchLocaleData( language: string, signal: AbortSignal ) { |
|
|
if ( language === 'en' ) { |
|
|
return [ language, undefined ]; |
|
|
} |
|
|
|
|
|
try { |
|
|
const response = await fetch( |
|
|
`https://widgets.wp.com/languages/calypso/${ language }-v1.1.json`, |
|
|
{ signal } |
|
|
); |
|
|
|
|
|
return [ language, await response.json() ]; |
|
|
} catch ( error ) { |
|
|
|
|
|
if ( error instanceof Error && error.name === 'AbortError' ) { |
|
|
throw error; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
return [ 'en', undefined ]; |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function useLocaleSlug() { |
|
|
const { user } = useAuth(); |
|
|
return user.locale_variant || user.language || 'en'; |
|
|
} |
|
|
|
|
|
export function I18nProvider( { children }: PropsWithChildren ) { |
|
|
const language = useLocaleSlug(); |
|
|
const [ loadedLocale, setLoadedLocale ] = useState< string | null >( null ); |
|
|
|
|
|
const i18n = defaultI18n; |
|
|
|
|
|
useEffect( () => { |
|
|
const abortController = new AbortController(); |
|
|
|
|
|
fetchLocaleData( language, abortController.signal ) |
|
|
.then( ( [ realLanguage, data ] ) => { |
|
|
i18n.resetLocaleData( data ); |
|
|
|
|
|
|
|
|
setLoadedLocale( realLanguage ); |
|
|
} ) |
|
|
.catch( () => { |
|
|
|
|
|
} ); |
|
|
|
|
|
return () => { |
|
|
abortController.abort(); |
|
|
}; |
|
|
}, [ i18n, language ] ); |
|
|
|
|
|
|
|
|
|
|
|
if ( loadedLocale === null ) { |
|
|
return null; |
|
|
} |
|
|
|
|
|
return <WPI18nProvider i18n={ i18n } children={ children } />; |
|
|
} |
|
|
|