39 lines
1.0 KiB
TypeScript
39 lines
1.0 KiB
TypeScript
"use client";
|
|
|
|
import NextLink from "next/link";
|
|
import { usePathname as useNextPathname } from "next/navigation";
|
|
import { useLocale } from "../context/LocaleContext";
|
|
import {
|
|
isInternalNavigationClick,
|
|
startNavigation,
|
|
} from "@/app/lib/navigation-loading";
|
|
|
|
type LocaleLinkProps = React.ComponentProps<typeof NextLink>;
|
|
|
|
export function LocaleLink({ href, onClick, ...props }: LocaleLinkProps) {
|
|
const locale = useLocale();
|
|
const hrefStr = typeof href === "string" ? href : href.pathname ?? "/";
|
|
const localeHref = hrefStr.startsWith("/")
|
|
? `/${locale}${hrefStr === "/" ? "" : hrefStr}`
|
|
: hrefStr;
|
|
|
|
return (
|
|
<NextLink
|
|
href={localeHref}
|
|
onClick={(event) => {
|
|
if (isInternalNavigationClick(event.nativeEvent, event.currentTarget)) {
|
|
startNavigation();
|
|
}
|
|
onClick?.(event);
|
|
}}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function usePathname() {
|
|
const path = useNextPathname();
|
|
const match = path?.match(/^\/(zh|en)(\/.*)?$/);
|
|
return match ? (match[2] ?? "/") : path ?? "/";
|
|
}
|