feat: 完善编辑工作台保存与离开体验
This commit is contained in:
1 parent
860d9266fe
commit
fa6b492bce
7 files changed
+168
-15
No files matched your search
@@ -0,0 +1,51 @@
|
||||
import { useEffect } from "react";
|
||||
import { Modal } from "antd";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
export function useEditorDraft(dirty: boolean) {
|
||||
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<HTMLAnchorElement>("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,
|
||||
});
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user