// src/i18n/utils.ts import { ui, defaultLang, languages } from './ui'; export type Lang = keyof typeof languages; export type UiKeys = keyof typeof ui[typeof defaultLang]; export function useTranslations(lang: Lang | undefined) { const currentLang = lang || defaultLang; return function t(key: UiKeys, ...args: any[]): string { let translation: string = ui[currentLang][key] || ui[defaultLang][key]; if (args.length > 0) { args.forEach((arg, index) => { translation = translation.replace(`{${index}}`, arg); }); } return translation; }; } export function getLocalizedPath(path: string, lang: Lang | undefined): string { const currentLang = lang || defaultLang; const basePath = import.meta.env.BASE_URL === '/' ? '' : import.meta.env.BASE_URL; // Astro's i18n routing handles prefixing automatically based on astro.config.mjs settings. // We just need to ensure the path is correctly formed relative to the base. // If a language is explicitly provided and it's not the default, // and prefixDefaultLocale is false (meaning default lang has no prefix), // we might need to add it. However, Astro typically handles this. // For now, let's assume Astro's routing takes care of the prefix. // This function might become simpler or even unnecessary depending on how LanguageSwitcher is used. let newPath = path; // Ensure path starts with a slash if it's not an external URL if (!newPath.startsWith('/') && !newPath.match(/^https?:\/\//)) { newPath = `/${newPath}`; } // If prefixDefaultLocale is false (default in our config) and currentLang is not defaultLang, // Astro will expect /zh/path. If currentLang is defaultLang, it expects /path. // If prefixDefaultLocale is true, all locales get a prefix: /en/path, /zh/path. // Given our astro.config.mjs: prefixDefaultLocale: false // If lang is 'zh', the path should be /zh/your-path // If lang is 'en' (default), the path should be /your-path // Astro's or Astro.redirect should handle this correctly when given a root-relative path. // This function's main job is to ensure the base path and the target path are combined correctly. const fullPath = `${basePath}${newPath}`; return fullPath.replace(/\/\/+/g, '/'); // Clean up any double slashes }