update
Some checks failed
deploy / deploy (push) Has been cancelled

This commit is contained in:
toom1996
2026-08-16 20:51:04 +08:00
parent 781242ede0
commit efd28d59e7
13 changed files with 512 additions and 782 deletions

View File

@ -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;
}
}
/**