TenantAtlas/apps/website/src/i18n.ts

76 lines
1.9 KiB
TypeScript

export const defaultLocale = 'de';
export const supportedLocales = ['de', 'en'] as const;
export type Locale = (typeof supportedLocales)[number];
export const localeLabels: Record<Locale, string> = {
de: 'Deutsch',
en: 'English',
};
export const localeHtmlLang: Record<Locale, string> = {
de: 'de',
en: 'en',
};
export const localeOg: Record<Locale, string> = {
de: 'de_DE',
en: 'en_US',
};
export function isLocale(value: string | undefined): value is Locale {
return supportedLocales.includes(value as Locale);
}
export function getLocaleFromPath(pathname: string): Locale {
const firstSegment = pathname.split('/').filter(Boolean)[0];
return isLocale(firstSegment) ? firstSegment : defaultLocale;
}
export function stripLocalePrefix(pathname: string): string {
const segments = pathname.split('/').filter(Boolean);
if (isLocale(segments[0])) {
segments.shift();
}
const stripped = `/${segments.join('/')}`;
return stripped === '/' ? '/' : stripped.replace(/\/+$/, '');
}
export function localizedPath(pathname: string, locale: Locale): string {
const basePath = stripLocalePrefix(pathname);
const keepTrailingSlash = pathname !== '/' && pathname.endsWith('/');
const withTrailingSlash = (path: string) =>
keepTrailingSlash && !path.endsWith('/') ? `${path}/` : path;
if (locale === defaultLocale) {
return withTrailingSlash(basePath === '' ? '/' : basePath);
}
if (basePath === '/' || basePath === '') {
return `/${locale}/`;
}
return withTrailingSlash(`/${locale}${basePath}`);
}
export function localizeHref(href: string, locale: Locale): string {
if (
href.startsWith('http://') ||
href.startsWith('https://') ||
href.startsWith('mailto:') ||
href.startsWith('tel:') ||
href.startsWith('#')
) {
return href;
}
const [path, hash] = href.split('#');
const localized = localizedPath(path || '/', locale);
return hash ? `${localized}#${hash}` : localized;
}