martials.no/src/utils/linking.ts

66 lines
1.5 KiB
TypeScript
Raw Normal View History

import type { AvailableLanguageTag } from "@/paraglide/runtime.js"
import type { AbsolutePathname, Project } from "@/types/types.ts"
interface TranslatedPathnames {
nb: AbsolutePathname
en: `/en${AbsolutePathname}`
}
export type NavLink =
"/"
| "/contact"
| "/projects"
| `/projects/${Project["id"]}`
| "/links"
| "/hardware"
const paths: Set<NavLink> = new Set([
"/",
"/contact",
"/projects",
"/links",
"/hardware"
])
/**
* Defines the localized pathnames for the site.
* The key must be used to navigate to the correct path.
* The value is the path that will be used for the given locale.
*
* @see https://inlang.com/m/iljlwzfs/paraglide-astro-i18n
*/
const pathnames: Record<AbsolutePathname, TranslatedPathnames> = {}
for (const path of paths) {
pathnames[path] = {
nb: path,
en: `/en${path}`
}
}
export function localizePathname(
pathname: NavLink,
locale: AvailableLanguageTag
): string {
const pathnameParts = pathname.split("/")
const firstSegment: AbsolutePathname = `/${pathnameParts[1]}`
if (pathnames[firstSegment]) {
const localizedPathname = pathnames[firstSegment][locale]
const rest = pathnameParts.slice(2)
if (rest.length > 0) {
return `${localizedPathname}/${rest.join("/")}`
} else {
return localizedPathname
}
}
return pathname
}
export function resolvePathname(pathname: string): AbsolutePathname {
if (pathname.startsWith("/en")) {
return pathname.slice(3) as AbsolutePathname
}
return pathname as AbsolutePathname
}