Files
persionalBrand/apps/taro/test/browser/admin-editor.spec.ts

1009 lines
44 KiB
TypeScript

import fs from "node:fs";
import { test, expect, type Page } from "@playwright/test";
// 从真实 DOM 点选区域,避免侧栏测试掩盖画布目标无法激活。
async function verifyCanvasTargets(page: Page, manifest: any, pageKey: string) {
const preview = page.locator(".component-template-preview");
const targets = manifest.admin.sections
.filter(
(section: any) =>
section.page === pageKey && (pageKey !== "detail" || section.target === "brand"),
)
.flatMap((section: any) =>
(section.previewTargets ?? [])
.filter((target: any) => !target.composite)
.map((target: any) => target.key),
);
if (pageKey !== "detail") {
targets.push(
...manifest.trustContentTypes.flatMap((item: any) =>
(item.previewTargets ?? [])
.filter((target: any) => target.page === pageKey)
.map((target: any) => target.key),
),
);
targets.push(
...manifest.trustContentTypes
.filter((item: any) => item.pages.includes(pageKey))
.map((item: any) => "trust:" + item.type),
);
}
for (const target of new Set<string>(targets)) {
const elements = preview.locator(`[data-editor-target="${target}"]`);
for (let index = 0; index < (await elements.count()); index++) {
const element = elements.nth(index);
if (!(await element.isVisible())) continue;
await element.scrollIntoViewIfNeeded();
const leafIndex = await element.evaluate((node, key) => {
return Array.from(node.querySelectorAll("*")).findIndex((child) => {
const rect = child.getBoundingClientRect();
return (
child.childElementCount === 0 &&
rect.width > 0 &&
rect.height > 0 &&
child.closest("[data-editor-target]")?.getAttribute("data-editor-target") === key &&
document
.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2)
?.closest("[data-editor-target]")
?.getAttribute("data-editor-target") === key
);
});
}, target);
// 点击区内真实叶子内容,避开圆角的透明区域及嵌套子选区。
const content = leafIndex >= 0 ? element.locator("*").nth(leafIndex) : element;
await content.scrollIntoViewIfNeeded();
const point = await content.evaluate((node) => {
const rect = node.getBoundingClientRect();
const x = rect.left + rect.width / 2;
const y = rect.top + rect.height / 2;
return {
x,
y,
target: document
.elementFromPoint(x, y)
?.closest("[data-editor-target]")
?.getAttribute("data-editor-target"),
};
});
expect(point.target, "实际命中区域:" + target).toBe(target);
const originalNode = await content.elementHandle();
expect(originalNode).not.toBeNull();
await page.mouse.move(point.x, point.y);
await expect
.poll(() =>
preview
.locator(".component-template-preview__outline")
.evaluateAll((outlines) =>
outlines.every((outline) => getComputedStyle(outline).pointerEvents === "none"),
),
)
.toBe(true);
expect(await originalNode!.evaluate((node) => node.isConnected)).toBe(true);
await page.mouse.click(point.x, point.y);
await expect(
preview.locator(".component-template-preview__outline.is-selected"),
).toHaveAttribute("data-selected-target", target);
}
}
}
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
const consoleWarnings = new WeakMap<Page, string[]>();
test.beforeEach(({ page }) => {
const warnings: string[] = [];
consoleWarnings.set(page, warnings);
page.on("console", (message) => {
const text = message.text();
const isWarning =
message.type() === "warning" ||
(message.type() === "error" &&
(text.startsWith("Warning:") ||
text.includes("non-boolean attribute") ||
text.includes("empty string")));
if (isWarning) warnings.push(text);
});
});
test.afterEach(({ page }) => {
expect(consoleWarnings.get(page) ?? []).toEqual([]);
});
const brand = {
id: "brand-fixture",
slug: "preview-fixture",
name: "预览品牌",
templateKey: "food",
tagline: "校园家常餐",
description: "认真做好每一餐",
avatarUrl: "/assets/owner/portrait.jpg",
coverUrl: "",
hours: "每日 17:00",
address: "东门附近",
deliveryNote: "提前预约",
contactPhone: "13800138000",
contactWechat: "food-example",
config: {
visualTemplateKey: "acheng-campus-food",
founder: "测试主理人",
title: "私房菜主理人",
heroImage: "",
visualPresentation: { home: { stallTitle: "原服务地点", worksTitle: "原餐品标题" } },
},
};
const adminOffering = {
id: "menu-fixture",
kind: "service",
name: "家庭聚餐定制",
summary: "为同学聚餐、家庭聚会提供常见的私房菜定制。",
description: "餐品详情",
priceText: "88.88",
coverUrl: brand.avatarUrl,
isEnabled: true,
sortOrder: 0,
config: { categoryKey: "custom" },
};
const adminTrust = {
id: "schedule-fixture",
type: "schedule",
title: "出摊安排",
summary: "工作日安排",
content: "周末安排",
sortOrder: 0,
isPublished: true,
config: {
weekdayLabel: "周一至周五",
weekdayDetail: "东门附近",
weekendLabel: "周六至周日",
weekendDetail: "周末晚间出摊",
},
};
const runtimeWorkspace = {
schemaVersion: "1.0.0",
publication: { status: "published", version: 1 },
brand: {
...brand,
founder: "测试主理人",
title: "私房菜主理人",
visualPresentation: brand.config.visualPresentation,
visualTemplateKey: "acheng-campus-food",
},
templateData: {},
navigation: { tabs: [] },
offerings: [
{
id: adminOffering.id,
name: adminOffering.name,
summary: adminOffering.summary,
priceText: adminOffering.priceText,
coverUrl: adminOffering.coverUrl,
presentation: {
categoryLabel: "定制餐品",
keywords: [],
details: { background: "餐品详情", designConcept: "", crafts: [], materialsList: [] },
},
},
],
inquiryForms: [
{
key: "brand-inquiry",
version: "1",
purpose: "inquiry",
target: "brand",
submissionAction: "create-inquiry",
fields: [
{ key: "name", label: "称呼", type: "text", required: true },
{ key: "message", label: "需求说明", type: "textarea", required: true },
],
},
],
trustItems: [{ ...adminTrust }],
trustPresentation: {},
capabilities: [],
plugins: [{ key: "inquiry", status: "enabled", config: {} }],
visualTemplate: {
key: "",
version: "",
name: "",
supportedIndustryTemplates: [],
variants: {},
},
theme: { colors: {} },
};
const templateContent = JSON.parse(
fs.readFileSync("../../packages/template-acheng-campus-food/template.json", "utf8"),
);
runtimeWorkspace.visualTemplate = {
key: templateContent.visualTemplateKey,
version: templateContent.version,
name: templateContent.displayName,
supportedIndustryTemplates: templateContent.supportedIndustryTemplates,
variants: templateContent.visualPresentation.variants,
};
// 根据真实声明生成完整列表数据,让每种内容区域都实际渲染。
const additionalFoodTrust = templateContent.trustContentTypes
.filter((item: { type: string }) => item.type !== "schedule")
.map(
(declaration: {
type: string;
label: string;
configFields?: Array<{ key: string; input: string; itemFields?: Array<{ key: string }> }>;
}) => ({
id: "food-" + declaration.type,
type: declaration.type,
title: declaration.label,
summary: "测试摘要",
content: "测试正文",
isPublished: true,
sortOrder: 0,
config: Object.fromEntries(
(declaration.configFields ?? []).map((field) => [
field.key,
field.input === "list"
? [
Object.fromEntries(
(field.itemFields ?? []).map((child) => [child.key, child.key + "测试值"]),
),
]
: field.key + "测试值",
]),
),
}),
);
runtimeWorkspace.trustItems.push(...additionalFoodTrust);
test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ page }) => {
test.setTimeout(60000);
let rejectOfferingSave = false;
let sessionAuthenticated = false;
await page.setViewportSize({ width: 1920, height: 1000 });
await page.route("http://localhost:3001/public/workspace**", (route) =>
route.fulfill({ json: runtimeWorkspace }),
);
await page.route("**/api/**", async (route) => {
const request = route.request();
const url = new URL(request.url());
url.pathname = url.pathname.replace(/^\/api/, "");
if (url.pathname === "/admin/session/current") {
if (!sessionAuthenticated) {
return route.fulfill({ status: 401, json: { error: { message: "未登录" } } });
}
return route.fulfill({
json: {
authenticated: true,
displayName: "测试管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "none",
},
});
}
if (url.pathname === "/admin/session/login") {
sessionAuthenticated = true;
return route.fulfill({
json: {
displayName: "测试管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "none",
},
});
}
if (url.pathname === "/admin/brands")
return route.fulfill({ json: [{ id: brand.id, role: "owner", brand }] });
if (url.pathname === "/admin/config/brand" && request.method() === "PATCH") {
const patch = request.postDataJSON();
if (patch.config) patch.config = { ...brand.config, ...patch.config };
Object.assign(brand, patch);
Object.assign(runtimeWorkspace.brand, brand);
return route.fulfill({ json: brand });
}
if (url.pathname === "/admin/config/brand") return route.fulfill({ json: brand });
if (url.pathname === "/admin/workspace/offerings")
return route.fulfill({ json: [adminOffering] });
if (url.pathname === "/admin/workspace/forms")
return route.fulfill({
json: [
{
id: "brand-inquiry",
name: "品牌咨询",
version: 1,
isEnabled: true,
purpose: "inquiry",
targetType: "brand",
submissionAction: "create-inquiry",
fieldsSnapshot: runtimeWorkspace.inquiryForms[0].fields,
},
],
});
if (
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,
summary: adminOffering.summary,
});
return route.fulfill({ json: adminOffering });
}
if (url.pathname === "/admin/config/trust-content")
return route.fulfill({ json: [adminTrust, ...additionalFoodTrust] });
if (
url.pathname === `/admin/config/trust-content/${adminTrust.id}` &&
request.method() === "PATCH"
) {
Object.assign(adminTrust, request.postDataJSON());
Object.assign(runtimeWorkspace.trustItems[0], {
title: adminTrust.title,
config: adminTrust.config,
});
return route.fulfill({ json: adminTrust });
}
if (url.pathname === "/admin/workspace")
return route.fulfill({
json: { brand, installations: [], fields: [], offerings: [], forms: [], templateContent },
});
if (url.pathname === "/admin/workspace/preview")
return route.fulfill({ json: runtimeWorkspace });
if (url.pathname === "/public/templates/food")
return route.fulfill({
json: { name: "餐饮模板", description: "fixture", serviceCategories: [] },
});
if (url.pathname === "/public/workspace") return route.fulfill({ json: runtimeWorkspace });
return route.fulfill({ json: {} });
});
await page.goto(`${adminOrigin}/admin/brand`);
await page.getByLabel("账号").fill("admin");
await page.getByLabel("密码").fill("fixture-password");
await page.locator('button[type="submit"]').click();
await expect(page.getByText("小程序页面配置")).toBeVisible();
await expect(page.getByLabel("品牌名称", { exact: true })).toBeHidden();
await page.getByText("品牌资料", { exact: true }).last().click();
await expect(page.getByLabel("品牌名称", { exact: true })).toBeVisible();
await page.getByText("页面编辑", { exact: true }).click();
const preview = page.locator(".component-template-preview");
await expect(preview.locator(".food-home .name")).toContainText("测试主理人");
await expect(page.getByText("选择要编辑的区域", { exact: true })).toBeVisible();
for (const width of [1920, 1280, 1024, 768, 390]) {
await page.setViewportSize({ width, height: 1000 });
const editor = page.locator(".presentation-editor");
await editor.scrollIntoViewIfNeeded();
await expect
.poll(() => editor.evaluate((element) => element.scrollWidth - element.clientWidth))
.toBeLessThanOrEqual(1);
await editor.screenshot({
path: "../../.codex-tasks/admin-editor-workspace/raw/editor-" + width + ".png",
});
}
await page.setViewportSize({ width: 1920, height: 1000 });
await page.getByRole("button", { name: "选择品牌信息区" }).click();
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
"data-selected-target",
"food.home.brand-card",
);
await expect(page.getByRole("button", { name: "编辑主理人身份" })).toBeVisible();
await page.getByRole("button", { name: "编辑服务地点" }).click();
await expect(page.getByLabel("出摊信息标题")).toBeVisible();
await page.getByRole("button", { name: "选择品牌信息区" }).click();
await page.getByRole("button", { name: "编辑主理人身份" }).click();
await expect(page.getByLabel("主理人姓名")).toBeVisible();
await page.keyboard.press("Escape");
const dimensions = await preview.evaluate((element) => {
const canvas = element.querySelector(".component-template-preview__canvas")!;
const name = element.querySelector(".name")!;
const avatar = element.querySelector(".identity img")!;
return {
width: canvas.getBoundingClientRect().width,
font: parseFloat(getComputedStyle(name).fontSize),
avatar: avatar.getBoundingClientRect().width,
transform: getComputedStyle(canvas.firstElementChild!).transform,
};
});
expect(dimensions.font / dimensions.width).toBeCloseTo(32 / 750, 3);
expect(dimensions.avatar / dimensions.width).toBeCloseTo(128 / 750, 3);
expect(dimensions.transform).toBe("none");
await expect
.poll(() =>
preview.locator(".identity img").evaluate((image: HTMLImageElement) => image.naturalWidth),
)
.toBeGreaterThan(0);
await preview.screenshot({ path: "../../.codex-tasks/preview-proportion/home.png" });
const actionButtons = preview.locator(".food-home .actions button");
await expect(actionButtons).toHaveCount(2);
const previewBox = await preview.locator(".component-template-preview__canvas").boundingBox();
const firstActionBox = await actionButtons.nth(0).boundingBox();
const secondActionBox = await actionButtons.nth(1).boundingBox();
expect(previewBox && firstActionBox && secondActionBox).toBeTruthy();
expect(firstActionBox!.x).toBeGreaterThanOrEqual(previewBox!.x);
expect(secondActionBox!.x + secondActionBox!.width).toBeLessThanOrEqual(
previewBox!.x + previewBox!.width,
);
await expect(actionButtons.nth(0)).toContainText("咨询 / 预订");
await expect(actionButtons.nth(1)).toContainText("查看餐品");
await page.getByRole("button", { name: "选择品牌信息区" }).click();
await page.getByRole("button", { name: "编辑首页操作按钮" }).click();
await expect(page.getByLabel("咨询按钮")).toBeVisible();
await page.keyboard.press("Escape");
await page.getByRole("button", { name: "选择品牌信息区" }).click();
await page.getByRole("button", { name: "编辑服务地点" }).click();
await expect(page.getByText("出摊信息标题")).toBeVisible();
await expect(page.getByText("招牌餐品标题")).toHaveCount(0);
await page.getByLabel("出摊信息标题").fill("后台草稿地点");
await expect(preview.locator(".notice-title")).toContainText("后台草稿地点");
await page.getByRole("button", { name: "保存页面内容" }).click();
await expect(page.getByText("页面内容已保存为草稿,发布后小程序才会更新")).toBeVisible();
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
"data-selected-target",
"food.home.location",
);
await page.getByRole("button", { name: "浏览页面" }).click();
await preview.locator(".food-home .actions button").nth(1).click();
await expect(page.getByText("招牌餐品标题")).toHaveCount(0);
await page.getByRole("button", { name: "点选编辑" }).click();
await page.getByRole("button", { name: "选择品牌信息区" }).click();
await page.getByRole("button", { name: "编辑服务地点" }).click();
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
"data-selected-target",
"food.home.location",
);
await page.keyboard.press("Escape");
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveCount(0);
await page.locator("label.ant-segmented-item").filter({ hasText: "套餐餐品" }).click();
await expect(page.getByRole("dialog", { name: "有尚未保存的修改" })).toHaveCount(0);
await expect(preview.locator(".offering-card")).toHaveCount(1);
await preview.locator(".offering-card .dish-name").click();
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
"data-selected-record-id",
adminOffering.id,
);
await page.getByLabel("名称", { exact: true }).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("名称", { exact: true })).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("名称", { exact: true })).toHaveValue("编辑后的家庭餐");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect.poll(() => adminOffering.name).toBe("编辑后的家庭餐");
await page.reload();
await page.locator("label.ant-segmented-item").filter({ hasText: "套餐餐品" }).click();
await expect(preview.locator(".offering-card")).toContainText("编辑后的家庭餐");
await page.getByText("出摊服务", { exact: true }).click();
await preview.locator('[data-editor-target="trust:schedule"]').click();
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
"data-selected-record-id",
adminTrust.id,
);
await page.getByLabel("工作日标题").fill("周一到周五营业");
await expect(preview.locator(".schedule-card")).toContainText("周一到周五营业");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect.poll(() => adminTrust.config.weekdayLabel).toBe("周一到周五营业");
await page.reload();
await page.getByText("出摊服务", { exact: true }).click();
await expect(preview.locator(".schedule-card")).toContainText("周一到周五营业");
await page.getByText("详情页", { exact: true }).click();
await expect(page.locator(".component-template-preview")).toHaveCount(1);
await expect(preview.locator(".component-template-preview__canvas")).toHaveCount(1);
await expect(preview.locator(".food-detail")).toHaveCount(1);
const detailBounds = await preview.evaluate((element) => {
const canvas = element.querySelector(".component-template-preview__canvas")!;
const bar = element.querySelector(".food-detail .bar")!;
const canvasBox = canvas.getBoundingClientRect();
const barBox = bar.getBoundingClientRect();
return {
position: getComputedStyle(bar).position,
left: barBox.left - canvasBox.left,
right: canvasBox.right - barBox.right,
bottom: canvasBox.bottom - barBox.bottom,
};
});
expect(detailBounds.position).toBe("absolute");
expect(detailBounds.left).toBeGreaterThanOrEqual(-1);
expect(detailBounds.right).toBeGreaterThanOrEqual(-1);
expect(detailBounds.bottom).toBeGreaterThanOrEqual(-1);
await preview.locator(".food-detail .bar").scrollIntoViewIfNeeded();
await expect(preview.locator(".food-detail .bar button")).toBeVisible();
await preview.screenshot({ path: "../../.codex-tasks/preview-proportion/detail.png" });
await expect(page.getByText("详情页由所选业务内容动态生成")).toBeVisible();
await expect(page.getByRole("button", { name: "点选编辑" })).toBeVisible();
await expect(page.getByLabel("价格标题")).toHaveCount(0);
await expect(page.getByLabel("餐品介绍")).toHaveCount(0);
await page.getByRole("button", { name: "详情页咨询入口", exact: true }).click();
await preview.locator(".food-detail .bar button").click();
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
"data-selected-target",
"acheng-campus-food.detail.action",
);
await page.getByLabel("咨询按钮文字", { exact: true }).fill("详情公共按钮回归");
await expect(preview.locator(".food-detail .bar button")).toContainText("详情公共按钮回归");
await page.getByRole("button", { name: "保存页面内容" }).click();
await expect(page.getByText("页面内容已保存为草稿,发布后小程序才会更新")).toBeVisible();
await page.reload();
await page.getByText("详情页", { exact: true }).click();
await expect(preview.locator(".food-detail .bar button")).toContainText("详情公共按钮回归");
await page.getByText("定制/咨询", { exact: true }).click();
await expect(preview.locator(".inquiry-form .form-field")).toHaveCount(2);
await expect(preview.locator(".inquiry-form")).toContainText("称呼");
await expect(preview.locator(".inquiry-form")).toContainText("需求说明");
await preview.locator('[data-editor-target="inquiry-field:name"]').click();
await expect(page.getByLabel("字段标题")).toHaveValue("称呼");
await preview.locator(".inquiry-form").scrollIntoViewIfNeeded();
await preview.screenshot({ path: "../../.codex-tasks/preview-proportion/inquiry.png" });
const formOverflow = await preview
.locator(".inquiry-form")
.evaluate((form) => form.scrollWidth - form.clientWidth);
expect(formOverflow).toBeLessThanOrEqual(1);
await page.getByRole("button", { name: "浏览页面" }).click();
await preview.locator(".inquiry-form input").first().fill("预览访客");
await expect(preview.locator(".inquiry-form input").first()).toHaveValue("预览访客");
await page.getByText("提交成功页", { exact: true }).click();
await expect(preview.locator(".success-page")).toBeVisible();
await expect(preview.locator(".success-page")).toContainText("已收到你的需求");
await page.getByText("记录页", { exact: true }).click();
await expect(preview.locator(".records-page")).toBeVisible();
await expect(preview.locator(".records-page")).toContainText("请在微信小程序内登录查看");
await page.locator("label.ant-segmented-item").filter({ hasText: "套餐餐品" }).click();
await page.getByRole("button", { name: "点选编辑" }).click();
await expect
.poll(() =>
preview.locator(".dish-media img").evaluate((image: HTMLImageElement) => image.naturalWidth),
)
.toBeGreaterThan(0);
for (const width of [390, 320]) {
await preview.locator(".component-template-preview__canvas").evaluate((element, size) => {
(element as HTMLElement).style.width = size + "px";
}, width);
const layout = await preview.evaluate((element) => {
const canvas = element.querySelector(".component-template-preview__canvas")!;
const card = element.querySelector(".offering-card")!;
const media = element.querySelector(".dish-media")!;
return {
canvas: canvas.getBoundingClientRect().width,
overflow: card.scrollWidth - card.clientWidth,
media: media.getBoundingClientRect().width,
};
});
expect(layout.overflow).toBeLessThanOrEqual(1);
expect(layout.media / layout.canvas).toBeCloseTo(224 / 750, 3);
await preview.screenshot({
path: "../../.codex-tasks/preview-proportion/menu-" + width + ".png",
});
}
await preview.locator(".component-template-preview__canvas").evaluate((element) => {
(element as HTMLElement).style.width = "";
});
const inspector = page.locator(".presentation-editor__inspector");
for (const pageKey of [
"home",
"offerings",
"profile",
"service",
"detail",
"inquiry",
"success",
"records",
]) {
const label =
templateContent.navigation.find((item: { page: string }) => item.page === pageKey)?.label ??
(
{ detail: "详情页", inquiry: "咨询页", success: "提交成功页", records: "记录页" } as Record<
string,
string
>
)[pageKey];
await page.getByText(label, { exact: true }).click();
await verifyCanvasTargets(page, templateContent, pageKey);
for (const section of templateContent.admin.sections.filter(
(item: { page: string }) => item.page === pageKey,
)) {
if (pageKey === "detail" && section.target !== "brand") continue;
for (const target of section.previewTargets ?? []) {
if (target.composite) continue;
await page
.locator(".presentation-editor__regions")
.getByRole("button", { name: target.label, exact: true })
.click();
const fields = section.fields.filter(
(field: { previewTarget: string }) => field.previewTarget === target.key,
);
for (const field of fields)
await expect(
inspector.locator(".ant-form-item-label").getByTitle(field.label, { exact: true }),
).toBeVisible();
}
}
if (pageKey !== "detail") {
for (const declaration of templateContent.trustContentTypes.filter(
(item: { pages: string[] }) => item.pages.includes(pageKey),
)) {
await page
.locator(".presentation-editor__regions")
.getByRole("button", { name: declaration.label, exact: true })
.click();
await expect(
inspector.getByLabel(declaration.adminFields.title, { exact: true }),
).toBeVisible();
for (const field of declaration.configFields ?? []) {
await expect(
inspector.locator(".ant-form-item-label").getByTitle(field.label, { exact: true }),
).toBeVisible();
}
}
}
for (const width of [320, 390]) {
await preview.locator(".component-template-preview__canvas").evaluate((element, size) => {
(element as HTMLElement).style.width = size + "px";
}, width);
await expect
.poll(() =>
preview
.locator(".component-template-preview__canvas")
.evaluate((element) => element.scrollWidth - element.clientWidth),
)
.toBeLessThanOrEqual(1);
await preview.screenshot({
path:
"../../.codex-tasks/template-audit-execution/raw/food-" + pageKey + "-" + width + ".png",
});
}
await preview.locator(".component-template-preview__canvas").evaluate((element) => {
(element as HTMLElement).style.width = "";
});
await preview.screenshot({
path: "../../.codex-tasks/template-audit-execution/raw/food-" + pageKey + ".png",
});
}
});
test("林境模板支持首页和主理人区域点选", async ({ page }) => {
test.setTimeout(60000);
let sessionAuthenticated = false;
await page.setViewportSize({ width: 1600, height: 900 });
const editorialBrand = {
...structuredClone(brand),
templateKey: "doors",
avatarUrl: "/template-preview/assets/linjing-editorial/content/founder-portrait.jpg",
config: {
visualTemplateKey: "linjing-editorial",
founder: "林境主理人",
title: "门系统设计师",
heroImage: "/template-preview/assets/linjing-editorial/content/entry-door.jpg",
homeHero: { title: "林境作品" },
visualPresentation: {
home: {
proofEyebrow: "专业积累",
proofTitle: "信任介绍",
manifestoEyebrow: "工作方法",
manifestoTitle: "专业方法",
worksEyebrow: "代表项目",
worksTitle: "作品与服务",
worksAction: "查看作品",
flowEyebrow: "合作方式",
flowTitle: "合作流程",
},
},
},
};
const editorialPillars = [
{ title: "比例与空间", desc: "根据建筑比例设计" },
{ title: "材料与工艺", desc: "可验证的材料标准" },
];
const editorialFlow = [
{ step: "01", name: "需求沟通", desc: "了解现场条件" },
{ step: "02", name: "方案确认", desc: "明确交付范围" },
{ step: "03", name: "制作安装", desc: "按方案实施" },
{ step: "04", name: "验收跟进", desc: "长期维护" },
];
const editorialWorkspace = {
...structuredClone(runtimeWorkspace),
brand: {
...structuredClone(runtimeWorkspace.brand),
...editorialBrand,
...editorialBrand.config,
founder: "林境主理人",
title: "门系统设计师",
heroImage: "/template-preview/assets/linjing-editorial/content/entry-door.jpg",
homeHero: { title: "林境作品" },
},
offerings: structuredClone(runtimeWorkspace.offerings).map((item) => ({
...item,
coverUrl: "/template-preview/assets/linjing-editorial/content/entry-door.jpg",
})),
trustItems: [
{
id: "credential-fixture",
type: "credential",
title: "专业资历",
summary: "建筑与门系统经验",
content: "持续服务私宅项目",
sortOrder: 0,
isPublished: true,
coverUrl: null,
config: {
pillars: editorialPillars,
serviceFlow: editorialFlow,
stats: [
{ value: "10 年", label: "从业经验", sub: "持续服务私宅" },
{ value: "200+", label: "项目落地", sub: "覆盖多个城市" },
{ value: "30+", label: "合作品牌", sub: "长期协作" },
{ value: "98%", label: "客户好评", sub: "来自真实反馈" },
],
},
},
],
trustPresentation: {
pillars: editorialPillars,
serviceFlow: editorialFlow,
stats: [
{ value: "10 年", label: "从业经验", sub: "持续服务私宅" },
{ value: "200+", label: "项目落地", sub: "覆盖多个城市" },
{ value: "30+", label: "合作品牌", sub: "长期协作" },
{ value: "98%", label: "客户好评", sub: "来自真实反馈" },
],
},
};
const editorialContent = JSON.parse(
fs.readFileSync("../../packages/template-linjing-editorial/template.json", "utf8"),
);
editorialWorkspace.visualTemplate = {
key: editorialContent.visualTemplateKey,
version: editorialContent.version,
name: editorialContent.displayName,
supportedIndustryTemplates: editorialContent.supportedIndustryTemplates,
variants: editorialContent.visualPresentation.variants,
};
await page.route("**/api/**", (route) => {
const url = new URL(route.request().url());
const path = url.pathname.replace(/^\/api/, "");
if (path === "/admin/session/current") {
if (!sessionAuthenticated) {
return route.fulfill({ status: 401, json: { error: { message: "未登录" } } });
}
return route.fulfill({
json: {
authenticated: true,
displayName: "测试管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "none",
},
});
}
if (path === "/admin/session/login") {
sessionAuthenticated = true;
return route.fulfill({
json: { displayName: "测试管理员", role: "owner", mustChangePassword: false },
});
}
if (path === "/admin/brands")
return route.fulfill({
json: [{ id: editorialBrand.id, role: "owner", brand: editorialBrand }],
});
if (path === "/admin/config/brand") {
if (route.request().method() === "PATCH") {
const patch = route.request().postDataJSON();
if (patch.config) patch.config = { ...editorialBrand.config, ...patch.config };
Object.assign(editorialBrand, patch);
Object.assign(editorialWorkspace.brand, editorialBrand, editorialBrand.config);
}
return route.fulfill({ json: editorialBrand });
}
if (
path === "/admin/config/trust-content/credential-fixture" &&
route.request().method() === "PATCH"
) {
Object.assign(editorialWorkspace.trustItems[0], route.request().postDataJSON());
Object.assign(editorialWorkspace.trustPresentation, editorialWorkspace.trustItems[0].config);
return route.fulfill({ json: editorialWorkspace.trustItems[0] });
}
if (path === "/admin/workspace/offerings") return route.fulfill({ json: [adminOffering] });
if (
path === "/admin/workspace/offerings/" + adminOffering.id &&
route.request().method() === "PATCH"
) {
Object.assign(adminOffering, route.request().postDataJSON());
Object.assign(editorialWorkspace.offerings[0].presentation, adminOffering.config);
return route.fulfill({ json: adminOffering });
}
if (path === "/admin/config/trust-content")
return route.fulfill({ json: editorialWorkspace.trustItems });
if (path === "/public/templates/doors")
return route.fulfill({
json: { name: "门窗业务", description: "林境页面方案", serviceCategories: [] },
});
if (path === "/admin/workspace")
return route.fulfill({
json: {
brand: editorialBrand,
installations: [],
fields: [],
offerings: [],
forms: [],
templateContent: editorialContent,
},
});
if (path === "/admin/workspace/preview" || path === "/public/workspace")
return route.fulfill({ json: editorialWorkspace });
return route.fulfill({ json: {} });
});
await page.goto(adminOrigin + "/admin/brand");
await page.getByLabel("账号").fill("admin");
await page.getByLabel("密码").fill("fixture-password");
await page.locator('button[type="submit"]').click();
const preview = page.locator(".component-template-preview");
await expect(preview.locator(".editorial-home")).toBeVisible();
await expect(preview.locator(".hero-title")).toContainText("林境作品");
await expect
.poll(() =>
preview.locator(".hero-image").evaluate((image: HTMLImageElement) => image.naturalWidth),
)
.toBeGreaterThan(0);
const stats = preview.locator('[data-editor-target="editorial.home.proof.stats"]');
await expect(stats.locator(":scope > *")).toHaveCount(4);
expect(
await stats.evaluate(
(element) => getComputedStyle(element).gridTemplateColumns.split(" ").length,
),
).toBe(2);
await preview.screenshot({
path: "../../.codex-tasks/template-audit-execution/raw/linjing-stats.png",
});
await stats.click();
const inspector = page.locator(".presentation-editor__inspector");
await expect(inspector.getByRole("heading", { name: "信任数据" })).toBeVisible();
await expect(page.getByLabel("数字或成果", { exact: true }).nth(0)).toHaveValue("10 年");
await expect(page.getByLabel("说明", { exact: true }).nth(1)).toHaveValue("项目落地");
await page.getByLabel("数字或成果", { exact: true }).nth(0).fill("25 年");
await expect(stats.locator(".stat-value").first()).toContainText("25 年");
await inspector.getByRole("button", { name: "保存此项内容" }).click();
await expect.poll(() => editorialWorkspace.trustItems[0].config.stats[0].value).toBe("25 年");
await preview.locator(".founder-name").click();
await expect(inspector.getByRole("heading", { name: "主理人介绍", exact: true })).toBeVisible();
for (const label of ["主理人姓名", "身份或职位", "主理人简介", "主理人标签"])
await expect(inspector.getByLabel(label, { exact: true })).toBeVisible();
await inspector.getByLabel("主理人简介").fill("跨页面共享的简介回归");
await expect(preview.locator(".founder-copy .quote")).toContainText("跨页面共享的简介回归");
await inspector.getByRole("button", { name: "保存页面内容" }).click();
await expect.poll(() => editorialBrand.description).toBe("跨页面共享的简介回归");
await page.reload();
await expect(preview.locator(".founder-copy .quote")).toContainText("跨页面共享的简介回归");
await expect(stats.locator(".stat-value").first()).toContainText("25 年");
await page.getByRole("button", { name: "信任数据", exact: true }).click();
await expect(page.getByLabel("数字或成果", { exact: true }).nth(0)).toHaveValue("25 年");
await preview.locator('[data-editor-target="editorial.home.hero"]').click();
await expect(page.getByLabel("首页主标题")).toBeVisible();
await page.getByLabel("设计理念", { exact: true }).fill("模板专属理念回归");
await expect(preview.locator(".hero-slogan")).toContainText("模板专属理念回归");
await page.getByRole("button", { name: "保存页面内容" }).click();
await expect(page.getByText("页面内容已保存为草稿,发布后小程序才会更新")).toBeVisible();
await page.reload();
await expect(preview.locator(".hero-slogan")).toContainText("模板专属理念回归");
await page.getByRole("button", { name: "信任数据", exact: true }).click();
await page.getByRole("button", { name: "下移第 1 项", exact: true }).click();
await expect(stats.locator(".stat-value").first()).toContainText("200+");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect.poll(() => editorialWorkspace.trustItems[0].config.stats[0].value).toBe("200+");
await page.reload();
await expect(stats.locator(".stat-value").first()).toContainText("200+");
await preview.locator(".pillar-title").first().click();
await expect(page.getByLabel("方法说明", { exact: true }).nth(0)).toBeVisible();
await page.getByLabel("方法名称", { exact: true }).nth(0).fill("方法名称回归");
await expect(preview.locator(".pillar-title").first()).toContainText("方法名称回归");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect(page.getByText("已保存内容草稿,发布后访客才会看到更新")).toBeVisible();
await page.reload();
await expect(preview.locator(".pillar-title").first()).toContainText("方法名称回归");
await preview.locator(".flow-name").first().click();
await expect(page.getByLabel("步骤编号", { exact: true }).nth(0)).toBeVisible();
await expect(page.getByLabel("步骤名称", { exact: true }).nth(0)).toBeVisible();
await page.getByLabel("步骤说明", { exact: true }).nth(0).fill("步骤说明回归");
await expect(preview.locator(".flow-desc").first()).toContainText("步骤说明回归");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect(page.getByText("已保存内容草稿,发布后访客才会看到更新")).toBeVisible();
await page.reload();
await expect(preview.locator(".flow-desc").first()).toContainText("步骤说明回归");
await preview.locator(".work-card").click();
for (const label of ["案例类别", "项目地点", "产品系列", "项目关键词"])
await expect(inspector.getByText(label, { exact: true })).toBeVisible();
await page.getByLabel("项目地点", { exact: true }).fill("项目地点回归");
await expect(preview.locator(".work-category")).toContainText("项目地点回归");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect(page.getByText("已保存内容草稿,发布后访客才会看到更新")).toBeVisible();
await page.reload();
await expect(preview.locator(".work-category")).toContainText("项目地点回归");
await page.getByText("主理人与我", { exact: true }).click();
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveCount(0);
await preview.locator(".editorial-profile .founder").click();
await expect(page.getByRole("button", { name: "信任数据", exact: true })).toHaveCount(0);
await expect(page.getByLabel("主理人姓名")).toBeVisible();
await page.getByLabel("主理人姓名").fill("修改后的主理人");
await expect(preview.locator(".editorial-profile .founder")).toContainText("修改后的主理人");
await page.getByRole("button", { name: "保存页面内容" }).click();
await expect(page.getByText("页面内容已保存为草稿,发布后小程序才会更新")).toBeVisible();
await page.getByRole("button", { name: "服务范围与适用对象", exact: true }).click();
await expect(page.getByText("此区域尚未配置内容")).toBeVisible();
await expect(page.getByRole("button", { name: "配置此区域内容" })).toBeVisible();
for (const pageKey of [
"home",
"offerings",
"profile",
"detail",
"inquiry",
"success",
"records",
]) {
const label =
editorialContent.navigation.find((item: { page: string }) => item.page === pageKey)?.label ??
(
{ detail: "详情页", inquiry: "咨询页", success: "提交成功页", records: "记录页" } as Record<
string,
string
>
)[pageKey];
await page.getByText(label, { exact: true }).click();
await verifyCanvasTargets(page, editorialContent, pageKey);
for (const section of editorialContent.admin.sections.filter(
(item: { page: string }) => item.page === pageKey,
)) {
if (pageKey === "detail" && section.target !== "brand") continue;
for (const target of section.previewTargets ?? []) {
if (target.composite) continue;
await page
.locator(".presentation-editor__regions")
.getByRole("button", { name: target.label, exact: true })
.click();
const fields = section.fields.filter(
(field: { previewTarget: string }) => field.previewTarget === target.key,
);
for (const field of fields)
await expect(
inspector.locator(".ant-form-item-label").getByTitle(field.label, { exact: true }),
).toBeVisible();
}
}
for (const width of [320, 390]) {
await preview.locator(".component-template-preview__canvas").evaluate((element, size) => {
(element as HTMLElement).style.width = size + "px";
}, width);
await expect
.poll(() =>
preview
.locator(".component-template-preview__canvas")
.evaluate((element) => element.scrollWidth - element.clientWidth),
)
.toBeLessThanOrEqual(1);
await preview.screenshot({
path:
"../../.codex-tasks/template-audit-execution/raw/linjing-" +
pageKey +
"-" +
width +
".png",
});
}
await preview.locator(".component-template-preview__canvas").evaluate((element) => {
(element as HTMLElement).style.width = "";
});
await preview.screenshot({
path: "../../.codex-tasks/template-audit-execution/raw/linjing-" + pageKey + ".png",
});
}
});