Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
50 lines
2.0 KiB
TypeScript
50 lines
2.0 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useState } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
|
|
/** The in-app address a plain left click on this event would go to, or null when the click stays or opens elsewhere. */
|
|
function leavingTo(e: MouseEvent): string | null {
|
|
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return null;
|
|
const link = (e.target as Element | null)?.closest?.("a[href]") as HTMLAnchorElement | null;
|
|
if (!link || (link.target && link.target !== "_self") || link.hasAttribute("download")) return null;
|
|
const url = new URL(link.href, location.href);
|
|
if (url.origin !== location.origin) return null;
|
|
if (url.pathname === location.pathname && url.search === location.search) return null; // a #name on this page
|
|
return url.pathname + url.search + url.hash;
|
|
}
|
|
|
|
/**
|
|
* Asks before an in-app link leaves unsaved edits (add-page-visual-editor). The browser asks for reloads and closing
|
|
* (usePageDraft). ponytail: browser Back is not guarded; the App Router has no hook for it.
|
|
*/
|
|
export function LeaveGuard({ dirty }: { dirty: boolean }) {
|
|
const t = useT();
|
|
const router = useRouter();
|
|
const [to, setTo] = useState<string | null>(null);
|
|
useEffect(() => {
|
|
if (!dirty) return;
|
|
// Capture phase on the document: before the link's own handler, which then sees the click is taken.
|
|
const onClick = (e: MouseEvent) => {
|
|
const href = leavingTo(e);
|
|
if (!href) return;
|
|
e.preventDefault();
|
|
setTo(href);
|
|
};
|
|
document.addEventListener("click", onClick, true);
|
|
return () => document.removeEventListener("click", onClick, true);
|
|
}, [dirty]);
|
|
return to ? (
|
|
<ConfirmDialog
|
|
title={t("PagesLeaveTitle")}
|
|
message={t("PagesLeaveMessage")}
|
|
confirmLabel={t("PagesLeave")}
|
|
destructive
|
|
onConfirm={() => { setTo(null); router.push(to); }}
|
|
onCancel={() => setTo(null)}
|
|
/>
|
|
) : null;
|
|
}
|