import { useEffect } from "react"; import { App } from "antd"; import { useNavigate } from "react-router-dom"; export function useEditorDraft(dirty: boolean) { const { modal } = App.useApp(); const navigate = useNavigate(); useEffect(() => { if (!dirty) return; const beforeUnload = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = ""; }; window.addEventListener("beforeunload", beforeUnload); const leave = (event: MouseEvent) => { if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return; const anchor = event.target instanceof Element ? event.target.closest("a[href]") : null; if (!anchor || anchor.target === "_blank" || anchor.hasAttribute("download")) return; const url = new URL(anchor.href, window.location.href); if (url.origin !== window.location.origin || url.pathname === window.location.pathname) return; event.preventDefault(); event.stopImmediatePropagation(); modal.confirm({ title: "有尚未保存的修改", content: "离开工作台会丢失未保存内容。请先保存,或确认放弃修改。", okText: "放弃修改并继续", cancelText: "继续编辑", onOk: () => { void navigate(`${url.pathname}${url.search}${url.hash}`); }, }); }; document.addEventListener("click", leave, true); return () => { window.removeEventListener("beforeunload", beforeUnload); document.removeEventListener("click", leave, true); }; }, [dirty, navigate]); return (action: () => void) => { if (!dirty) return action(); modal.confirm({ title: "有尚未保存的修改", content: "切换后当前内容可能丢失。请先保存,或确认放弃修改。", okText: "放弃修改并继续", cancelText: "继续编辑", onOk: action, }); }; }