"use client"; import { ComponentProps, ElementType, MouseEvent, ReactNode, Ref } from "react"; import { useRouter } from "../hooks/use-router"; type Props = { as?: C; ref?: Ref; href: string; replace?: boolean; scroll?: "top" | "preserve"; mask?: string; children?: ReactNode; } & ComponentProps; export default function Link({ as, href, children, replace, scroll, mask, onClick, ref, ...props }: Props) { let router = useRouter(); let using: "replace" | "navigate" = replace ? "replace" : "navigate"; let shouldScroll = !scroll || scroll == "top"; function handleClick(e: MouseEvent) { if (onClick) { onClick(e); } let isLocal = isLocalLink(href); if ( e.button === 0 && !e.ctrlKey && !e.metaKey && !e.defaultPrevented && isLocal ) { e.preventDefault(); router[using](href, { scroll: shouldScroll, ...(mask ? { mask: mask } : {}), }); } } const Tag = as || "a"; return ( {children} ); } function isLocalLink(path: string) { try { let urlObject = new URL(path, window.location.origin); return urlObject.origin === window.location.origin; } catch (e) { return false; } }