54 lines
1.4 KiB
TypeScript
54 lines
1.4 KiB
TypeScript
import { studioRoutes } from "../studio-routes.ts";
|
|
import type {
|
|
AnchorHTMLAttributes,
|
|
MouseEvent as ReactMouseEvent,
|
|
} from "react";
|
|
|
|
import { useStudio } from "../use-studio.ts";
|
|
|
|
type GuardedStudioLinkProps = AnchorHTMLAttributes<HTMLAnchorElement> & {
|
|
href: string;
|
|
};
|
|
|
|
function isPlainPrimaryClick(event: ReactMouseEvent<HTMLAnchorElement>): boolean {
|
|
return event.button === 0 &&
|
|
!event.metaKey &&
|
|
!event.ctrlKey &&
|
|
!event.shiftKey &&
|
|
!event.altKey;
|
|
}
|
|
|
|
export function GuardedStudioLink({
|
|
href,
|
|
onClick,
|
|
...props
|
|
}: GuardedStudioLinkProps) {
|
|
const { navigateInternal } = useStudio();
|
|
return (
|
|
<a
|
|
{...props}
|
|
href={href}
|
|
onClick={(event) => {
|
|
onClick?.(event);
|
|
if (event.defaultPrevented || !isPlainPrimaryClick(event)) return;
|
|
if (
|
|
event.currentTarget.hasAttribute("download") ||
|
|
(event.currentTarget.target && event.currentTarget.target !== "_self")
|
|
) return;
|
|
if (href.startsWith("#")) return;
|
|
const target = new URL(href, window.location.href);
|
|
if (target.origin !== window.location.origin) return;
|
|
if (
|
|
target.pathname !== studioRoutes.home() &&
|
|
!target.pathname.startsWith(`${studioRoutes.home()}/`)
|
|
) return;
|
|
event.preventDefault();
|
|
navigateInternal(
|
|
`${target.pathname}${target.search}${target.hash}`,
|
|
event.currentTarget,
|
|
);
|
|
}}
|
|
/>
|
|
);
|
|
}
|