28 行
846 B
TypeScript
28 行
846 B
TypeScript
import { useCallback } from 'react'
|
|
import { useLocation, useNavigate, useParams } from 'react-router-dom'
|
|
|
|
import { isLocaleCode, localeFromPath, localiseTo } from '@/lib/locales'
|
|
|
|
import type { NavigateFunction, NavigateOptions, To } from 'react-router-dom'
|
|
|
|
import type { LocaleCode } from '@/lib/locales'
|
|
|
|
|
|
export const useLocale = (): LocaleCode => {
|
|
const { locale } = useParams ()
|
|
const location = useLocation ()
|
|
return isLocaleCode (locale) ? locale : localeFromPath (location.pathname) ?? 'ja'
|
|
}
|
|
|
|
|
|
export const useLocaleNavigate = (): NavigateFunction => {
|
|
const navigate = useNavigate ()
|
|
const locale = useLocale ()
|
|
return useCallback ((to: To | number, options?: NavigateOptions) => {
|
|
if (typeof to === 'number')
|
|
navigate (to)
|
|
else
|
|
navigate (localiseTo (to, locale), options)
|
|
}, [locale, navigate])
|
|
}
|