@ -1,35 +1,19 @@
|
||||
import {
|
||||
DEFAULT_LOCALE,
|
||||
LOCALES,
|
||||
PREFIX_DEFAULT_LOCALE,
|
||||
isLocaleSegment,
|
||||
type Locale,
|
||||
} from './config';
|
||||
import { getLocaleByPath } from 'astro:i18n';
|
||||
import { DEFAULT_LOCALE, LOCALES, type Locale } from './config';
|
||||
import { translate } from './dictionary';
|
||||
|
||||
/**
|
||||
* 从当前 URL 解析语言:
|
||||
* - 路径首段若是支持的语言前缀(如 /cn/shows → cn)则用之;
|
||||
* - 否则回退到默认语言(en)。
|
||||
* 从 URL 解析语言,委托 Astro 内置的 astro:i18n.getLocaleByPath。
|
||||
* 无前缀(默认语言)路径会解析回 DEFAULT_LOCALE。
|
||||
*/
|
||||
export function getLocaleFromUrl(url: URL | string): Locale {
|
||||
const pathname = typeof url === 'string' ? url : url.pathname;
|
||||
const seg = pathname.split('/').filter(Boolean)[0];
|
||||
return isLocaleSegment(seg) ? seg : DEFAULT_LOCALE;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成带语言前缀的链接。
|
||||
* - en(默认且 PREFIX_DEFAULT_LOCALE=false)→ /shows
|
||||
* - cn → /cn/shows
|
||||
* 第二个参数可指定目标语言,方便做语言切换器。
|
||||
*/
|
||||
export function useTranslatedPath(locale: Locale) {
|
||||
return (path: string, targetLocale: Locale = locale): string => {
|
||||
const clean = path.startsWith('/') ? path : `/${path}`;
|
||||
if (targetLocale === DEFAULT_LOCALE && !PREFIX_DEFAULT_LOCALE) return clean;
|
||||
return `/${targetLocale}${clean}`;
|
||||
};
|
||||
try {
|
||||
const locale = getLocaleByPath(pathname);
|
||||
return (LOCALES as readonly string[]).includes(locale) ? (locale as Locale) : DEFAULT_LOCALE;
|
||||
} catch {
|
||||
return DEFAULT_LOCALE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user