ファイル
btrc-hub/frontend/src/lib/locales.ts
T
2026-10-28 20:57:22 +09:00

80 行
2.4 KiB
TypeScript

import { apiGet } from '@/lib/api'
import { currentRenderContext } from '@/lib/renderContext'
import type { To } from 'react-router-dom'
export const SUPPORTED_LOCALES = ['ja', 'ain-Kana'] as const
export type LocaleCode = typeof SUPPORTED_LOCALES[number]
export type AvailableLocale = { code: string; name: string }
export const fetchLocales = (): Promise<{ locales: AvailableLocale[] }> =>
apiGet ('/locales')
export const isLocaleCode = (value: unknown): value is LocaleCode =>
SUPPORTED_LOCALES.some (locale => locale === value)
export const localeLanguage = (locale: LocaleCode): 'ja' | 'ain' =>
locale === 'ja' ? 'ja' : 'ain'
export const localeFromPath = (pathname: string): LocaleCode | null => {
const segment = pathname.split (/[/?#]/)[1]
return isLocaleCode (segment) ? segment : null
}
export const resolveViewingLocale = (
pathname: string,
routeLocale?: unknown,
): LocaleCode =>
isLocaleCode (routeLocale) ? routeLocale : localeFromPath (pathname) ?? 'ja'
export const currentViewingLocale = (): LocaleCode =>
resolveViewingLocale (currentRenderContext ()?.pathname ?? '')
export const unlocalisedPath = (pathname: string): string => {
const locale = localeFromPath (pathname)
return locale == null ? pathname : pathname.slice (locale.length + 1) || '/'
}
export const localiseTo = (to: To, locale: LocaleCode): To => {
const pathname = typeof to === 'string' ? to : to.pathname
if (pathname == null
|| !(pathname.startsWith ('/'))
|| pathname.startsWith ('//')
|| localeFromPath (pathname) != null)
return to
const localised = `/${ locale }${ pathname }`
return typeof to === 'string' ? localised : { ...to, pathname: localised }
}
export const switchLocalePath = (
location: { pathname: string; search: string; hash: string },
locale: LocaleCode,
): string =>
`/${ locale }${ unlocalisedPath (location.pathname) }${ location.search }${ location.hash }`
// Keep automatic selection independent of the page and API route trees.
export const automaticallySelectedLocale = (): LocaleCode => 'ja'
export const legacyLocalePath = (
location: { pathname: string; search: string; hash: string },
isPage: (pathname: string) => boolean = () => false,
): string | null => {
if (localeFromPath (location.pathname) != null || !isPage (location.pathname))
return null
return switchLocalePath (location, automaticallySelectedLocale ())
}