Files
Tiber365/src/utils/i18n.ts
2025-07-24 18:46:24 +02:00

74 lines
2.0 KiB
TypeScript

// Updated i18n utils for Astro's built-in i18n system
import enTranslations from '../content/i18n/en.json';
import nlTranslations from '../content/i18n/nl.json';
import deTranslations from '../content/i18n/de.json';
import frTranslations from '../content/i18n/fr.json';
export const SUPPORTED_LOCALES = ['en', 'nl', 'de', 'fr'] as const;
export type Locale = typeof SUPPORTED_LOCALES[number];
export const languages = {
en: { name: 'English', flag: '🇬🇧' },
nl: { name: 'Nederlands', flag: '🇳🇱' },
de: { name: 'Deutsch', flag: '🇩🇪' },
fr: { name: 'Français', flag: '🇫🇷' }
};
export function getLangFromUrl(url: URL): Locale {
const [, lang] = url.pathname.split('/');
if (lang && SUPPORTED_LOCALES.includes(lang as Locale)) {
return lang as Locale;
}
return 'en';
}
// Load translations directly from JSON files
const translations: Record<Locale, any> = {
en: enTranslations,
nl: nlTranslations,
de: deTranslations,
fr: frTranslations
};
export async function useTranslations(lang: Locale) {
const translationData = translations[lang] || translations.en || {};
return function t(key: string): string {
const keys = key.split('.');
let value: any = translationData;
for (const k of keys) {
value = value?.[k];
if (value === undefined) break;
}
// Fallback to English if translation missing
if (value === undefined && lang !== 'en') {
let fallback: any = translations.en;
for (const k of keys) {
fallback = fallback?.[k];
if (fallback === undefined) break;
}
value = fallback;
}
return value || key;
};
}
// Simple translation function for components that don't need async
export function t(key: string): string {
// This is a fallback - in practice, components should use useTranslations
return key;
}
export function getCurrentLocale(): Locale {
return 'en';
}
export function localizePath(path: string, locale: Locale): string {
if (locale === 'en') {
return path;
}
return `/${locale}${path}`;
}