From 7af0886d9cc9cd05ca87aa9bb94c637ac3bf31f2 Mon Sep 17 00:00:00 2001 From: grassblock Date: Sun, 20 Jul 2025 21:56:57 +0800 Subject: [PATCH] feat: init i18n features --- .../helper/i18n/LanguagePicker.astro | 14 ++++++++++++++ src/i18n/ui.ts | 19 +++++++++++++++++++ src/i18n/utils.ts | 19 +++++++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 src/components/helper/i18n/LanguagePicker.astro create mode 100644 src/i18n/ui.ts create mode 100644 src/i18n/utils.ts diff --git a/src/components/helper/i18n/LanguagePicker.astro b/src/components/helper/i18n/LanguagePicker.astro new file mode 100644 index 0000000..ad95615 --- /dev/null +++ b/src/components/helper/i18n/LanguagePicker.astro @@ -0,0 +1,14 @@ +--- +import { languages } from '../../../i18n/ui'; +import { getLangFromUrl, useTranslatedPath } from '../../../i18n/utils'; + +const lang = getLangFromUrl(Astro.url); +const translatePath = useTranslatedPath(lang); +--- + \ No newline at end of file diff --git a/src/i18n/ui.ts b/src/i18n/ui.ts new file mode 100644 index 0000000..a473799 --- /dev/null +++ b/src/i18n/ui.ts @@ -0,0 +1,19 @@ +export const languages = { + en: 'English', + zh_hans: '中文(简体)', +}; + +export const defaultLang = 'en'; +export const showDefaultLang = false; + +export const ui = { + en: { + 'nav.home': 'Home', + 'nav.about': 'About', + 'nav.twitter': 'Twitter', + }, + zh_hans: { + 'nav.home': '首页', + 'nav.about': '关于', + }, +} as const; \ No newline at end of file diff --git a/src/i18n/utils.ts b/src/i18n/utils.ts new file mode 100644 index 0000000..4edeb6d --- /dev/null +++ b/src/i18n/utils.ts @@ -0,0 +1,19 @@ +import {ui, defaultLang, showDefaultLang} from './ui'; + +export function getLangFromUrl(url: URL) { + const [, lang] = url.pathname.split('/'); + if (lang in ui) return lang as keyof typeof ui; + return defaultLang; +} + +export function useTranslations(lang: keyof typeof ui) { + return function t(key: keyof typeof ui[typeof defaultLang]) { + return ui[lang][key] || ui[defaultLang][key]; + } +} + +export function useTranslatedPath(lang: keyof typeof ui) { + return function translatePath(path: string, l: string = lang) { + return !showDefaultLang && l === defaultLang ? path : `/${l}${path}` + } +} \ No newline at end of file