feat: 完善编辑工作台保存与离开体验

This commit is contained in:
que01 committed 2026-10-10 11:22:49 +08:00
1 parent 860d9266fe
commit fa6b492bce
7 files changed
+168 -15

No files matched your search

+9 -1
View File
@@ -22,9 +22,12 @@ import { ImageUrlField } from "../../components/ImageUrlField.js";
import { MutationError, QueryState } from "../../components/QueryState.js";
import { PresentationEditor } from "./PresentationEditor.js";
import "./BrandPage.css";
import { useEditorDraft } from "./use-editor-draft.js";
export function BrandPage() {
const [panel, setPanel] = useState("pages");
const [dirty, setDirty] = useState(false);
useEditorDraft(dirty);
const client = createApiClient();
const queryClient = useQueryClient();
const [form] = Form.useForm<BrandProfile>();
@@ -45,8 +48,10 @@ export function BrandPage() {
const save = useMutation({
mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values),
onSuccess: () => {
setDirty(false);
message.success("品牌表达已保存");
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
},
});
return (
@@ -73,7 +78,9 @@ export function BrandPage() {
]}
/>
<Space>
<Tag>草稿工作区</Tag>
<Tag color={dirty ? "orange" : "default"}>
{dirty ? "品牌资料有未保存修改" : "草稿工作区"}
</Tag>
<Link to="/admin/publication">检查与发布 →</Link>
</Space>
</div>
@@ -83,6 +90,7 @@ export function BrandPage() {
form={form}
layout="vertical"
initialValues={brand.data}
onValuesChange={() => setDirty(true)}
onFinish={(values) => save.mutate(values)}
>
<section className="brand-settings-section" aria-labelledby="brand-identity-title">
@@ -11,10 +11,12 @@ export function InquiryPreviewEditor({
runtime,
fieldKey,
onDraft,
onSaved,
}: {
runtime: RuntimeInquiryForm;
fieldKey: string;
onDraft: (fields: RuntimeInquiryForm["fields"]) => void;
onSaved?: () => void;
}) {
const [form] = Form.useForm<Record<string, unknown>>();
const cache = useQueryClient();
@@ -46,6 +48,7 @@ export function InquiryPreviewEditor({
return createApiClient().updateAdminInquiryForm(record.id, { fieldsSnapshot });
},
onSuccess: () => {
onSaved?.();
message.success("表单字段已保存为草稿");
void cache.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
void cache.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
@@ -117,6 +117,21 @@
margin-bottom: 24px;
}
.presentation-editor__inspector form > .ant-space:last-child {
position: sticky;
bottom: 0;
z-index: 2;
padding: 16px 0 4px;
border-top: 1px solid #e5e7eb;
background: #fff;
}
.presentation-editor__inspector form > .ant-space:last-child .ant-btn-primary {
min-width: 140px;
}
.presentation-editor__inspector > .ant-tag {
margin-bottom: 20px;
}
@media (max-width: 1199px) {
.presentation-editor__workspace {
grid-template-columns: minmax(0, 1fr);
@@ -50,6 +50,7 @@ import {
type PresentationValues,
} from "./presentation-bindings.js";
import "./PresentationEditor.css";
import { useEditorDraft } from "./use-editor-draft.js";
interface PresentationEditorProps {
templateContent: AdminTemplateContent | null | undefined;
@@ -175,6 +176,8 @@ export function PresentationEditor({
const [previewBrandValues, setPreviewBrandValues] = useState<Record<string, unknown>>({});
const [inquiryDraft, setInquiryDraft] =
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
const [brandDirty, setBrandDirty] = useState(false);
const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft);
const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand");
const sections = useMemo(() => {
const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({
@@ -305,18 +308,27 @@ export function PresentationEditor({
[selectedSection, selection?.targetKey],
);
const handleTargetSelected = useCallback(
(next?: PreviewSelection) =>
setSelection(
next
? resolvePreviewSelection(
next.targetKey,
next.recordId,
visibleTargets,
selectedPage ?? "home",
)
: undefined,
),
[visibleTargets, selectedPage],
(next?: PreviewSelection) => {
const select = () =>
setSelection(
next
? resolvePreviewSelection(
next.targetKey,
next.recordId,
visibleTargets,
selectedPage ?? "home",
)
: undefined,
);
if (recordDraft || inquiryDraft)
guardDraft(() => {
setInquiryDraft(undefined);
setRecordDraft(undefined);
select();
});
else select();
},
[visibleTargets, selectedPage, recordDraft, inquiryDraft, guardDraft],
);
const relatedTargets = [
...(templateContent?.admin.sections ?? [])
@@ -378,6 +390,7 @@ export function PresentationEditor({
});
},
onSuccess: () => {
setBrandDirty(false);
message.success("页面内容已保存为草稿,发布后小程序才会更新");
window.dispatchEvent(new Event("template-preview-refresh"));
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
@@ -424,6 +437,7 @@ export function PresentationEditor({
);
const handleValuesChange = useCallback(
(_changed: PresentationValues, allValues: PresentationValues) => {
setBrandDirty(true);
const next = applyBrandPreviewValues(
brand as unknown as Record<string, unknown>,
config,
@@ -559,14 +573,34 @@ export function PresentationEditor({
aria-label="选择小程序页面"
value={selectedPage}
options={pageOptions}
onChange={setActivePage}
onChange={(value) =>
guardDraft(() => {
setBrandDirty(false);
form.setFieldsValue(initialValues);
setPreviewConfig(config ?? {});
setPreviewBrandValues({});
setRecordDraft(undefined);
setInquiryDraft(undefined);
setActivePage(value);
})
}
style={{ minWidth: 180 }}
/>
) : (
<Segmented
value={selectedPage}
options={pageOptions}
onChange={(value) => setActivePage(String(value))}
onChange={(value) =>
guardDraft(() => {
setBrandDirty(false);
form.setFieldsValue(initialValues);
setPreviewConfig(config ?? {});
setPreviewBrandValues({});
setRecordDraft(undefined);
setInquiryDraft(undefined);
setActivePage(String(value));
})
}
/>
)}
</Space>
@@ -646,6 +680,15 @@ export function PresentationEditor({
<Typography.Title level={5}>
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
</Typography.Title>
<Tag color={brandDirty || recordDraft || inquiryDraft ? "orange" : "default"}>
{save.isPending
? "正在保存"
: save.isError
? "保存失败,请重试"
: brandDirty || recordDraft || inquiryDraft
? "有未保存修改"
: "草稿已同步"}
</Tag>
{selectedPage === "detail" ? (
<Alert
type="info"
@@ -661,6 +704,7 @@ export function PresentationEditor({
}
fieldKey={activeTarget.slice("inquiry-field:".length)}
onDraft={setInquiryDraft}
onSaved={() => setInquiryDraft(undefined)}
/>
) : selectedTarget?.composite ? (
<Alert
@@ -956,6 +1000,7 @@ function RecordEditor({
onFinish={(values) => save.mutate(values)}
style={{ minHeight: 0, display: "flex", flexDirection: "column" }}
>
{save.isPending ? <Typography.Text type="secondary">正在保存内容…</Typography.Text> : null}
<Typography.Paragraph type="secondary">{section.description}</Typography.Paragraph>
<div style={{ flex: 1 }}>
<Row gutter={16}>
@@ -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,
});
};
}