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

@@ -1,5 +1,13 @@
# Progress
## 保存体验收尾
- 品牌资料、页面字段、记录和咨询字段暴露未保存状态;保存成功清除对应状态,失败保留输入。
- 切换页面/记录提供取消或放弃确认,刷新关闭窗口提供提醒,工作区内链接离开提供确认。
- 保存操作区采用统一的面板底部样式;业务记录与品牌配置继续分别保存到原有接口。
- 浏览器测试补充未保存取消切换与失败重试场景;测试采用独立接口 fixture,不冒充当前数据库的端到端验收。
- 本轮没有重构品牌切换器或新增跨实体批量保存 API,这些不作为已验证能力。
## 工作台重构补充验收
- 上一轮将布局整理判为全部完成不准确,补充真正的工作台任务:视图分离、三栏布局和层级区域导航。
@@ -26,3 +34,7 @@
- lint 暴露已有 InquiryPreviewEditor 类型问题,已通过 Form 泛型和普通对象传入修复。
- 保留已知构建 api chunk 超过 500 kB 提示,后续由 Admin 前端打包优化任务负责;记录在 ADR 0021。
- 本轮不涉及新增 API 或数据迁移。
- 最终收尾完成:新增全局未保存离开提醒、切换确认、保存状态和失败保留输入;属性面板保存按钮固定在底部。
- 验证通过:Admin/Taro typecheck、Admin lint、format:check、19 项模板契约、Admin build、浏览器 2 项(含未保存取消切换与失败重试)。
- 构建仍有 api chunk 超过 500 kB 的提示,属于后续打包优化项,不影响构建结果。
+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,
});
};
}
@@ -245,6 +245,7 @@ const templateContent = {
};
test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ page }) => {
let rejectOfferingSave = false;
await page.setViewportSize({ width: 1920, height: 1000 });
await page.route("http://localhost:3001/public/workspace**", (route) =>
route.fulfill({ json: runtimeWorkspace }),
@@ -291,6 +292,15 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
url.pathname === `/admin/workspace/offerings/${adminOffering.id}` &&
request.method() === "PATCH"
) {
if (rejectOfferingSave) {
rejectOfferingSave = false;
return route.fulfill({
status: 500,
json: {
error: { message: "保存暂时失败,请重试", code: "TEST_FAILURE", requestId: "fixture" },
},
});
}
Object.assign(adminOffering, request.postDataJSON());
Object.assign(runtimeWorkspace.offerings[0], {
name: adminOffering.name,
@@ -430,7 +440,16 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
adminOffering.id,
);
await page.getByLabel("餐品名称").fill("编辑后的家庭餐");
await expect(page.getByText("有未保存修改", { exact: true })).toBeVisible();
await page.getByText("出摊服务", { exact: true }).click();
await expect(page.getByRole("dialog", { name: "有尚未保存的修改" })).toBeVisible();
await page.getByRole("button", { name: "继续编辑" }).click();
await expect(page.getByLabel("餐品名称")).toHaveValue("编辑后的家庭餐");
await expect(preview.locator(".offering-card")).toContainText("编辑后的家庭餐");
rejectOfferingSave = true;
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect(page.getByText("保存暂时失败,请重试", { exact: true })).toBeVisible();
await expect(page.getByLabel("餐品名称")).toHaveValue("编辑后的家庭餐");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect.poll(() => adminOffering.name).toBe("编辑后的家庭餐");
await page.reload();