Files
sass-mohfarawati/lib/locale.ts
T

50 lines
1.3 KiB
TypeScript

import { routing } from "../i18n/routing";
export type AppLocale = (typeof routing.locales)[number];
export function resolveLocale(locale: string): AppLocale {
if (locale === "en" || locale === "ar") {
return locale;
}
return routing.defaultLocale;
}
export function getDirection(locale: string): "ltr" | "rtl" {
return resolveLocale(locale) === "ar" ? "rtl" : "ltr";
}
export function stripLocalePrefix(pathname: string): string {
for (const locale of routing.locales) {
if (pathname === `/${locale}`) {
return "/";
}
if (pathname.startsWith(`/${locale}/`)) {
return pathname.slice(locale.length + 1);
}
}
return pathname || "/";
}
export function getLocalizedPath(locale: string, pathname = "/"): string {
return getLocalizedPathWithDefault(locale, pathname, routing.defaultLocale);
}
export function getLocalizedPathWithDefault(
locale: string,
pathname = "/",
defaultLocale: AppLocale = routing.defaultLocale,
): string {
const localeKey = resolveLocale(locale);
const normalizedPath = pathname === "" ? "/" : pathname;
const strippedPath = stripLocalePrefix(normalizedPath);
if (localeKey === defaultLocale) {
return strippedPath;
}
return strippedPath === "/" ? `/${localeKey}` : `/${localeKey}${strippedPath}`;
}