40 lines
914 B
TypeScript
40 lines
914 B
TypeScript
"use client";
|
|
|
|
import type { ComponentProps, MouseEvent } from "react";
|
|
import Link from "next/link";
|
|
import { useRouter } from "next/navigation";
|
|
import { flushPendingSaves } from "@/lib/admin-form-save-bridge";
|
|
|
|
export function GuardedLink({
|
|
href,
|
|
onClick,
|
|
...props
|
|
}: ComponentProps<typeof Link>) {
|
|
const router = useRouter();
|
|
|
|
const handleClick = async (event: MouseEvent<HTMLAnchorElement>) => {
|
|
onClick?.(event);
|
|
if (
|
|
event.defaultPrevented ||
|
|
event.button !== 0 ||
|
|
event.metaKey ||
|
|
event.ctrlKey ||
|
|
event.shiftKey ||
|
|
event.altKey ||
|
|
typeof href !== "string"
|
|
) {
|
|
return;
|
|
}
|
|
|
|
event.preventDefault();
|
|
try {
|
|
await flushPendingSaves();
|
|
router.push(href);
|
|
} catch {
|
|
// The persistent save error remains visible on the current page.
|
|
}
|
|
};
|
|
|
|
return <Link href={href} onClick={handleClick} {...props} />;
|
|
}
|