feat: 统一业务内容双入口编辑预览

This commit is contained in:
que01 committed 2026-10-11 12:55:13 +08:00
1 parent bfbcee45bb
commit 91322fa9a0
5 files changed
+338 -77

No files matched your search

@@ -155,6 +155,8 @@ export function RecordContentEditor({
});
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
if (source === "offering")
void queryClient.invalidateQueries({ queryKey: ["admin-workspace-offering-fields"] });
},
});
return (
@@ -183,6 +183,7 @@ export function PresentationEditor({
const breakpoints = Grid.useBreakpoint();
const [activePage, setActivePage] = useState<string>();
const [selection, setSelection] = useState<PreviewSelection | undefined>(initialSelection);
const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection));
const [detailOfferingId, setDetailOfferingId] = useState<string>();
const [recordDraft, setRecordDraft] = useState<{
source: "offering" | "trust";
@@ -292,6 +293,7 @@ export function PresentationEditor({
queryKey: ["admin-offerings"],
queryFn: () => createApiClient().listAdminOfferings(),
enabled: selectedRecordSource === "offering",
refetchOnMount: "always",
});
const trustQuery = useQuery({
queryKey: ["trust-content"],
@@ -435,10 +437,46 @@ export function PresentationEditor({
}, [form, initialValues]);
useEffect(() => {
if (!pageOptions.some((item) => item.value === activePage))
setActivePage(pageOptions[0]?.value);
}, [activePage, pageOptions]);
useEffect(() => setSelection(undefined), [selectedPage, templateContent?.displayName]);
const initialPage =
typeof initialSelection === "object" && "page" in initialSelection
? String(initialSelection.page)
: undefined;
if (initialPage) {
setActivePage(
pageOptions.some((item) => item.value === initialPage)
? initialPage
: pageOptions[0]?.value,
);
return;
}
if (!activePage && pageOptions.length) setActivePage(pageOptions[0]?.value);
}, [activePage, initialSelection, pageOptions]);
useEffect(() => {
if (hasInitializedSelection) return;
if (!pageOptions.length) return;
if (!initialSelection) return;
const requestedPage =
typeof initialSelection === "object" && "page" in initialSelection
? String(initialSelection.page)
: undefined;
const resolvedPage =
requestedPage && pageOptions.some((item) => item.value === requestedPage)
? requestedPage
: (pageOptions[0]?.value ?? "home");
setSelection(
resolvePreviewSelection(
initialSelection.targetKey,
initialSelection.recordId,
visibleTargets,
resolvedPage,
),
);
setActivePage(resolvedPage);
setHasInitializedSelection(true);
}, [hasInitializedSelection, initialSelection, pageOptions, selectedPage, visibleTargets]);
useEffect(() => {
if (!initialSelection) setSelection(undefined);
}, [initialSelection, selectedPage, templateContent?.displayName]);
useEffect(() => {
if (!selection?.recordId) return;
const records =
@@ -565,6 +603,12 @@ export function PresentationEditor({
...(config.presentation && typeof config.presentation === "object"
? (config.presentation as Record<string, unknown>)
: {}),
...(typeof config.categoryLabel === "string"
? { categoryLabel: config.categoryLabel }
: {}),
...(typeof config.area === "string" ? { area: config.area } : {}),
...(typeof config.series === "string" ? { series: config.series } : {}),
...(typeof config.spaceType === "string" ? { spaceType: config.spaceType } : {}),
heroImage:
typeof config.detailHero === "string"
? config.detailHero
@@ -573,8 +617,10 @@ export function PresentationEditor({
: null,
details: {
...item.presentation.details,
...(config.details && typeof config.details === "object"
? (config.details as Record<string, unknown>)
...(config.details &&
typeof config.details === "object" &&
"background" in config.details
? (config.details as RuntimeWorkspace["offerings"][number]["presentation"]["details"])
: {}),
},
},
@@ -16,13 +16,21 @@
overflow: hidden;
}
.service-offering-editor__preview > * {
flex-shrink: 0;
}
.service-offering-editor__view {
align-self: flex-start;
margin-bottom: 10px;
}
.service-offering-editor__preview > .component-template-preview-shell {
flex: 1;
flex: 1 1 0;
min-height: 0;
}
.service-offering-editor__preview .component-template-preview {
min-height: 0;
}
@@ -31,13 +39,14 @@
display: flex;
flex-direction: column;
max-height: 72vh;
overflow-y: auto;
padding-right: 4px;
}
.service-offering-editor__form-scroll {
flex: 1;
min-height: 0;
overflow-y: auto;
padding-right: 4px;
}
.service-offering-editor__preview .ant-alert {
@@ -21,7 +21,6 @@ import type {
TemplateAdminSection,
} from "@personal-brand/api-client";
import { useMemo, useState } from "react";
import { useEffect, useRef } from "react";
import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { ImageUrlField } from "../../components/ImageUrlField.js";
@@ -44,13 +43,12 @@ export function ServicesPage() {
const [offeringForm] = Form.useForm();
const [offeringOpen, setOfferingOpen] = useState(false);
const [editingOffering, setEditingOffering] = useState<Offering | null>(null);
const [offeringDraftVersion, setOfferingDraftVersion] = useState(0);
const [previewPage, setPreviewPage] = useState<"offerings" | "detail">("detail");
const listFieldsRef = useRef<HTMLDivElement | null>(null);
const detailFieldsRef = useRef<HTMLDivElement | null>(null);
const formScrollRef = useRef<HTMLDivElement | null>(null);
const offerings = useQuery({
queryKey: ["admin-offerings"],
queryFn: () => client.listAdminOfferings(),
refetchOnMount: "always",
});
const workspace = useQuery({
queryKey: ["admin-workspace-offering-fields"],
@@ -59,6 +57,7 @@ export function ServicesPage() {
const previewWorkspace = useQuery({
queryKey: ["admin-preview-workspace-services"],
queryFn: () => client.getAdminPreviewWorkspace(),
refetchOnMount: "always",
});
const templateFields: TemplateAdminField[] = (
workspace.data?.templateContent?.admin.sections ?? []
@@ -134,14 +133,10 @@ export function ServicesPage() {
),
[templateFields, listFields, detailFields],
);
useEffect(() => {
const target = previewPage === "offerings" ? listFieldsRef.current : detailFieldsRef.current;
if (!target || !formScrollRef.current) return;
formScrollRef.current.scrollTo({
top: target.offsetTop - formScrollRef.current.offsetTop - 12,
behavior: "smooth",
});
}, [previewPage, editingOffering?.id]);
const activeTemplateFields =
previewPage === "offerings"
? [...listFields, ...otherFields.filter((field) => field.page === "offerings")]
: [...detailFields, ...otherFields.filter((field) => field.page === "detail")];
const previewWorkspaceDraft = useMemo<RuntimeWorkspace | undefined>(() => {
if (!previewWorkspace.data || !editingOffering) return undefined;
const values = offeringForm.getFieldsValue(true) as Record<string, unknown>;
@@ -184,19 +179,34 @@ export function ServicesPage() {
...(config.presentation && typeof config.presentation === "object"
? (config.presentation as Record<string, unknown>)
: {}),
...(typeof config.categoryLabel === "string"
? { categoryLabel: config.categoryLabel }
: {}),
...(typeof config.area === "string" ? { area: config.area } : {}),
...(typeof config.series === "string" ? { series: config.series } : {}),
...(typeof config.spaceType === "string" ? { spaceType: config.spaceType } : {}),
heroImage:
typeof config.detailHero === "string"
? config.detailHero
: typeof offeringValues.coverUrl === "string" && offeringValues.coverUrl.trim()
? offeringValues.coverUrl
: (item.coverUrl ?? null),
details: {
...item.presentation.details,
...(config.details && typeof config.details === "object"
? {
...item.presentation.details,
...(config.details as Record<string, unknown>),
}
: {}),
},
},
}
: item,
),
brand: previewWorkspace.data.brand,
};
}, [previewWorkspace.data, editingOffering, templateFields]);
}, [previewWorkspace.data, editingOffering, templateFields, offeringDraftVersion]);
const saveOffering = useMutation({
mutationFn: (values: Record<string, unknown>) => {
const fields = Object.fromEntries(
@@ -217,7 +227,10 @@ export function ServicesPage() {
setOfferingOpen(false);
setEditingOffering(null);
offeringForm.resetFields();
offeringForm.setFieldsValue({});
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
void queryClient.invalidateQueries({ queryKey: ["admin-workspace-offering-fields"] });
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace-services"] });
},
});
const deleteOffering = useMutation({
@@ -412,6 +425,7 @@ export function ServicesPage() {
<ComponentTemplatePreview
workspace={previewWorkspaceDraft}
page={previewPage}
offeringId={editingOffering.id}
targets={previewTargets[previewPage] ?? []}
selection={{
targetKey:
@@ -428,9 +442,10 @@ export function ServicesPage() {
className="service-offering-editor__form"
form={offeringForm}
layout="vertical"
onValuesChange={() => setOfferingDraftVersion((version) => version + 1)}
onFinish={(values) => saveOffering.mutate(values as Record<string, unknown>)}
>
<div ref={formScrollRef} className="service-offering-editor__form-scroll">
<div className="service-offering-editor__form-scroll">
<Typography.Title level={5}>基础信息</Typography.Title>
<Form.Item name="kind" label="类型" rules={[{ required: true }]}>
<Select
@@ -479,62 +494,41 @@ export function ServicesPage() {
]}
/>
</Form.Item>
{activeTemplateFields.length ? (
<div>
<Typography.Title level={5}>
{previewPage === "offerings" ? "列表展示字段" : "详情展示字段"}
</Typography.Title>
<Typography.Paragraph type="secondary">
这里只编辑左侧预览对应的字段;它们与小程序页面编辑的是同一份业务数据。
</Typography.Paragraph>
<RecordContentFields
section={{
...templateFieldSection,
fields: activeTemplateFields,
}}
/>
</div>
) : null}
{editingOffering ? (
<Button
htmlType="button"
onClick={() =>
navigate("/admin/brand", {
state: {
targetKey:
previewPage === "offerings"
? visualOfferingTarget.key
: (detailTarget?.key ?? visualOfferingTarget.key),
recordId: editingOffering.id,
},
})
}
>
在小程序页面编辑
</Button>
) : null}
</div>
{templateFields.length ? (
<>
<Typography.Paragraph type="secondary">
以下模板字段与左侧预览及小程序页面编辑的是同一份业务数据。
</Typography.Paragraph>
{listFields.length ? (
<div ref={listFieldsRef}>
<Typography.Title level={5}>列表展示</Typography.Title>
<RecordContentFields
section={{
...templateFieldSection,
fields: listFields,
}}
/>
</div>
) : null}
{detailFields.length ? (
<div ref={detailFieldsRef}>
<Typography.Title level={5}>详情展示</Typography.Title>
<RecordContentFields
section={{
...templateFieldSection,
fields: detailFields,
}}
/>
</div>
) : null}
{otherFields.length ? (
<>
<Typography.Title level={5}>其他模板内容</Typography.Title>
<RecordContentFields
section={{
...templateFieldSection,
fields: otherFields,
}}
/>
</>
) : null}
{editingOffering ? (
<Button
htmlType="button"
onClick={() =>
navigate("/admin/brand", {
state: {
targetKey: visualOfferingTarget.key,
recordId: editingOffering.id,
},
})
}
>
在小程序页面编辑
</Button>
) : null}
</>
) : null}
</Form>
</div>
</Modal>
@@ -0,0 +1,210 @@
import fs from "node:fs";
import { test, expect } from "@playwright/test";
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
const templateContent = JSON.parse(
fs.readFileSync("../../packages/template-acheng-campus-food/template.json", "utf8"),
);
const brand = {
id: "brand-fixture",
slug: "preview-fixture",
name: "预览品牌",
templateKey: "food",
tagline: "校园家常餐",
description: "认真做好每一餐",
avatarUrl: "",
coverUrl: "",
hours: "每日 17:00",
address: "东门附近",
deliveryNote: "提前预约",
contactPhone: "13800138000",
contactWechat: "food-example",
config: {
visualTemplateKey: "acheng-campus-food",
founder: "测试主理人",
title: "私房菜主理人",
heroImage: "",
visualPresentation: {},
},
};
const adminOffering = {
id: "menu-fixture",
kind: "service",
name: "家庭聚餐定制",
summary: "为同学聚餐、家庭聚会提供常见的私房菜定制。",
description: "餐品详情",
priceText: "88.88",
coverUrl: "",
isEnabled: true,
sortOrder: 0,
config: {
categoryLabel: "家庭餐",
area: "东门",
series: "预约制",
spaceType: "8 人聚餐",
details: { background: "原餐品介绍", designConcept: "", crafts: [], materialsList: [] },
keywords: [],
},
};
const runtimeWorkspace = {
schemaVersion: "1.0.0",
publication: { status: "published", version: 1 },
brand: {
...brand,
...brand.config,
founder: brand.config.founder,
title: brand.config.title,
visualPresentation: {},
visualTemplateKey: brand.config.visualTemplateKey,
},
templateData: {},
navigation: { tabs: [] },
offerings: [
{
id: adminOffering.id,
name: adminOffering.name,
summary: adminOffering.summary,
priceText: adminOffering.priceText,
coverUrl: adminOffering.coverUrl,
presentation: {
categoryLabel: adminOffering.config.categoryLabel,
area: adminOffering.config.area,
series: adminOffering.config.series,
spaceType: adminOffering.config.spaceType,
keywords: [],
details: { ...adminOffering.config.details },
},
},
],
inquiryForms: [],
trustItems: [],
trustPresentation: {},
capabilities: [],
theme: { colors: {} },
};
test("业务编辑弹窗预览列表与详情详情同一份内容", async ({ page }) => {
test.setTimeout(60000);
let savedBody: any;
await page.setViewportSize({ width: 1920, height: 1000 });
await page.route("**/api/**", async (route) => {
const url = new URL(route.request().url());
const path = url.pathname.replace(/^\/api/, "");
if (path === "/admin/session/login")
return route.fulfill({
json: {
token: "fixture-token",
displayName: "测试管理员",
role: "owner",
mustChangePassword: false,
},
});
if (path === "/admin/brands")
return route.fulfill({ json: [{ id: brand.id, role: "owner", brand }] });
if (path === "/admin/workspace/offerings")
return route.fulfill({
json: [{ ...adminOffering, config: structuredClone(adminOffering.config) }],
});
if (path === "/admin/workspace/forms") return route.fulfill({ json: [] });
if (
path === `/admin/workspace/offerings/${adminOffering.id}` &&
route.request().method() === "PATCH"
) {
savedBody = route.request().postDataJSON();
const savedOffering = { ...adminOffering, ...savedBody };
Object.assign(adminOffering, structuredClone(savedOffering));
runtimeWorkspace.offerings[0] = {
...runtimeWorkspace.offerings[0],
name: adminOffering.name,
summary: adminOffering.summary,
priceText: adminOffering.priceText,
coverUrl: adminOffering.coverUrl,
presentation: structuredClone(adminOffering.config),
};
return route.fulfill({ json: structuredClone(adminOffering) });
}
if (path === "/admin/workspace")
return route.fulfill({
json: {
brand,
installations: [],
fields: [],
offerings: [{ ...adminOffering, config: structuredClone(adminOffering.config) }],
forms: [],
templateContent,
},
});
if (path === "/admin/config/brand") return route.fulfill({ json: brand });
if (path === "/public/templates/food")
return route.fulfill({
json: { name: "餐饮模板", description: "fixture", serviceCategories: [] },
});
if (path === "/admin/workspace/preview")
return route.fulfill({ json: structuredClone(runtimeWorkspace) });
if (path === "/public/workspace")
return route.fulfill({ json: structuredClone(runtimeWorkspace) });
return route.fulfill({ json: {} });
});
await page.goto(`${adminOrigin}/admin/services`);
await page.getByLabel("账号").fill("admin");
await page.getByLabel("密码").fill("fixture-password");
await page.locator('button[type="submit"]').click();
await page.getByRole("button", { name: "编辑详情" }).click();
const editor = page.locator(".service-offering-editor");
const preview = editor.locator(".component-template-preview");
await expect(preview.locator(".food-detail")).toContainText("家庭聚餐定制");
await expect(preview).toHaveAttribute(
"data-active-target",
"acheng-campus-food.detail.dishDetail",
);
await expect(preview).toHaveAttribute("data-active-record-id", adminOffering.id);
await expect(editor.locator(".service-offering-editor__view")).toContainText("详情内容");
await expect(page.getByText("正在核对详情展示")).toBeVisible();
await page.getByLabel("餐品介绍").fill("弹窗编辑后的餐品介绍");
await expect(preview.locator(".food-detail .body")).toContainText("弹窗编辑后的餐品介绍");
await page.getByText("列表卡片", { exact: true }).click();
await expect(preview.locator(".offering-card")).toContainText("家庭聚餐定制");
await expect(preview).toHaveAttribute("data-active-target", "acheng-campus-food.offerings.item");
await expect(page.getByText("正在核对列表展示")).toBeVisible();
await page.getByLabel("名称", { exact: true }).fill("列表实时预览餐品");
await expect(preview.locator(".offering-card")).toContainText("列表实时预览餐品");
await page.getByText("详情内容", { exact: true }).click();
await expect(preview.locator(".food-detail")).toContainText("列表实时预览餐品");
await expect(page.getByLabel("餐品介绍")).toHaveValue("弹窗编辑后的餐品介绍");
await page.locator(".ant-modal-footer").getByRole("button", { name: "OK" }).click();
await expect(page.getByText("业务提供项已保存")).toBeVisible();
await page.locator(".ant-modal-wrap").waitFor({ state: "hidden" });
await page.getByRole("button", { name: "编辑详情" }).first().click();
await expect(page.locator(".component-template-preview")).toBeVisible();
await page.getByRole("button", { name: "在小程序页面编辑" }).click();
await expect(page.getByText("页面预览", { exact: true })).toBeVisible({ timeout: 15000 });
await page.getByText("首页业务卡片", { exact: true }).click();
await expect(
page.getByText("正在编辑业务提供项:列表实时预览餐品", { exact: true }),
).toBeVisible();
await page.getByLabel("名称", { exact: true }).fill("小程序页保存后的餐品");
await page.getByLabel("简介", { exact: true }).fill("跨入口保存后的业务简介");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect(page.getByText("已保存内容草稿,发布后访客才会看到更新")).toBeVisible();
expect(savedBody.name).toBe("小程序页保存后的餐品");
expect(savedBody.summary).toBe("跨入口保存后的业务简介");
await page.goBack();
await expect(page.getByText("小程序内容:业务展示与详情")).toBeVisible();
await page.getByRole("button", { name: "编辑详情" }).click();
await expect(page.getByLabel("名称", { exact: true })).toHaveValue("小程序页保存后的餐品");
await expect(page.getByLabel("餐品介绍")).toHaveValue("弹窗编辑后的餐品介绍");
await page.locator(".ant-modal-footer").getByRole("button", { name: "OK" }).click();
await expect(page.getByText("业务提供项已保存")).toBeVisible();
expect(savedBody.name).toBe("小程序页保存后的餐品");
expect(savedBody.summary).toBe("跨入口保存后的业务简介");
expect(savedBody.config.details.background).toBe("弹窗编辑后的餐品介绍");
});