fix: 完善模板可视化编辑闭环与通用验收

This commit is contained in:
que01 committed 2026-10-10 16:20:08 +08:00
1 parent fa6b492bce
commit 22a82dbfba
39 files changed
+7773 -443

No files matched your search

@@ -0,0 +1,64 @@
# 本轮执行进度
## 当前恢复点
- 任务:现有两模板按通用规则诊断、修复、验收。
- 形态:single-full。
- 进度:7/7;任务真源为 TODO.csv。
- 当前:本轮审计修复和证据归档完成,详见 docs/template-audit-2026-10-10.md。
- 验证:真实数据库集成 41 项通过,覆盖 193 个声明绑定;真实 manifest 浏览器逐页/320 与 390 宽布局、全部实际存在目标的画布内部点选、方法和流程子字段修改重载共 2 项通过(42.3 秒)。
- 静态报告:两模板 blocker 均为 0,food review 55,linjing review 23;命令仍退出 1,保留原报告 completionStatus=unverified。
- 动态审查:raw/manual-review.json 为每条 review 保存来源、只读理由和证据;条件组合未穷举,不将源码审查冒充浏览器全分支验证。
- 数据:只在随机独立 schema 做 integration;没有生产 migration 或 seed 改写。
- 下一步:当前无剩余实现任务;保持未提交 diff,后续模板按相同规则验收。静态 completionStatus 不自动改为完整通过。
## 本轮新增故障与修复
1. 新 config 被旧完整品牌对象覆盖:仅发送改变的标准字段和新 config,剔除模板选择字段。
2. 保存后 Admin 预览读取旧发布快照:从当前品牌记录构建内存草稿,与公开投影共用服务;公开仍读取发布快照。
3. 旧 config.avatarUrl 覆盖共享头像:标准列优先,主动清空后旧别名不得复活。
4. templateFields 错页、templateData 未同步:按 page 分组并同步专属草稿。
5. 列表只检查 binding:补逐个 itemFields 检查及排序;空区域提供内容管理入口。
6. 详情正文与底部按钮共用目标:拆为两个公共编辑区,业务记录仍仅选择预览。
## 画布检查的失败记录
新增检查先后发现测试命中点不正确:圆角透明角落、父容器采样落在子区、装饰图片被遮罩覆盖。原始失败保留 raw/browser-*-failure.log;最终也发现林境 fixture 缺少所有介绍标题,使父区域没有显示文字,补真实结构的标题内容后验收通过。重新审查测试输入后,改为点击目标内有文字的叶子内容,并先确认浏览器真实 elementFromPoint 命中的最近目标。没有强制点击、删业务断言或改变模板视觉。
## 前轮历史(已被本轮验证补充)
# 本轮审计结果
本轮按 skill 完成诊断、修复、回归与剩余项归档;模板整体验收仍为 unverified。
## 静态结果
- acheng-campus-food:blocker 11 → 2;review 120
- linjing-editorial:blocker 26 → 2;review 65
## 已验证
- 林境真实 manifest:主理人完整字段、最近选区、统计 2×2、数值编辑保存重载、共享简介保存重载、侧栏信任记录定位、主理人页不出现首页统计目标。
- 餐饮现有浏览器回归通过,新增共享字段未逐一完成端到端验证。
- 浏览器 2 项通过;模板契约 19 项、诊断器 15 项通过;Admin 单元测试、Admin/Taro 类型、Admin lint 与生产构建、全仓格式及 diff 检查通过。
- 独立随机 schema 的 API 集成 40 项通过;不等于所有新模板字段发布流程逐项已验证。
## 未完成与限制
- 两模板详情页公共按钮文案仍由品牌配置读取,与只读详情预览边界需进一步明确,4 条静态 blocker 保留。
- 动态循环、条件分支等 review 仍需逐项核对,不能用静态报告证明完整。
- 林境截图验证 2×2,使用 fixture 主图且头像未加载,不能作为真实原型视觉一致性证明;原型全量对照未完成。
- 未对每个新增共享字段执行真实数据库发布后公开读取;现有集成通过不能替代该覆盖。
- Admin 构建仍有已有大于 500 kB chunk 提示。
## 经验沉淀
新增多入口绑定同步及未挂载字段保留规则,补入 skill 和回归。未提交 commit,未迁移生产数据。
## 最终门槛
- browser-current.log:2/2 通过,42.3 秒;实际画布目标检查没有使用 force 或 dispatchEvent。
- integration-final.log:41/41 通过,193 个真实绑定保存/草稿/发布验证。
- API Client 3/3、模板契约 19/19、诊断器 19/19;API/Admin/Taro 类型检查通过。
- API/Admin lint、Admin 构建、两模板 H5 与 weapp 构建通过;格式和 diff 检查通过。
- 完整范围、78 条动态映射 review 的源码审阅和视觉限制保留在最终文档及 raw/manual-review.json;没有将静态退出 1 隐藏为通过。
@@ -0,0 +1,3 @@
# 按 template-completion-audit 执行现有模板审计
范围:自动发现两个模板,修复共享字段入口、选区、信任页作用域与实际绑定,运行真实 manifest 浏览器及隔离数据库回归,记录未完成证据。没有生产数据迁移或自动提交。
@@ -0,0 +1,8 @@
id,task,status,acceptance_criteria,validation_command,completed_at,retry_count,notes
1,采集真实基线,DONE,before 报告已存档,node scripts/template-doctor.mjs,2026-10-10,0,退出 1 保留实际问题
2,修复公共编辑和字段绑定,DONE,真实 manifest 修改保存重载测试通过,playwright admin-editor.spec.ts,2026-10-10,1,修复共享字段未挂载覆盖
3,执行审计验证并归档边界,DONE,保留未验证和失败项,pnpm format:check,2026-10-10,0,详情按钮与原型全量验收未完成
4,补齐详情公共文案和真实卡片字段,DONE,所有展示字段有对应入口,pnpm validate:templates,2026-10-10,0,详情正文与底部按钮独立目标;真实卡片字段补齐;模板契约 19 项通过
5,验证真实声明的浏览器编辑闭环,DONE,两个模板真实声明保存重载测试通过,playwright admin-editor.spec.ts,2026-10-10,0,2 项真实 manifest 浏览器通过;含逐页画布内部点击、字段面板、列表子项修改重载和多宽检查
6,验证数据库保存发布隔离,DONE,新增字段真实持久化发布回归通过,pnpm --filter @personal-brand/api test:integration,2026-10-10,0,41 项集成通过;193 个真实绑定隔离数据库保存草稿发布验证
7,归档动态映射和视觉验收,DONE,逐项证据与门槛验证完成,pnpm template:doctor,2026-10-10,4,78 条动态审查归档;最终画布检查通过;原型结构与视觉边界详见 docs/template-audit-2026-10-10.md
1 id task status acceptance_criteria validation_command completed_at retry_count notes
2 1 采集真实基线 DONE before 报告已存档 node scripts/template-doctor.mjs 2026-10-10 0 退出 1 保留实际问题
3 2 修复公共编辑和字段绑定 DONE 真实 manifest 修改保存重载测试通过 playwright admin-editor.spec.ts 2026-10-10 1 修复共享字段未挂载覆盖
4 3 执行审计验证并归档边界 DONE 保留未验证和失败项 pnpm format:check 2026-10-10 0 详情按钮与原型全量验收未完成
5 4 补齐详情公共文案和真实卡片字段 DONE 所有展示字段有对应入口 pnpm validate:templates 2026-10-10 0 详情正文与底部按钮独立目标;真实卡片字段补齐;模板契约 19 项通过
6 5 验证真实声明的浏览器编辑闭环 DONE 两个模板真实声明保存重载测试通过 playwright admin-editor.spec.ts 2026-10-10 0 2 项真实 manifest 浏览器通过;含逐页画布内部点击、字段面板、列表子项修改重载和多宽检查
7 6 验证数据库保存发布隔离 DONE 新增字段真实持久化发布回归通过 pnpm --filter @personal-brand/api test:integration 2026-10-10 0 41 项集成通过;193 个真实绑定隔离数据库保存草稿发布验证
8 7 归档动态映射和视觉验收 DONE 逐项证据与门槛验证完成 pnpm template:doctor 2026-10-10 4 78 条动态审查归档;最终画布检查通过;原型结构与视觉边界详见 docs/template-audit-2026-10-10.md
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+2
View File
@@ -1,5 +1,7 @@
# Product Direction
- 模板新增、绑定修改及宣称完成前,执行 pnpm template:doctor 并遵循 docs/template-completion-rules.md。静态校验、输入框出现、mock 成功不能单独证明完成;回归使用真实 manifest,按区域全部可见变量验收。
- The core product is a personal-brand platform whose primary goal is to build trust and convert that trust into qualified inquiries or collaborations.
- Personal-brand identity, positioning, proof of work, communication expectations, and contact paths are higher priority than any single industry workflow.
- Industry behavior is implemented as replaceable templates. Food, consulting, design, photography, and future industries must not hard-code their terminology or fields into the shared brand model or shared UI.
@@ -21,7 +21,7 @@ export function TemplateListField({
},
]}
>
{(rows, { add, remove }, { errors }) => (
{(rows, { add, remove, move }, { errors }) => (
<Space direction="vertical" style={{ width: "100%" }}>
{rows.map((row, index) => (
<Space key={row.key} align="start" wrap>
@@ -40,6 +40,20 @@ export function TemplateListField({
</Form.Item>
))}
<Button onClick={() => remove(row.name)}>删除</Button>
<Button
aria-label={`上移第 ${index + 1} 项`}
disabled={index === 0}
onClick={() => move(index, index - 1)}
>
上移
</Button>
<Button
aria-label={`下移第 ${index + 1} 项`}
disabled={index === rows.length - 1}
onClick={() => move(index, index + 1)}
>
下移
</Button>
</Space>
))}
<Form.ErrorList errors={errors} />
@@ -44,7 +44,7 @@ export function ComponentTemplatePreview({
if (target?.composite) composite = candidate;
candidate = candidate.parentElement?.closest<HTMLElement>("[data-editor-target]") ?? null;
}
return composite ?? deepest;
return deepest ?? composite;
},
[targets],
);
@@ -36,6 +36,7 @@ import { TemplatePreview } from "./TemplatePreview.js";
import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js";
import {
resolvePreviewSelection,
previewTrustRecordId,
type PreviewSelection,
type PreviewTarget,
} from "./preview-selection.js";
@@ -72,7 +73,12 @@ function trustSection(
description: declaration.help ?? "编辑当前展示内容。",
page,
target: "trust",
previewTargets: [{ key, label: declaration.label }],
previewTargets: [
{ key, label: declaration.label },
...(declaration.previewTargets ?? []).filter(
(target) => !target.page || target.page === page,
),
],
fields: [
{
key: "title",
@@ -94,11 +100,21 @@ function trustSection(
: {}),
...(field === "content" && declaration.required ? { required: true } : {}),
})),
...(declaration.configFields ?? []).map((field) => ({
...field,
previewTarget: `trust:${declaration.type}`,
})),
].map((field) => ({ ...field, previewTarget: `trust:${declaration.type}` })),
...(declaration.configFields ?? [])
.filter((field) => {
const target = declaration.previewTargets?.find(
(target) => target.key === field.previewTarget,
);
return !target?.page || target.page === page;
})
.map((field) => ({
...field,
previewTarget: field.previewTarget ?? `trust:${declaration.type}`,
})),
].map((field) => ({
...field,
previewTarget: (field as TemplateAdminField).previewTarget ?? `trust:${declaration.type}`,
})),
};
}
@@ -185,18 +201,14 @@ export function PresentationEditor({
binding: field.binding ?? `brand.config.templateData.${field.key}`,
}));
return [
...(declaredTemplateFields.length
? [
{
key: "template-data",
title: "模板专属内容",
description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。",
page: templateContent?.templateFields?.[0]?.page ?? "home",
target: "brand" as const,
fields: declaredTemplateFields,
},
]
: []),
...[...new Set(declaredTemplateFields.map((field) => field.page ?? "home"))].map((page) => ({
key: `template-data:${page}`,
title: "模板专属内容",
description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。",
page,
target: "brand" as const,
fields: declaredTemplateFields.filter((field) => (field.page ?? "home") === page),
})),
...(templateContent?.admin.sections ?? []),
].map((section) => ({
...section,
@@ -204,6 +216,8 @@ export function PresentationEditor({
(field) =>
field.binding.startsWith("brand.config.") ||
[
"brand.name",
"brand.tagline",
"brand.avatarUrl",
"brand.description",
"brand.contactPhone",
@@ -226,12 +240,7 @@ export function PresentationEditor({
const selectedPage = pageOptions.some((item) => item.value === activePage)
? activePage
: pageOptions[0]?.value;
const visibleSections = sections.filter(
(section) =>
section.page === selectedPage &&
// 详情页内容来自所选业务记录;不再展示一套额外的品牌级详情编辑器。
!(selectedPage === "detail" && section.target === "brand"),
);
const visibleSections = sections.filter((section) => section.page === selectedPage);
const recordSections = useMemo(
() =>
(templateContent?.trustContentTypes ?? [])
@@ -242,12 +251,17 @@ export function PresentationEditor({
const visibleTargets = useMemo<PreviewTarget[]>(
() =>
[...(templateContent?.admin.sections ?? []), ...recordSections]
.filter((section) => section.page === selectedPage && selectedPage !== "detail")
.filter(
(section) =>
section.page === selectedPage &&
(selectedPage !== "detail" || section.target === "brand"),
)
.flatMap((section) =>
(section.previewTargets ?? []).map((target) => ({
...target,
page: section.page,
source: previewTargetSource(section, target.key),
...(section.key.startsWith("trust:") ? { trustType: section.key.slice(6) } : {}),
})),
)
.concat(
@@ -384,9 +398,22 @@ export function PresentationEditor({
const save = useMutation({
mutationFn: (values: PresentationValues) => {
const nextConfig = applyPresentationValues(config, sections, values);
// 页面内容编辑不提交模板选择,避免触发切换模板的权限校验。
const { visualTemplateKey: _visualTemplateKey, ...contentConfig } = nextConfig;
const standard = applyStandardBrandValues(
brand as unknown as Record<string, unknown>,
sections,
values,
);
const changed = Object.fromEntries(
Object.entries(standard).filter(
([key, value]) =>
key !== "config" && value !== (brand as unknown as Record<string, unknown>)[key],
),
);
return createApiClient().updateAdminBrand({
config: nextConfig,
...applyStandardBrandValues(brand as unknown as Record<string, unknown>, sections, values),
...changed,
config: contentConfig,
});
},
onSuccess: () => {
@@ -436,23 +463,48 @@ export function PresentationEditor({
[brand, previewBrandValues, previewConfig],
);
const handleValuesChange = useCallback(
(_changed: PresentationValues, allValues: PresentationValues) => {
(changed: PresentationValues, allValues: PresentationValues) => {
setBrandDirty(true);
const synchronized: PresentationValues = {
...(form.getFieldsValue(true) as PresentationValues),
...allValues,
};
for (const section of sections) {
for (const field of section.fields) {
const name = presentationFieldName(section.key, field.key);
if (!Object.prototype.hasOwnProperty.call(changed, name)) continue;
for (const peer of sections) {
for (const item of peer.fields) {
if (item.binding === field.binding)
synchronized[presentationFieldName(peer.key, item.key)] = changed[name];
}
}
}
}
form.setFieldsValue(synchronized);
const next = applyBrandPreviewValues(
brand as unknown as Record<string, unknown>,
config,
sections,
allValues,
synchronized,
);
setPreviewConfig((next.config as Record<string, unknown>) ?? {});
setPreviewBrandValues(next);
},
[brand, config, sections],
[brand, config, sections, form],
);
const draftWorkspace = useMemo(() => {
if (!previewWorkspace) return undefined;
const next: RuntimeWorkspace = {
...previewWorkspace,
templateData: {
...previewWorkspace.templateData,
...(previewConfig.templateData &&
typeof previewConfig.templateData === "object" &&
!Array.isArray(previewConfig.templateData)
? (previewConfig.templateData as Record<string, unknown>)
: {}),
},
inquiryForms: previewWorkspace.inquiryForms.map((item) =>
item.key === inquiryRuntime?.key && inquiryDraft ? { ...item, fields: inquiryDraft } : item,
),
@@ -657,9 +709,10 @@ export function PresentationEditor({
? selectedDetailOfferingId
: draftWorkspace?.offerings[0]?.id
: target.source === "trust"
? draftWorkspace?.trustItems.find(
(item) => target.key === `trust:${item.type}`,
)?.id
? previewTrustRecordId(
draftWorkspace?.trustItems ?? [],
target.trustType,
)
: undefined;
handleTargetSelected({
targetKey: target.key,
@@ -689,12 +742,21 @@ export function PresentationEditor({
? "有未保存修改"
: "草稿已同步"}
</Tag>
{selectedPage === "detail" ? (
{selectedPage === "detail" && !selectedTarget ? (
<Alert
type="info"
showIcon
message="详情页由所选业务内容动态生成"
description="选择不同的业务内容即可预览对应详情;内容请在业务提供项中维护。"
description="选择业务内容预览详情,记录内容在业务提供项中维护;公共标题和按钮文案可从左侧区域列表配置,对全部详情生效。"
action={
<Button
onClick={() => {
void navigate("/admin/services");
}}
>
管理业务内容
</Button>
}
/>
) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? (
<InquiryPreviewEditor
@@ -726,9 +788,10 @@ export function PresentationEditor({
? selectedDetailOfferingId
: draftWorkspace?.offerings[0]?.id
: child.source === "trust"
? draftWorkspace?.trustItems.find(
(item) => child.key === `trust:${item.type}`,
)?.id
? previewTrustRecordId(
draftWorkspace?.trustItems ?? [],
child.trustType,
)
: undefined;
handleTargetSelected({
targetKey: child.key,
@@ -807,6 +870,28 @@ export function PresentationEditor({
: {})}
/>
)
) : selectedRecordSource ? (
<Alert
type="info"
showIcon
message="此区域尚未配置内容"
description="创建并启用对应内容后,即可在预览中点选编辑。"
action={
<Button
onClick={() =>
guardDraft(() => {
void navigate(
selectedRecordSource === "trust"
? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}`
: "/admin/services",
);
})
}
>
配置此区域内容
</Button>
}
/>
) : !selectedTarget ? (
<div className="presentation-editor__empty">
<Typography.Title level={5}>选择要编辑的区域</Typography.Title>
@@ -820,7 +905,7 @@ export function PresentationEditor({
layout="vertical"
initialValues={initialValues}
onValuesChange={handleValuesChange}
onFinish={(values) => save.mutate(values)}
onFinish={() => save.mutate(form.getFieldsValue(true) as PresentationValues)}
style={{ minHeight: 0, display: "flex", flexDirection: "column" }}
>
<div style={{ flex: 1 }}>
@@ -34,7 +34,7 @@ function safePath(binding: string): string[] | null {
const prefixes = ["brand.config.", "offering.config.", "trust.config."];
const prefix = prefixes.find((candidate) => binding.startsWith(candidate));
const standardField =
/^(brand\.(avatarUrl|description|contactPhone|contactWechat|address|hours|deliveryNote)|offering\.(name|summary|description|coverUrl|priceText)|trust\.(title|summary|content|coverUrl))$/.test(
/^(brand\.(name|tagline|avatarUrl|description|contactPhone|contactWechat|address|hours|deliveryNote)|offering\.(name|summary|description|coverUrl|priceText)|trust\.(title|summary|content|coverUrl))$/.test(
binding,
);
if (!prefix && !standardField) return null;
@@ -100,6 +100,7 @@ export function applyPresentationValues(
const path = safePath(field.binding);
if (!path) continue;
const raw = values[presentationFieldName(section.key, field.key)];
if (raw === undefined) continue;
const value =
field.input === "list" && Array.isArray(raw)
? field.itemValueKey
@@ -1,11 +1,21 @@
export type PreviewSelection = { targetKey: string; recordId?: string };
// 与模板 slot 一致,优先选择承载结构化内容的记录。
export function previewTrustRecordId(
items: { id?: string; type: string; config: Record<string, unknown> }[],
type: string | undefined,
): string | undefined {
const matches = items.filter((item) => item.type === type);
return (matches.find((item) => Object.keys(item.config).length > 0) ?? matches[0])?.id;
}
export type PreviewTarget = {
key: string;
label: string;
source: "brand" | "offering" | "trust" | "inquiry";
page: string;
composite?: boolean;
trustType?: string;
children?: string[];
};
@@ -18,6 +28,6 @@ export function resolvePreviewSelection(
const target = targets.find((item) => item.key === targetKey && item.page === page);
if (!target) return undefined;
if (recordId && target.source !== "offering" && target.source !== "trust") return undefined;
if (!recordId && (target.source === "offering" || target.source === "trust")) return undefined;
// 空区域仍可选中,编辑面板提供创建内容的入口。
return recordId ? { targetKey, recordId } : { targetKey };
}
+37 -2
View File
@@ -7,7 +7,10 @@ import {
presentationFieldName,
readPresentationValue,
} from "../src/features/brand/presentation-bindings.ts";
import { resolvePreviewSelection } from "../src/features/brand/preview-selection.ts";
import {
resolvePreviewSelection,
previewTrustRecordId,
} from "../src/features/brand/preview-selection.ts";
const config = {
founder: "阿成",
@@ -184,6 +187,38 @@ assert.deepEqual(resolvePreviewSelection("offering.card", "one", targets, "offer
targetKey: "offering.card",
recordId: "one",
});
assert.equal(resolvePreviewSelection("offering.card", undefined, targets, "offerings"), undefined);
assert.deepEqual(resolvePreviewSelection("offering.card", undefined, targets, "offerings"), {
targetKey: "offering.card",
});
assert.equal(resolvePreviewSelection("brand.hero", "one", targets, "home"), undefined);
assert.equal(resolvePreviewSelection("brand.hero", undefined, targets, "offerings"), undefined);
// 未挂载的同源编辑入口不能清空已有字段。
assert.deepEqual(
applyPresentationValues(
{ founder: "保留姓名", title: "保留职位" },
[
{
key: "identity",
fields: [
{ key: "founder", binding: "brand.config.founder" },
{ key: "title", binding: "brand.config.title" },
],
},
],
{ "identity:founder": "修改姓名" },
),
{ founder: "修改姓名", title: "保留职位" },
);
assert.equal(
previewTrustRecordId(
[
{ id: "plain", type: "credential", config: {} },
{ id: "structured", type: "credential", config: { stats: [] } },
],
"credential",
),
"structured",
);
assert.equal(previewTrustRecordId([], "credential"), undefined);
+1 -1
View File
@@ -199,7 +199,7 @@ class AdminWorkspaceController {
@Get("preview")
async getPreviewWorkspace(@Req() request: FastifyRequest): Promise<unknown> {
const { brandId } = this.requireAdmin(request);
return this.publicWorkspace.getForBrandId(brandId);
return this.publicWorkspace.getForBrandId(brandId, true);
}
private jsonObject(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
@@ -18,6 +18,7 @@ import type {
RuntimeTrustItem,
RuntimeWorkspace,
} from "@personal-brand/types";
import { buildBrandReleaseSnapshot } from "../../brand-release.service.js";
import {
projectBrandAliases,
projectOfferingDetails,
@@ -30,14 +31,16 @@ import {
export class PublicWorkspaceService {
constructor(private readonly prisma: PrismaService) {}
async getForBrandId(brandId: string): Promise<unknown> {
async getForBrandId(brandId: string, draft = false): Promise<unknown> {
const release = await this.prisma.brandRelease.findFirst({
where: { brandId, status: "published" },
orderBy: { version: "desc" },
select: { version: true, createdAt: true, snapshot: true },
});
const releaseSnapshot = this.jsonObject(release?.snapshot) as unknown as BrandReleaseSnapshot;
if (!release) {
const draftSnapshot = draft ? await buildBrandReleaseSnapshot(this.prisma, brandId) : null;
const sourceSnapshot = draftSnapshot ?? release?.snapshot;
const releaseSnapshot = this.jsonObject(sourceSnapshot) as unknown as BrandReleaseSnapshot;
if (!release && !draftSnapshot) {
return {
contractVersion: "1.0",
schemaVersion: "1.0.0",
@@ -258,9 +261,9 @@ export class PublicWorkspaceService {
const runtimeWorkspace: RuntimeWorkspace = {
schemaVersion: "1.0.0",
publication: {
status: "published",
version: release.version,
publishedAt: release.createdAt.toISOString(),
status: draftSnapshot ? "draft" : "published",
version: draftSnapshot ? null : (release?.version ?? null),
...(!draftSnapshot && release ? { publishedAt: release.createdAt.toISOString() } : {}),
},
brand: runtimeBrand,
templateData,
+300 -4
View File
@@ -28,6 +28,254 @@ after(async () => {
await prisma.$disconnect();
});
test("real template declarations persist brand offering and trust bindings through draft and publication", async (context) => {
const user = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
const { runtimeContractForBinding } = await import("@personal-brand/types");
const readPath = (object, path) => path.reduce((value, key) => value?.[key], object);
const writePath = (object, path, value) => {
const [key, ...tail] = path;
if (!tail.length) object[key] = value;
else {
object[key] ??= {};
writePath(object[key], tail, value);
}
};
let checked = 0;
for (const slug of ["default-brand", "linjing-doors"]) {
const original = await prisma.brandProfile.findUniqueOrThrow({ where: { slug } });
const originalOffering = await prisma.offering.findFirstOrThrow({
where: { brandId: original.id, isEnabled: true },
orderBy: { sortOrder: "asc" },
});
const originalReleases = await prisma.brandRelease.findMany({
where: { brandId: original.id },
});
const originalTrust = await prisma.trustContent.findMany({
where: { brandId: original.id, isPublished: true },
orderBy: { sortOrder: "asc" },
});
const headers = {
authorization: `Bearer ${signIdentity({ subject: user.id, brandId: original.id, role: "admin" })}`,
};
const manifest = JSON.parse(
(await request("/admin/workspace", { headers })).body,
).templateContent;
const fields = [
...manifest.admin.sections.flatMap((section) => section.fields),
...(manifest.templateFields ?? []),
];
const distinct = [...new Map(fields.map((field) => [field.binding, field])).values()];
const brandPatch = { config: structuredClone(original.config ?? {}) };
const offeringPatch = { config: structuredClone(originalOffering.config ?? {}) };
const expected = [];
for (const field of distinct) {
const [source, ...path] = field.binding.split(".");
if (!["brand", "offering"].includes(source)) continue;
const token = "binding-" + slug + "-" + field.key;
const value =
field.input === "list"
? [
field.itemValueKey
? token
: Object.fromEntries(
(field.itemFields ?? []).map((child) => [child.key, token + "-" + child.key]),
),
]
: field.input === "image"
? "https://example.com/" + token + ".jpg"
: field.input === "phone"
? "13800138001"
: field.input === "number"
? 73
: field.input === "boolean"
? true
: token;
writePath(source === "brand" ? brandPatch : offeringPatch, path, value);
expected.push({ field, source, path, value });
}
delete brandPatch.config.visualTemplateKey;
const createdTrustIds = [];
try {
assert.equal(
(await request("/admin/config/brand", { method: "PATCH", headers, payload: brandPatch }))
.statusCode,
200,
);
assert.equal(
(
await request("/admin/workspace/offerings/" + originalOffering.id, {
method: "PATCH",
headers,
payload: offeringPatch,
})
).statusCode,
200,
);
const savedBrand = JSON.parse((await request("/admin/config/brand", { headers })).body);
const expectedTrust = [];
for (const declaration of manifest.trustContentTypes) {
const records = originalTrust.filter((item) => item.type === declaration.type);
let record =
records.find((item) => Object.keys(item.config ?? {}).length > 0) ?? records[0];
if (!record) {
record = await prisma.trustContent.create({
data: {
brandId: original.id,
type: declaration.type,
title: "字段验收占位",
content: "字段验收占位",
isPublished: true,
config: {},
},
});
createdTrustIds.push(record.id);
}
const patch = { config: structuredClone(record.config ?? {}) };
const trustFields = [
...["title", "summary", "content"]
.filter((key) => !declaration.hideStandardFields?.includes(key))
.map((key) => ({ key, binding: "trust." + key, input: "text" })),
...(declaration.configFields ?? []),
];
for (const field of trustFields) {
const token = "binding-" + slug + "-" + declaration.type + "-" + field.key;
const path = field.binding.split(".").slice(1);
const existing = readPath(record, path);
const value =
field.input === "list"
? Array.from(
{ length: Array.isArray(existing) && existing.length ? existing.length : 1 },
(_, index) =>
Object.fromEntries(
(field.itemFields ?? []).map((child) => [
child.key,
token + "-" + index + "-" + child.key,
]),
),
)
: token;
writePath(patch, path, value);
expectedTrust.push({ id: record.id, path, value, binding: field.binding });
}
const updated = await request("/admin/config/trust-content/" + record.id, {
method: "PATCH",
headers,
payload: patch,
});
assert.equal(updated.statusCode, 200, updated.body);
}
const savedTrust = JSON.parse(
(await request("/admin/config/trust-content", { headers })).body,
);
const savedOffering = JSON.parse(
(await request("/admin/workspace/offerings", { headers })).body,
).find((item) => item.id === originalOffering.id);
const draft = JSON.parse((await request("/admin/workspace/preview", { headers })).body);
for (const item of expectedTrust) {
assert.deepEqual(
readPath(
savedTrust.find((record) => record.id === item.id),
item.path,
),
item.value,
item.binding + " persistence",
);
assert.deepEqual(
readPath(
draft.trustItems.find((record) => record.id === item.id),
item.path,
),
item.value,
item.binding + " draft projection",
);
checked += 1;
}
for (const item of expected) {
assert.deepEqual(
readPath(item.source === "brand" ? savedBrand : savedOffering, item.path),
item.value,
item.field.binding + " persistence",
);
const contract = runtimeContractForBinding(item.field.binding);
assert.ok(contract, item.field.binding);
let runtimePath = contract.runtimePath.replace(/^workspace\./, "");
if (item.field.binding === "offering.config.detailHero")
runtimePath = "offerings[].presentation.heroImage";
const offeringIndex = draft.offerings.findIndex(
(offering) => offering.id === originalOffering.id,
);
runtimePath = runtimePath.replace("offerings[]", "offerings." + offeringIndex);
assert.deepEqual(
readPath(draft, runtimePath.split(".")),
item.value,
item.field.binding + " draft projection",
);
checked += 1;
}
const publish = await request("/admin/releases/publish", {
method: "POST",
headers,
payload: { note: "真实声明全部品牌和业务字段验收" },
});
assert.equal(publish.statusCode, 201, publish.body);
const publicWorkspace = JSON.parse(
(await request("/public/workspace?brandSlug=" + slug)).body,
);
assert.deepEqual(publicWorkspace.brand, draft.brand);
assert.deepEqual(publicWorkspace.templateData, draft.templateData);
assert.deepEqual(publicWorkspace.offerings, draft.offerings);
assert.deepEqual(publicWorkspace.trustItems, draft.trustItems);
assert.deepEqual(publicWorkspace.trustPresentation, draft.trustPresentation);
} finally {
const columns = [
"name",
"tagline",
"description",
"avatarUrl",
"contactPhone",
"contactWechat",
"address",
"coverUrl",
"hours",
"deliveryNote",
"config",
];
await prisma.brandProfile.update({
where: { id: original.id },
data: Object.fromEntries(columns.map((key) => [key, original[key]])),
});
const offeringColumns = ["name", "summary", "description", "priceText", "coverUrl", "config"];
await prisma.offering.update({
where: { id: originalOffering.id },
data: Object.fromEntries(offeringColumns.map((key) => [key, originalOffering[key]])),
});
await prisma.brandRelease.deleteMany({
where: { brandId: original.id, id: { notIn: originalReleases.map((item) => item.id) } },
});
for (const record of originalTrust)
await prisma.trustContent.update({
where: { id: record.id },
data: {
title: record.title,
summary: record.summary,
content: record.content,
config: record.config,
},
});
await prisma.trustContent.deleteMany({ where: { id: { in: createdTrustIds } } });
for (const release of originalReleases)
await prisma.brandRelease.update({
where: { id: release.id },
data: { status: release.status },
});
}
}
assert.ok(checked > 100, "真实声明应覆盖两个模板全部品牌和业务字段");
context.diagnostic(
"Validated " + checked + " manifest bindings through persistence draft and publication",
);
});
test("food structured edits survive publication and reach the generated page slots", async () => {
const { readFileSync } = await import("node:fs");
const { runInNewContext } = await import("node:vm");
@@ -1325,11 +1573,15 @@ test("admin can install a template and public workspace exposes enabled configur
}
});
test("admin preview workspace is brand-scoped and exposes only the published runtime", async () => {
test("admin preview workspace is authorized and brand-scoped draft runtime", async () => {
const user = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
const token = signIdentity({ subject: user.id, brandId, role: "admin" });
const unauthorized = await request("/admin/workspace/preview");
assert.equal(unauthorized.statusCode, 401);
const invalid = await request("/admin/workspace/preview", {
headers: { authorization: "Bearer invalid-preview-token" },
});
assert.equal(invalid.statusCode, 401);
const wrongRole = await request("/admin/workspace/preview", {
headers: { authorization: `Bearer ${customerToken}` },
});
@@ -1339,12 +1591,39 @@ test("admin preview workspace is brand-scoped and exposes only the published run
});
assert.equal(authorized.statusCode, 200);
const workspace = JSON.parse(authorized.body);
assert.equal(workspace.publication?.status, "published");
assert.equal(workspace.publication?.status, "draft");
assert.equal(
workspace.brand.slug,
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).slug,
);
assert.equal(workspace.brand.visualTemplateKey, "acheng-campus-food");
const unpublishedBrand = await prisma.brandProfile.create({
data: {
slug: "unpublished-preview-fixture",
name: "未发布预览品牌",
templateKey: "personal",
config: { visualTemplateKey: "linjing-editorial" },
adminMemberships: { create: { adminUserId: user.id, role: "owner" } },
},
});
try {
const draftToken = signIdentity({
subject: user.id,
brandId: unpublishedBrand.id,
role: "admin",
});
const draft = await request("/admin/workspace/preview", {
headers: { authorization: `Bearer ${draftToken}` },
});
assert.equal(draft.statusCode, 200);
assert.equal(JSON.parse(draft.body).brand.slug, unpublishedBrand.slug);
assert.equal(JSON.parse(draft.body).publication.status, "draft");
const publicResult = await request("/public/workspace?brandSlug=" + unpublishedBrand.slug);
assert.equal(JSON.parse(publicResult.body).publication.status, "unpublished");
assert.equal(JSON.parse(publicResult.body).brand, null);
} finally {
await prisma.brandProfile.delete({ where: { id: unpublishedBrand.id } });
}
});
test("admin can customize workspace fields with brand isolation", async () => {
@@ -1518,7 +1797,8 @@ test("edited template facts reach public workspace only after publication", asyn
const changedDetailHero = "https://example.com/integration-detail.jpg";
const changedDetailBackground = "集成测试案例详情正文";
const changedTemplateData = "集成测试设计理念";
const changedStats = [{ value: "42", label: "测试成果" }];
const changedStats = [{ value: "42", label: "测试成果", sub: "持久化子标题" }];
const changedDescription = "唯一品牌简介保存发布验证";
const obsolete = await prisma.trustContent.create({
data: {
brandId: doorsBrand.id,
@@ -1537,6 +1817,7 @@ test("edited template facts reach public workspace only after publication", asyn
method: "PATCH",
headers,
payload: {
description: changedDescription,
config: {
homeHero: { ...brandConfig.homeHero, title: changedTitle },
visualPresentation: {
@@ -1553,6 +1834,8 @@ test("edited template facts reach public workspace only after publication", asyn
},
});
assert.equal(brandUpdate.statusCode, 200);
const reloadedBrand = await request("/admin/config/brand", { headers });
assert.equal(JSON.parse(reloadedBrand.body).description, changedDescription);
const trustUpdate = await request(`/admin/config/trust-content/${trust.id}`, {
method: "PATCH",
headers,
@@ -1575,9 +1858,21 @@ test("edited template facts reach public workspace only after publication", asyn
},
});
assert.equal(offeringUpdate.statusCode, 200);
const preview = await request("/admin/workspace/preview", { headers });
assert.equal(preview.statusCode, 200);
const savedDraft = JSON.parse(preview.body);
assert.equal(savedDraft.publication.status, "draft");
assert.equal(savedDraft.brand.description, changedDescription);
assert.equal(savedDraft.templateData.designPhilosophy, changedTemplateData);
assert.deepEqual(savedDraft.trustPresentation.stats, changedStats);
assert.equal(
savedDraft.offerings.find((item) => item.id === offering.id).presentation.area,
changedArea,
);
const draftView = JSON.parse((await request("/public/workspace?brandSlug=linjing-doors")).body);
assert.deepEqual(draftView.brand.homeHero, before.brand.homeHero);
assert.equal(draftView.brand.description, before.brand.description);
assert.equal(
draftView.brand.visualPresentation.success.intro,
before.brand.visualPresentation.success.intro,
@@ -1603,6 +1898,7 @@ test("edited template facts reach public workspace only after publication", asyn
(await request("/public/workspace?brandSlug=linjing-doors")).body,
);
assert.equal(afterPublish.brand.homeHero.title, changedTitle);
assert.equal(afterPublish.brand.description, changedDescription);
assert.equal(afterPublish.templateData.designPhilosophy, changedTemplateData);
assert.equal(Object.hasOwn(afterPublish.templateData, "internalOnly"), false);
assert.equal(afterPublish.brand.visualPresentation.success.intro, changedIntro);
@@ -1623,7 +1919,7 @@ test("edited template facts reach public workspace only after publication", asyn
await prisma.trustContent.delete({ where: { id: obsolete.id } });
await prisma.brandProfile.update({
where: { id: doorsBrand.id },
data: { config: originalBrandConfig },
data: { config: originalBrandConfig, description: doorsBrand.description },
});
await prisma.trustContent.update({
where: { id: trust.id },
+443 -206
View File
@@ -1,4 +1,73 @@
import { test, expect } from "@playwright/test";
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;
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
);
});
}, 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);
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 brand = {
@@ -94,157 +163,44 @@ const runtimeWorkspace = {
capabilities: [],
theme: { colors: {} },
};
const templateContent = {
displayName: "餐饮模板",
navigation: [
{ key: "home", page: "home", label: "首页" },
{ key: "offerings", page: "offerings", label: "套餐餐品" },
{ key: "service", page: "service", label: "出摊服务" },
{ key: "detail", page: "detail", label: "详情页" },
{ key: "inquiry", page: "inquiry", label: "定制/咨询" },
{ key: "success", page: "success", label: "提交成功页" },
{ key: "records", page: "records", label: "记录页" },
],
assetSlots: [],
trustContentTypes: [
{
type: "schedule",
label: "每周出摊安排",
adminFields: { title: "安排标题", summary: "安排摘要", content: "安排正文" },
hideStandardFields: ["summary", "content"],
pages: ["service"],
configFields: [
{
key: "weekdayLabel",
binding: "trust.config.weekdayLabel",
label: "工作日标题",
input: "text",
},
{
key: "weekdayDetail",
binding: "trust.config.weekdayDetail",
label: "工作日地点",
input: "text",
},
{
key: "weekendLabel",
binding: "trust.config.weekendLabel",
label: "周末标题",
input: "text",
},
{
key: "weekendDetail",
binding: "trust.config.weekendDetail",
label: "周末地点",
input: "text",
},
],
},
],
admin: {
sections: [
{
key: "detailCopy",
title: "餐品说明",
description: "编辑详情页说明",
page: "detail",
target: "brand",
previewTargets: [{ key: "acheng-campus-food.detail.detailCopy", label: "餐品说明" }],
fields: [
{
key: "priceLabel",
binding: "brand.config.visualPresentation.detail.priceLabel",
label: "价格标题",
input: "text",
previewTarget: "acheng-campus-food.detail.detailCopy",
},
],
},
{
key: "offering-card",
title: "餐品卡片",
description: "编辑单条餐品",
page: "offerings",
target: "offering",
previewTargets: [{ key: "acheng-campus-food.offerings.item", label: "餐品卡片" }],
fields: [
{
key: "name",
binding: "offering.name",
label: "餐品名称",
input: "text",
previewTarget: "acheng-campus-food.offerings.item",
},
{
key: "summary",
binding: "offering.summary",
label: "餐品简介",
input: "textarea",
previewTarget: "acheng-campus-food.offerings.item",
},
],
},
{
key: "home",
title: "首页内容",
description: "首页可编辑项",
page: "home",
target: "brand",
previewTargets: [
{
key: "food.home.brand-card",
label: "品牌信息区",
composite: true,
children: ["food.home.identity", "food.home.location", "food.home.actions"],
},
{ key: "food.home.identity", label: "主理人身份" },
{ key: "food.home.location", label: "服务地点" },
{ key: "food.home.offerings-heading", label: "餐品区域标题" },
{ key: "food.home.actions", label: "首页操作按钮" },
],
fields: [
{
key: "identity",
binding: "brand.config.founder",
previewTarget: "food.home.identity",
label: "主理人姓名",
input: "text",
},
{
key: "stallTitle",
binding: "brand.config.visualPresentation.home.stallTitle",
previewTarget: "food.home.location",
label: "出摊信息标题",
input: "text",
},
{
key: "stallTime",
binding: "brand.config.visualPresentation.home.stallTime",
previewTarget: "food.home.location",
label: "营业时间说明",
input: "text",
},
{
key: "worksTitle",
binding: "brand.config.visualPresentation.home.worksTitle",
previewTarget: "food.home.offerings-heading",
label: "招牌餐品标题",
input: "text",
},
{
key: "primaryAction",
binding: "brand.config.visualPresentation.home.primaryAction",
previewTarget: "food.home.actions",
label: "咨询按钮",
input: "text",
},
],
},
],
},
};
const templateContent = JSON.parse(
fs.readFileSync("../../packages/template-acheng-campus-food/template.json", "utf8"),
);
// 根据真实声明生成完整列表数据,让每种内容区域都实际渲染。
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;
await page.setViewportSize({ width: 1920, height: 1000 });
await page.route("http://localhost:3001/public/workspace**", (route) =>
@@ -266,7 +222,9 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
if (url.pathname === "/admin/brands")
return route.fulfill({ json: [{ id: brand.id, role: "owner", brand }] });
if (url.pathname === "/admin/config/brand" && request.method() === "PATCH") {
Object.assign(brand, request.postDataJSON());
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 });
}
@@ -309,7 +267,7 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
return route.fulfill({ json: adminOffering });
}
if (url.pathname === "/admin/config/trust-content")
return route.fulfill({ json: [adminTrust] });
return route.fulfill({ json: [adminTrust, ...additionalFoodTrust] });
if (
url.pathname === `/admin/config/trust-content/${adminTrust.id}` &&
request.method() === "PATCH"
@@ -439,17 +397,17 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
"data-selected-record-id",
adminOffering.id,
);
await page.getByLabel("餐品名称").fill("编辑后的家庭餐");
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("餐品名称")).toHaveValue("编辑后的家庭餐");
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("餐品名称")).toHaveValue("编辑后的家庭餐");
await expect(page.getByLabel("名称", { exact: true })).toHaveValue("编辑后的家庭餐");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect.poll(() => adminOffering.name).toBe("编辑后的家庭餐");
await page.reload();
@@ -492,9 +450,22 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
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: "点选编辑" })).toHaveCount(0);
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("称呼");
@@ -543,81 +514,178 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
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);
await page.setViewportSize({ width: 1600, height: 900 });
const editorialBrand = {
...structuredClone(brand),
templateKey: "personal",
avatarUrl: "/assets/acheng-campus-food/owner/portrait.jpg",
config: {
visualTemplateKey: "linjing-editorial",
founder: "林境主理人",
title: "建筑设计师",
heroImage: "/assets/tab/home.png",
heroImage: "/assets/acheng-campus-food/owner/portrait.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: "/assets/tab/home.png",
heroImage: "/assets/acheng-campus-food/owner/portrait.jpg",
homeHero: { title: "林境作品" },
},
offerings: [],
trustItems: [],
};
const editorialContent = {
displayName: "林境模板",
navigation: [
{ key: "home", page: "home", label: "首页" },
{ key: "profile", page: "profile", label: "主理人与我" },
offerings: structuredClone(runtimeWorkspace.offerings).map((item) => ({
...item,
coverUrl: "/assets/acheng-campus-food/owner/portrait.jpg",
})),
trustItems: [
{
id: "credential-fixture",
type: "credential",
title: "专业资历",
summary: "建筑与门系统经验",
content: "持续服务私宅项目",
config: {
pillars: editorialPillars,
serviceFlow: editorialFlow,
stats: [
{ value: "10 年", label: "从业经验", sub: "持续服务私宅" },
{ value: "200+", label: "项目落地", sub: "覆盖多个城市" },
{ value: "30+", label: "合作品牌", sub: "长期协作" },
{ value: "98%", label: "客户好评", sub: "来自真实反馈" },
],
},
},
],
assetSlots: [],
trustContentTypes: [],
admin: {
sections: [
{
key: "home",
title: "首页主视觉",
page: "home",
target: "brand",
previewTargets: [{ key: "editorial.home.hero", label: "首页主视觉" }],
fields: [
{
key: "heroTitle",
binding: "brand.config.homeHero.title",
label: "首页标题",
input: "text",
previewTarget: "editorial.home.hero",
},
],
},
{
key: "identity",
title: "主理人与联系方式",
page: "profile",
target: "brand",
previewTargets: [
{ key: "linjing-editorial.profile.identity", label: "主理人与联系方式" },
],
fields: [
{
key: "founder",
binding: "brand.config.founder",
label: "主理人姓名",
input: "text",
previewTarget: "linjing-editorial.profile.identity",
},
],
},
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"),
);
await page.route("**/api/**", (route) => {
const url = new URL(route.request().url());
const path = url.pathname.replace(/^\/api/, "");
@@ -629,7 +697,34 @@ test("林境模板支持首页和主理人区域点选", async ({ page }) => {
return route.fulfill({
json: [{ id: editorialBrand.id, role: "owner", brand: editorialBrand }],
});
if (path === "/admin/config/brand") return route.fulfill({ json: 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/personal")
return route.fulfill({
json: { name: "个人品牌", description: "林境模板", serviceCategories: [] },
@@ -661,12 +756,154 @@ test("林境模板支持首页和主理人区域点选", async ({ page }) => {
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("1. 数字或成果")).toHaveValue("10 年");
await expect(page.getByLabel("2. 说明")).toHaveValue("项目落地");
await page.getByLabel("1. 数字或成果").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("1. 数字或成果")).toHaveValue("25 年");
await preview.locator('[data-editor-target="editorial.home.hero"]').click();
await expect(page.getByLabel("首页标题")).toBeVisible();
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("1. 方法说明")).toBeVisible();
await page.getByLabel("1. 方法名称").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("1. 步骤编号")).toBeVisible();
await expect(page.getByLabel("1. 步骤名称")).toBeVisible();
await page.getByLabel("1. 步骤说明").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('[data-editor-target="linjing-editorial.profile.identity"]').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",
});
}
});
@@ -0,0 +1,25 @@
# 0022 模板完成度诊断与修复闭环
## 背景
可点击但变量不全、数据来源错位、编辑标记破坏网格反复出现。旧检查只证明字段存在;简化 manifest 的 fixture 不能验证真实层级。
## 决策
以视觉区域为验收单位,连接 renderer 数据读取、manifest 绑定、编辑交互、保存重载发布、视觉证据。静态诊断自动发现模板,输出问题码及位置;未验证不能当作通过。规则见 [模板完成度规则](../template-completion-rules.md)。
## 替代方案
增加点选标记不能判断字段完整性;模板特判不能覆盖新模板;静态分析不能证明浏览器布局和持久化。采用静态诊断加真实 manifest 驱动交互验证。
## 后果
编译通过的模板也可能未完成。诊断器测试通过不代表模板通过。同一事实的多个入口必须写回同一值;单记录编辑器不能静默承接跨来源保存。
## 迁移计划
先提供独立只读命令和 skill,生成现有缺口报告,逐项修复补证据。不修改数据库、seed 或旧发布快照。不将现有缺口隐藏在绿色旧校验中;所有模板交付必须执行新诊断并归档剩余项。
## 草稿预览修正
Admin 的 /admin/workspace/preview 从当前品牌记录构建内存快照,并使用公开 Runtime 的同一投影服务,返回 publication.status=draft。公开路由仍只读取发布快照。此更改解决保存后预览退回发布旧值、未发布品牌无法预览的问题,不创建数据库发布记录。原有客户端 Runtime 类型增加 draft 状态,集成测试同时验证授权、品牌范围、草稿重载和发布隔离。
+2
View File
@@ -21,6 +21,8 @@
## 模板与配置包
- 执行 pnpm template:doctor 并遵循 [模板完成度规则](template-completion-rules.md),诊断未解决项和未验证项不能视为完成;
- 模板声明必须真正驱动安装和升级,不能只增加类型而保留 Controller 硬编码;
- 每个页面上的品牌事实、信任资料、业务详情和可编辑文案都必须来自 Runtime 数据,并在同一页面声明对应 Admin editor binding;`pnpm validate:templates` 的逐页 renderer / editor 契约测试通过后才能判定模板完成;
- 每种模板信任内容必须声明实际展示页面,逐页测试要同时验证“声明的类型有 renderer 消费”和“renderer 使用的类型已声明”;
@@ -0,0 +1,31 @@
---
name: template-completion-audit
description: Diagnose and repair personal-brand template editability, region selection, field bindings, persistence and visual regressions. Use for new template acceptance or recurring template editor defects; distinguish static coverage from complete delivery.
---
# Template completion audit
在目标仓库运行;先读取 AGENTS.md、docs/template-completion-rules.md 和 docs/engineering-delivery-checklist.md。此 skill 的版本化来源位于 docs/skills/template-completion-audit/SKILL.md;仓库规则是唯一标准。
## 执行
1. 确认当前分支、已有修改、真实模板包与原始视觉参考。使用真实 manifest,禁止为方便测试重新写简化声明。
2. 运行 pnpm template:doctor --output <task-dir>/before.json;按需加 --template <packageKey>。退出 1 是发现问题,退出 2 是工具错误;完整保留两者,不吞掉失败。
3. 检查每个区域的全部展示变量、来源、绑定、页面和记录 ID;特别核查共享事实、fallback 优先级、组合选区对子区的拦截、列表项和未消费字段。未知映射标 review,不猜测为通过。
4. 优先修同根公共逻辑,补失败回归后小批修改。诊断命令只读,不提供猜测式 --fix。catalog 和格式化可以自动运行;不以清报告为由复制数据库字段、修改 seed、删除显示内容或放宽检查。用户授权编辑不等于授权破坏性迁移。
5. 对每个修改的字段使用独特值执行点选、预览、正确请求、保存、重载、发布验证;真实数据库测试必须隔离。mock PATCH 只能证明前端请求;必须说明缺失的持久化证据。
6. 比较原型与多屏宽截图,特别核查新增 DOM wrapper 对 grid/flex 直接子项的影响。未见原型时记录视觉基线待核实。
7. 重跑诊断、相关测试、类型与构建门槛;保存 after.json、命令结果、截图及剩余项。连续 3 次同类失败时重新审查数据链和测试输入,不能继续堆补丁。
8. 将新的故障模式写入通用规则和故障注入测试。报告工具交付与模板完成两种状态,不能用静态绿色或单条 fixture 成功代替完整验收。
## 验收证据
记录模板/代码版本、真实 manifest 来源、page/target/binding 覆盖、失败与修复、保存重载发布证据、视觉对照、未验证项。对静态分析无法处理的跨组件、动态路径和布局问题保留人工审查及浏览器测试,不自动免责。
已有案例:整张主理人卡片只编辑标签;统计块绑定到介绍标题;额外 wrapper 将 2×2 变成 1×4;trust 子目标缺页面或导航无法解析记录;两套简介导致保存值不是渲染值。将这些作为复现模式,不把具体模板布局写成所有模板的规则。
新增共享字段入口时,检查同一 binding 多个表单名的同步;未挂载字段必须保留原值。真实 manifest 的多入口修改、保存、重载是必测项,单入口 fixture 不能替代。
保存回归必须检查请求 payload 中的新 config 不被旧对象覆盖,内容修改不携带模板选择字段。验证真实 Admin 草稿预览刷新后仍为新值,同时公开 Runtime 保持旧值直至发布。模板专属字段须按 page 分组并同步 templateData;列表逐个核对 itemFields,空区域必须有配置入口。
检查标准品牌列与旧 config 同名冲突和清空优先级;主动清空后旧别名不得恢复。除侧栏逐页字段覆盖外,从画布内部叶子内容实际点击并核对选区;不能使用强制点击伪造可用性证据。
+57
View File
@@ -0,0 +1,57 @@
# 两套模板编辑闭环验收(2026-10-10)
范围为餐饮 acheng-campus-food 和林境 linjing-editorial 的可编辑区域、实际字段、草稿与发布数据链。基线 commit 为 fa6b492,分支 feat/admin-component-preview;结果对应当前未提交 diff。两个模板 manifest 均为包内 template.json,版本 1.0.0,测试直接读取真实声明,没有重写简化 manifest。
## 本轮修复
- 主理人区域展示的姓名、身份、简介、头像和标签提供完整入口;多个入口同步共享值。
- 组合区域只导航,子区域优先点选;信任内容按页面定位真实记录,列表每个子字段可编辑并支持排序。
- 林境信任数据在原 stats 容器加标记,保持 2×2;专业方法、合作流程及主理人页范围/说明独立编辑。
- 餐饮日程的工作日和周末各自对应 4 个配置字段;配送方式对应自取/配送标题和说明;流程对应结构化步骤及附注。
- 首页业务卡片声明补齐实际显示的地点、类别、系列、关键词、优先图片;移除该卡不消费的字段入口。
- 详情仅选择业务记录预览,并提供业务管理入口;详情正文公共文案与底部咨询入口分为两个可编辑区域。
- 保存仅发送真正修改的标准字段和新 config,防止旧 config 覆盖新值;跨区域未挂载修改保留,普通内容保存不携带切换模板字段。
- 模板专属字段按各自 page 分组,预览同步 templateData。
- Admin 预览改用当前品牌草稿的内存快照;公开 Runtime 仍只读取发布快照。未发布品牌也能预览,不产生发布记录。
- 标准品牌列优先于旧 config 同名残留;主动清空后旧别名也不能恢复旧联系方式或简介。
- 无记录的区域仍可定位,并显示进入相应内容管理页面的配置入口。
## 验证证据
原始证据目录为 .codex-tasks/template-audit-execution/raw/。
| 范围 | 证据与结果 |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| 数据持久化 | integration-final.log:41 项通过;其中 generic manifest 回归对 193 个 distinct binding 写入独特值,验证 Admin 重载、草稿 Runtime、发布后公开输出 |
| 草稿与公开隔离 | 同一集成套件覆盖草稿改变而公开保持旧值、发布后更新、未发布品牌、授权及品牌范围 |
| 授权 | Admin preview 无凭证、无效凭证、customer 错误角色和授权成功路径均有自动化验证 |
| 实际编辑器 | browser-current.log:使用两套真实 manifest;逐页侧栏字段、实际画布区域内部点击、共享字段与业务记录修改重载、保存失败保留、切页保护 |
| 列表 | 林境统计值、排序、专业方法名称、流程说明修改预览及保存重载;数据库回归覆盖所有声明列表 itemFields |
| 详情/表单 | 动态业务内容不在详情编辑;公共底部按钮独立点选、修改、保存重载;咨询字段预览、成功页和记录页可显示 |
| 布局 | 每个页面在 320/390 像素画布验证无横向溢出,并归档对应截图;统计检查两列四项;详情按钮限制在画布范围 |
| 契约与诊断器 | contracts-final.log:19 项;doctor-tests-final.log:19 项,含故障注入 |
| 客户端与纯函数 | api-client-final.log:3 项;types 标准列冲突及清空回归、Admin binding 单元测试通过 |
| 工程门槛 | API/Admin/Taro 类型检查,API/Admin lint,Admin build,food/linjing 各自 H5 和 weapp 构建,format:check 与 git diff --check |
集成测试使用随机隔离 schema,迁移并 seed 后运行,最后删除测试 schema;临时发布记录和 fixture 有清理。没有修改生产数据、Prisma schema、migration 或 seed。
## 动态映射与原型审阅
原始诊断 after.json 保留餐饮 55 条、林境 23 条 review,blocker 均为 0。命令仍退出 1,completionStatus 保持 unverified。manual-review.json 为全部 78 条记录保存来源审查结论与证据,不修改原报告,也不把人工审查当自动豁免。
主要审查结论:动态 trust 目标用 type 和实际 id 定位;formTargets 分别提供咨询/成功/记录页目标;工作日/周末和 pickup/delivery 动态字段都有实际声明;作品副标题由 series 与 keywords 派生;餐品数量和分类由业务列表派生,无独立重复字段;图标轮换仅为固定视觉资源。
对照原始 React 参考:餐饮位于 /home/que01/下载/阿成校园餐---微信小程序原型/,林境位于 /home/que01/下载/林境门作-·-别墅门系统高级工坊.zip。检查本次编辑标记保持统计、日程、配送及合作流程的原布局结构;没有通过 CSS 改写视觉来迁就数据。截图使用确定性本地图片 fixture,林境借用本地餐饮照片,证明布局与图片加载,不代表原型照片或像素级一致。
条件项逐行核对了可选文字/联系方式、列表、详情记录、附注分隔符等显示逻辑。浏览器验证完整内容和代表性的空区域/失败分支,未穷举所有字段为空的排列组合,也没有验证每个字段在真实微信 IDE 中的交互。当前证据不应解释为永久保证全部模板或所有未来分支无缺陷。
## 后续模板的固定验收方式
1. package manifest 自动发现,运行 template:doctor 保存基线和退出码。
2. 以视觉选区核对全部数据来源、页作用域、列表子字段和只读理由。
3. 对真实 manifest 执行画布点选及编辑器检查,不能只点侧栏。
4. 隔离数据库对 distinct binding 验证保存、草稿、发布输出及授权,不能用 mock PATCH 替代。
5. 对照原型与多宽截图,新增 wrapper 必须核查 grid/flex 直接子项。
6. 归档人工动态审查与未验证范围;新故障加入诊断器/回归与 skill。
Admin 构建的既有大于 500 kB chunk 警告仍存在。后续由 Admin 前端维护工作处理分包,本轮不提高阈值掩盖警告。浏览器 NO_COLOR/FORCE_COLOR 冲突提示来自运行环境,不影响测试结果。
+63
View File
@@ -0,0 +1,63 @@
# 模板完成度规则
## 区域与数据层级
直接编辑区域须提供全部展示变量,名称与边界一致。主理人卡片不能只有标签字段。共享姓名、头像等允许多个入口,但指向唯一权威值并说明影响范围。
组合区域仅导航、不承载字段;子区可独立点选,父容器不能吞掉点击。详情页为动态记录预览,选择记录并链接业务编辑入口。访客输入和系统状态只读并说明原因。
列表支持每项编辑、增删和必要排序;数量和布局由模板约束决定,不把四项、两列强加给所有模板。
## 完成门槛
| 层次 | 需要证明 | 历史问题 |
| ---------- | -------------------------------------------------- | ----------------------------------------- |
| 数据来源 | 每个展示变量有真实绑定或只读理由 | description/slogan、未消费的 brandPromise |
| 区域覆盖 | 选中边界内所有变量可修改 | 主理人只剩标签、统计只有介绍标题 |
| 层级与记录 | 最近目标点选,导航与画布一致,页面和 recordId 正确 | 自定义 trust 目标找不到记录 |
| 编辑闭环 | 独特值修改、预览变化、正确请求、重载保留 | 只验证输入框出现 |
| 发布隔离 | 草稿不影响公开内容、发布生效、品牌隔离 | 旧快照、跨品牌污染 |
| 视觉 | 原型对照、行列、宽度、按钮、滚动、多屏宽 | wrapper 使 2×2 变 1×4 |
| 异常 | 空值仍可配置、失败保留输入、重试、切页保护 | 无记录无入口、部分失败仍提示成功 |
## 自动诊断边界
运行 pnpm template:doctor,自动扫描 packages/template-*/template.json 和 Taro renderer;支持 --template packageKey、--output path 输出 JSON。每个问题包含 code、page、target、binding、位置和修复方向。
staticStatus 只代表支持范围内的静态检查。completionStatus 保持 unverified,直到交互、隔离数据库保存发布、视觉证据经过审阅。退出 0 仅表示静态通过,1 表示 blocker/review,2 表示执行故障。
AST 解析可追踪 workspace.brand、presentation、object 和局部别名。动态路径、跨组件和间接映射等未知情况标为 review,不能猜测为通过。诊断器包含正反故障注入测试。
## 修复闭环
1. 保留真实 manifest、renderer、原型、失败截图和只读报告。
2. 按 code/page/target/binding 聚合同根问题,先修共享逻辑,再修声明;测试必须使用真实 manifest。
3. 先补失败回归。确定性格式化、catalog 生成可自动执行;业务字段归属、迁移、视觉调整按证据判断,不能自动猜测覆盖用户数据。
4. 小批修复,优先原 DOM 加标记;新增 wrapper 必查 grid/flex 直接子项和 CSS 选择器。
5. 重跑诊断及修改、保存、重载、公开输出;跨来源保存检查部分失败,mock 成功不能替代数据库证据。
6. 保留剩余项;连续 3 次同类失败重新审查原始数据链和测试输入,禁止删断言或弱化规则求绿。
7. 新故障加入诊断规则、测试和文档;skill 引用统一规则,不复制两套标准。
## 验收证据
归档 Git commit/未提交 diff、模板版本、命令结果、页面区域字段覆盖、原型与截图、隔离数据来源、保存重载发布测试定位和剩余项。状态为 pass/fail/unverified/not-applicable,最后一种必须附原因,不记录凭证和客户私密数据。
CI 可执行 pnpm test:template-doctor 和诊断命令。新模板自动扫描。现有缺口或动态证据未验证时不得声称模板全部完成。
## 共享绑定回归补充
同一绑定出现在多个区域时,修改任一入口后其他入口必须同步。未挂载字段不得以 undefined 覆盖已有配置;保存当前区域也不能清空其他区域。回归必须至少覆盖首页修改、主理人页修改、保存及重载,不能只使用单字段 fixture。
## 保存与预览补充
保存请求仅包含允许修改的字段及新配置。禁止在新 config 后展开带旧 config 的完整品牌对象,禁止内容编辑携带 visualTemplateKey 触发模板切换权限。共享表单保存须保留跨区域修改。
Admin 预览读取当前品牌的草稿 Runtime,公开接口读取已发布快照。两者共用投影逻辑;保存后预览、重新加载预览、发布后公开读取必须分别测试。不得用 mock 返回最新数据掩盖真实预览接口仍读旧发布快照。
templateFields 按各自 page 分组;预览同步 templateData。列表审计必须核对 itemFields 的每个实际展示子字段,列表 binding 存在不代表子字段完整。缺少记录的区域仍须提供配置入口。
## 旧配置与标准列优先级
Runtime 合并标准品牌列和模板 config 时,标准列是共享品牌事实的权威值。同名旧 config 不得覆盖标准列;标准列主动清空为 null 时,旧 slogan、phone、wechat、studioAddress 等别名也不能恢复旧内容。回归须注入冲突值及清空值,验证草稿和公开投影一致,不依赖清洗数据库掩盖优先级错误。
画布点选测试必须点击实际区域内部的叶子内容,并验证目标和记录 ID;侧栏定位通过不能代替画布可点击。应避开圆角透明角落,不能用强制点击或 dispatchEvent 掩盖真实命中问题。
+8 -7
View File
@@ -15,16 +15,17 @@ This document records where template-controlled content is stored and how it rea
## Food Schedule Example
The food template declares the schedule type for the `home` and `service` pages. Its Admin fields map directly to existing database columns:
餐饮模板的日程在 service 页展示,使用 TrustContent.config 的浅层字段:
- `adminFields.title` edits `TrustContent.title`.
- `adminFields.summary` edits the primary weekday schedule in `TrustContent.summary`.
- `adminFields.content` edits the weekend and supplementary schedule in `TrustContent.content`.
- The public workspace returns those values as a `RuntimeTrustItem`; the home and service page renderers read `item.summary` and `item.content`.
- title 编辑日程区块标题。
- weekdayLabel、weekdayTag、weekdayDetail、weekdayHours 编辑工作日卡片。
- weekendLabel、weekendTag、weekendDetail、weekendHours 编辑周末卡片。
- status 编辑日程状态。summary 和 content 已在该类型声明中隐藏,不参与日程渲染。
- 配送范围与流程分别使用 coverage 和 process 类型的配置字段,不能把摘要或正文作为第二套结构化数据入口。
No schedule-specific Prisma migration is needed. Different templates can choose different field labels while retaining the shared trust-content storage contract.
编辑器区域列表和 renderer 的 slot 均优先使用带结构化配置的记录。页面点选传递真实 recordId;没有记录时提供内容管理入口。保存只影响品牌草稿,发布后公开 Runtime 才更新。模板样例仍属于包,不作为数据库注册目录。
The Admin editor lists the selected template's declared trust types and uses their `adminFields` labels, help, and placeholders. In the food workspace, the service page links directly to the trust-content editor, so the schedule is configured under **内容管理 → 信任内容 → 出摊安排**. Saving changes the brand's draft content; the Mini Program sees the new values after the next publication.
详情页中的业务记录只提供选择预览;公共标题和按钮文案通过品牌配置区域编辑,影响全部详情页,不复制到每条业务记录。
## Inquiry Field Runtime Mapping
+3 -1
View File
@@ -29,7 +29,9 @@
"preview:templates": "pnpm --filter @personal-brand/taro dev:preview",
"build:admin:preview": "PREVIEW_ALL_TEMPLATES=true API_BASE_URL=/api PREVIEW_PUBLIC_PATH=/template-preview/ pnpm --filter @personal-brand/taro build:preview && node scripts/package-template-preview.cjs && VITE_APP_BASE_PATH=/admin/ VITE_API_BASE_URL=/api pnpm --filter @personal-brand/admin build",
"build:taro:food": "pnpm --filter @personal-brand/taro build:h5 && pnpm --filter @personal-brand/taro build:weapp",
"build:taro:linjing": "TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:h5 && TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:weapp"
"build:taro:linjing": "TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:h5 && TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:weapp",
"template:doctor": "node scripts/template-doctor.mjs",
"test:template-doctor": "node --test scripts/test/template-doctor.test.mjs"
},
"devDependencies": {
"@eslint/js": "^9.17.0",
+1
View File
@@ -136,6 +136,7 @@ export interface AdminTemplateContent {
placeholder?: string;
required?: boolean;
configFields?: TemplateAdminField[];
previewTargets?: Array<{ key: string; label: string; page?: string }>;
maxPublishedItems?: number;
hideStandardFields?: Array<"summary" | "content">;
}>;
@@ -192,6 +192,30 @@ export const generatedTemplatePackageRegistry = [
"label": "记录数量单位",
"input": "text",
"previewTarget": "acheng-campus-food.profile.identity"
},
{
"key": "acheng-campus-food_profile_identity_avatarUrl",
"binding": "brand.avatarUrl",
"label": "主理人头像",
"input": "image",
"previewTarget": "acheng-campus-food.profile.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "acheng-campus-food_profile_identity_name",
"binding": "brand.name",
"label": "品牌名称",
"input": "text",
"previewTarget": "acheng-campus-food.profile.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "acheng-campus-food_profile_identity_description",
"binding": "brand.description",
"label": "主理人简介",
"input": "textarea",
"previewTarget": "acheng-campus-food.profile.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
}
],
"previewTargets": [
@@ -235,6 +259,14 @@ export const generatedTemplatePackageRegistry = [
"label": "封面图片",
"input": "image",
"previewTarget": "acheng-campus-food.home.offering"
},
{
"key": "detailHero",
"binding": "offering.config.detailHero",
"label": "详情主图",
"input": "image",
"previewTarget": "acheng-campus-food.home.offering",
"help": "此图优先用于卡片和详情;未填写时使用封面图片。"
}
],
"previewTargets": [
@@ -367,6 +399,38 @@ export const generatedTemplatePackageRegistry = [
"binding": "brand.config.visualPresentation.home.manifestoTitle",
"label": "出餐承诺标题",
"input": "text"
},
{
"key": "food_home_identity_avatarUrl",
"binding": "brand.avatarUrl",
"label": "主理人头像",
"input": "image",
"previewTarget": "food.home.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "food_home_identity_description",
"binding": "brand.description",
"label": "主理人简介",
"input": "textarea",
"previewTarget": "food.home.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "food_home_location_address",
"binding": "brand.address",
"label": "服务地址",
"input": "text",
"previewTarget": "food.home.location",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "food_home_hero_name",
"binding": "brand.name",
"label": "品牌名称",
"input": "text",
"previewTarget": "food.home.hero",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
}
]
},
@@ -380,16 +444,23 @@ export const generatedTemplatePackageRegistry = [
{
"key": "processAction",
"binding": "brand.config.visualPresentation.service.processAction",
"label": "流程咨询按钮",
"label": "咨询按钮文字",
"input": "text",
"placeholder": "例如:立即预订",
"previewTarget": "acheng-campus-food.service.service"
"previewTarget": "food.service.process-action"
}
],
"previewTargets": [
{
"key": "acheng-campus-food.service.service",
"label": "出摊服务页说明"
"label": "出摊服务页说明",
"composite": true,
"children": [
"food.service.process-action"
]
},
{
"key": "food.service.process-action",
"label": "咨询按钮文字"
}
]
},
@@ -427,6 +498,21 @@ export const generatedTemplatePackageRegistry = [
"label": "封面图片",
"input": "image",
"previewTarget": "acheng-campus-food.offerings.item"
},
{
"key": "detailHero",
"binding": "offering.config.detailHero",
"label": "详情主图",
"input": "image",
"previewTarget": "acheng-campus-food.offerings.item",
"help": "此图优先用于卡片和详情;未填写时使用封面图片。"
},
{
"key": "categoryLabel",
"binding": "offering.config.categoryLabel",
"label": "餐品类别",
"input": "text",
"previewTarget": "acheng-campus-food.offerings.item"
}
],
"previewTargets": [
@@ -677,21 +763,6 @@ export const generatedTemplatePackageRegistry = [
"label": "食材与搭配标题",
"input": "text",
"previewTarget": "acheng-campus-food.detail.detailCopy"
},
{
"key": "inquiryAction",
"binding": "brand.config.visualPresentation.detail.inquiryAction",
"label": "咨询按钮文字",
"input": "text",
"previewTarget": "acheng-campus-food.detail.detailCopy"
},
{
"key": "inquiryHint",
"binding": "brand.config.visualPresentation.detail.inquiryHint",
"label": "咨询后的处理说明",
"help": "只写能够兑现的联系和确认方式。",
"input": "textarea",
"previewTarget": "acheng-campus-food.detail.detailCopy"
}
],
"previewTargets": [
@@ -801,6 +872,58 @@ export const generatedTemplatePackageRegistry = [
"label": "咨询记录页"
}
]
},
{
"key": "offerings_detailAction",
"title": "详情按钮文字",
"description": "此页同类按钮共用此文案。",
"page": "offerings",
"target": "brand",
"previewTargets": [
{
"key": "acheng-campus-food.offerings.action",
"label": "详情按钮文字"
}
],
"fields": [
{
"key": "detailAction",
"binding": "brand.config.visualPresentation.offerings.detailAction",
"label": "详情按钮文字",
"input": "text",
"previewTarget": "acheng-campus-food.offerings.action"
}
]
},
{
"key": "detailAction",
"title": "详情页咨询入口",
"description": "公共按钮与提示,对所有业务详情生效。",
"page": "detail",
"target": "brand",
"fields": [
{
"key": "inquiryAction",
"binding": "brand.config.visualPresentation.detail.inquiryAction",
"label": "咨询按钮文字",
"input": "text",
"previewTarget": "acheng-campus-food.detail.action"
},
{
"key": "inquiryHint",
"binding": "brand.config.visualPresentation.detail.inquiryHint",
"label": "咨询后的处理说明",
"help": "只写能够兑现的联系和确认方式。",
"input": "textarea",
"previewTarget": "acheng-campus-food.detail.action"
}
],
"previewTargets": [
{
"key": "acheng-campus-food.detail.action",
"label": "详情页咨询入口"
}
]
}
]
},
@@ -1493,7 +1616,7 @@ export const generatedTemplatePackageRegistry = [
"key": "designPhilosophy",
"page": "home",
"binding": "brand.config.templateData.designPhilosophy",
"previewTarget": "linjing-editorial.home.home",
"previewTarget": "editorial.home.hero",
"label": "设计理念",
"help": "用一两句话说明你的设计方法。",
"input": "textarea",
@@ -1558,6 +1681,38 @@ export const generatedTemplatePackageRegistry = [
"required": true,
"placeholder": "例如:别墅门系统主理人",
"previewTarget": "linjing-editorial.profile.identity"
},
{
"key": "avatarUrl",
"binding": "brand.avatarUrl",
"label": "主理人头像",
"input": "image",
"previewTarget": "linjing-editorial.profile.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "contactPhone",
"binding": "brand.contactPhone",
"label": "联系电话",
"input": "phone",
"previewTarget": "linjing-editorial.profile.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "contactWechat",
"binding": "brand.contactWechat",
"label": "联系微信",
"input": "text",
"previewTarget": "linjing-editorial.profile.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "address",
"binding": "brand.address",
"label": "联系地址",
"input": "text",
"previewTarget": "linjing-editorial.profile.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
}
],
"previewTargets": [
@@ -1581,26 +1736,55 @@ export const generatedTemplatePackageRegistry = [
"input": "text",
"previewTarget": "linjing-editorial.home.offering"
},
{
"key": "summary",
"binding": "offering.summary",
"label": "简介",
"input": "textarea",
"previewTarget": "linjing-editorial.home.offering"
},
{
"key": "priceText",
"binding": "offering.priceText",
"label": "价格说明",
"input": "text",
"previewTarget": "linjing-editorial.home.offering"
},
{
"key": "coverUrl",
"binding": "offering.coverUrl",
"label": "封面图片",
"input": "image",
"previewTarget": "linjing-editorial.home.offering"
},
{
"key": "detailHero",
"binding": "offering.config.detailHero",
"label": "详情主图",
"input": "image",
"previewTarget": "linjing-editorial.home.offering",
"help": "此图优先用于卡片和详情;未填写时使用封面图片。"
},
{
"key": "categoryLabel",
"binding": "offering.config.categoryLabel",
"label": "案例类别",
"input": "text",
"previewTarget": "linjing-editorial.home.offering"
},
{
"key": "area",
"binding": "offering.config.area",
"label": "项目地点",
"input": "text",
"previewTarget": "linjing-editorial.home.offering"
},
{
"key": "series",
"binding": "offering.config.series",
"label": "产品系列",
"input": "text",
"previewTarget": "linjing-editorial.home.offering"
},
{
"key": "keywords",
"binding": "offering.config.keywords",
"label": "项目关键词",
"input": "list",
"itemValueKey": "value",
"itemFields": [
{
"key": "value",
"label": "关键词"
}
],
"previewTarget": "linjing-editorial.home.offering"
}
],
"previewTargets": [
@@ -1619,7 +1803,7 @@ export const generatedTemplatePackageRegistry = [
"previewTargets": [
{
"key": "editorial.home.identity",
"label": "主理人标签"
"label": "主理人介绍"
},
{
"key": "editorial.home.hero",
@@ -1639,7 +1823,21 @@ export const generatedTemplatePackageRegistry = [
},
{
"key": "linjing-editorial.home.home",
"label": "首页品牌表达"
"label": "首页品牌表达",
"composite": true,
"children": [
"editorial.home.identity",
"editorial.home.hero",
"editorial.home.proof",
"editorial.home.manifesto",
"editorial.home.works",
"editorial.home.flow",
"linjing-editorial.home.offering"
]
},
{
"key": "editorial.home.flow",
"label": "合作流程标题"
}
],
"fields": [
@@ -1707,49 +1905,105 @@ export const generatedTemplatePackageRegistry = [
"binding": "brand.config.visualPresentation.home.worksAction",
"label": "查看案例入口",
"input": "text",
"previewTarget": "linjing-editorial.home.home"
"previewTarget": "editorial.home.works"
},
{
"key": "flowEyebrow",
"binding": "brand.config.visualPresentation.home.flowEyebrow",
"label": "合作流程小标题",
"input": "text",
"previewTarget": "linjing-editorial.home.home"
"previewTarget": "editorial.home.flow"
},
{
"key": "flowTitle",
"binding": "brand.config.visualPresentation.home.flowTitle",
"label": "项目流程标题",
"input": "text",
"previewTarget": "linjing-editorial.home.home"
"previewTarget": "editorial.home.flow"
},
{
"key": "heroTitle",
"binding": "brand.config.homeHero.title",
"label": "首页主标题",
"input": "text",
"previewTarget": "linjing-editorial.home.home"
"previewTarget": "editorial.home.hero"
},
{
"key": "heroEyebrow",
"binding": "brand.config.homeHero.eyebrow",
"label": "主图项目标注",
"input": "text",
"previewTarget": "linjing-editorial.home.home"
"previewTarget": "editorial.home.hero"
},
{
"key": "heroDescription",
"binding": "brand.config.homeHero.slogan",
"label": "首页主图说明",
"input": "textarea",
"previewTarget": "linjing-editorial.home.home"
"previewTarget": "editorial.home.hero"
},
{
"key": "heroAction",
"binding": "brand.config.homeHero.cta",
"label": "主图行动文字",
"input": "text",
"previewTarget": "linjing-editorial.home.home"
"previewTarget": "editorial.home.hero"
},
{
"key": "avatarUrl",
"binding": "brand.avatarUrl",
"label": "主理人头像",
"input": "image",
"previewTarget": "editorial.home.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "founder",
"binding": "brand.config.founder",
"label": "主理人姓名",
"input": "text",
"previewTarget": "editorial.home.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "title",
"binding": "brand.config.title",
"label": "身份或职位",
"input": "text",
"previewTarget": "editorial.home.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "description",
"binding": "brand.description",
"label": "主理人简介",
"input": "textarea",
"previewTarget": "editorial.home.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "heroFallback_name",
"binding": "brand.name",
"label": "备用主标题(品牌名称)",
"input": "text",
"previewTarget": "editorial.home.hero",
"help": "共享品牌值;对应主图文案为空时使用。"
},
{
"key": "heroFallback_tagline",
"binding": "brand.tagline",
"label": "备用标注(品牌标语)",
"input": "text",
"previewTarget": "editorial.home.hero",
"help": "共享品牌值;对应主图文案为空时使用。"
},
{
"key": "heroFallback_description",
"binding": "brand.description",
"label": "备用说明(品牌简介)",
"input": "text",
"previewTarget": "editorial.home.hero",
"help": "共享品牌值;对应主图文案为空时使用。"
}
]
},
@@ -1776,7 +2030,7 @@ export const generatedTemplatePackageRegistry = [
"input": "textarea"
}
],
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.coverage"
},
{
"key": "warranty",
@@ -1791,83 +2045,102 @@ export const generatedTemplatePackageRegistry = [
"input": "textarea"
}
],
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.warranty"
},
{
"key": "recordsTitle",
"binding": "brand.config.visualPresentation.profile.recordsTitle",
"label": "咨询记录入口标题",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.records"
},
{
"key": "recordsSubtitle",
"binding": "brand.config.visualPresentation.profile.recordsSubtitle",
"label": "咨询记录入口说明",
"input": "textarea",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.records"
},
{
"key": "coverageTitle",
"binding": "brand.config.visualPresentation.profile.coverageTitle",
"label": "服务区域标题",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.coverage"
},
{
"key": "warrantyTitle",
"binding": "brand.config.visualPresentation.profile.warrantyTitle",
"label": "履约说明标题",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.warranty"
},
{
"key": "phoneLabel",
"binding": "brand.config.visualPresentation.profile.phoneLabel",
"label": "电话标签",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.identity"
},
{
"key": "wechatLabel",
"binding": "brand.config.visualPresentation.profile.wechatLabel",
"label": "微信标签",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.identity"
},
{
"key": "addressLabel",
"binding": "brand.config.visualPresentation.profile.addressLabel",
"label": "地址标签",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.identity"
},
{
"key": "callAction",
"binding": "brand.config.visualPresentation.profile.callAction",
"label": "拨打电话按钮",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.identity"
},
{
"key": "copyAction",
"binding": "brand.config.visualPresentation.profile.copyAction",
"label": "复制微信按钮",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.identity"
},
{
"key": "recordsCountUnit",
"binding": "brand.config.visualPresentation.profile.recordsCountUnit",
"label": "记录数量单位",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.identity"
}
],
"previewTargets": [
{
"key": "linjing-editorial.profile.profileDetails",
"label": "服务区域与履约说明"
"label": "主理人页面",
"composite": true,
"children": [
"linjing-editorial.profile.identity",
"linjing-editorial.profile.records",
"linjing-editorial.profile.coverage",
"linjing-editorial.profile.warranty"
]
},
{
"key": "linjing-editorial.profile.records",
"label": "咨询记录入口"
},
{
"key": "linjing-editorial.profile.coverage",
"label": "服务区域"
},
{
"key": "linjing-editorial.profile.warranty",
"label": "履约说明"
}
]
},
@@ -1905,6 +2178,28 @@ export const generatedTemplatePackageRegistry = [
"label": "封面图片",
"input": "image",
"previewTarget": "linjing-editorial.offerings.item"
},
{
"key": "detailHero",
"binding": "offering.config.detailHero",
"label": "详情主图",
"input": "image",
"previewTarget": "linjing-editorial.offerings.item",
"help": "此图优先用于卡片和详情;未填写时使用封面图片。"
},
{
"key": "categoryLabel",
"binding": "offering.config.categoryLabel",
"label": "案例类别",
"input": "text",
"previewTarget": "linjing-editorial.offerings.item"
},
{
"key": "area",
"binding": "offering.config.area",
"label": "项目地点",
"input": "text",
"previewTarget": "linjing-editorial.offerings.item"
}
],
"previewTargets": [
@@ -2173,21 +2468,6 @@ export const generatedTemplatePackageRegistry = [
"label": "材料说明标题",
"input": "text",
"previewTarget": "linjing-editorial.detail.detailCopy"
},
{
"key": "inquiryAction",
"binding": "brand.config.visualPresentation.detail.inquiryAction",
"label": "咨询按钮文字",
"input": "text",
"previewTarget": "linjing-editorial.detail.detailCopy"
},
{
"key": "inquiryHint",
"binding": "brand.config.visualPresentation.detail.inquiryHint",
"label": "咨询后的处理说明",
"help": "只填写能兑现的服务安排。",
"input": "textarea",
"previewTarget": "linjing-editorial.detail.detailCopy"
}
],
"previewTargets": [
@@ -2297,6 +2577,58 @@ export const generatedTemplatePackageRegistry = [
"label": "咨询记录页"
}
]
},
{
"key": "offerings_detailAction",
"title": "详情按钮文字",
"description": "此页同类按钮共用此文案。",
"page": "offerings",
"target": "brand",
"previewTargets": [
{
"key": "linjing-editorial.offerings.action",
"label": "详情按钮文字"
}
],
"fields": [
{
"key": "detailAction",
"binding": "brand.config.visualPresentation.offerings.detailAction",
"label": "详情按钮文字",
"input": "text",
"previewTarget": "linjing-editorial.offerings.action"
}
]
},
{
"key": "detailAction",
"title": "详情页咨询入口",
"description": "公共按钮与提示,对所有业务详情生效。",
"page": "detail",
"target": "brand",
"fields": [
{
"key": "inquiryAction",
"binding": "brand.config.visualPresentation.detail.inquiryAction",
"label": "咨询按钮文字",
"input": "text",
"previewTarget": "linjing-editorial.detail.action"
},
{
"key": "inquiryHint",
"binding": "brand.config.visualPresentation.detail.inquiryHint",
"label": "咨询后的处理说明",
"help": "只填写能兑现的服务安排。",
"input": "textarea",
"previewTarget": "linjing-editorial.detail.action"
}
],
"previewTargets": [
{
"key": "linjing-editorial.detail.action",
"label": "详情页咨询入口"
}
]
}
]
},
@@ -2355,12 +2687,30 @@ export const generatedTemplatePackageRegistry = [
"profile"
],
"help": "填写经验、资质、专业标准或工作方法。",
"previewTargets": [
{
"key": "editorial.home.proof.stats",
"label": "信任数据",
"page": "home"
},
{
"key": "editorial.home.manifesto.pillars",
"label": "专业方法",
"page": "home"
},
{
"key": "editorial.home.flow.steps",
"label": "合作流程步骤",
"page": "home"
}
],
"configFields": [
{
"key": "stats",
"binding": "trust.config.stats",
"label": "信任数据",
"input": "list",
"previewTarget": "editorial.home.proof.stats",
"itemFields": [
{
"key": "value",
@@ -2382,6 +2732,7 @@ export const generatedTemplatePackageRegistry = [
"binding": "trust.config.pillars",
"label": "专业方法",
"input": "list",
"previewTarget": "editorial.home.manifesto.pillars",
"itemFields": [
{
"key": "title",
@@ -2398,6 +2749,7 @@ export const generatedTemplatePackageRegistry = [
"binding": "trust.config.serviceFlow",
"label": "合作流程",
"input": "list",
"previewTarget": "editorial.home.flow.steps",
"itemFields": [
{
"key": "step",
@@ -2676,4 +3028,4 @@ export const generatedTemplatePackageRegistry = [
}
];
export const generatedTemplatePackageRegistryHash =
"d2dc4f44e161e567f9e726a777689e09b5e31cbc41aefe569a9531ccf6a604dd";
"dbe686adc4c4efa5a7667c08671381fb28152c688baefcc70bf52655bed3012e";
@@ -222,7 +222,11 @@ function Service({ workspace }: { workspace: RuntimeWorkspace }) {
)}
<Text>{text(process.config.refundNote)}</Text>
</View>
<Button className="process-action" onClick={() => navigate("inquiry")}>
<Button
data-editor-target="food.service.process-action"
className="process-action"
onClick={() => navigate("inquiry")}
>
{p.processAction || "立即咨询"} →
</Button>
</View>
@@ -461,7 +465,9 @@ function OfferingList({ workspace }: { workspace: RuntimeWorkspace }) {
<Text className="subtitle">{item.desc}</Text>
<View className="dish-bottom">
<Text className="price">{item.priceRange}</Text>
<Text className="more">{p.detailAction || "查看详情 ›"}</Text>
<Text className="more" data-editor-target="acheng-campus-food.offerings.action">
{p.detailAction || "查看详情 ›"}
</Text>
</View>
</View>
</View>
@@ -560,7 +566,7 @@ function Detail({ workspace, id }: { workspace: RuntimeWorkspace; id?: string })
))}
</View>
</View>
<View className="bar">
<View className="bar" data-editor-target="acheng-campus-food.detail.action">
<Button onClick={() => navigate("inquiry", { offeringId: item.id })}>
{p.inquiryAction || "咨询 / 提前预订"}
</Button>
@@ -185,6 +185,30 @@
"label": "记录数量单位",
"input": "text",
"previewTarget": "acheng-campus-food.profile.identity"
},
{
"key": "acheng-campus-food_profile_identity_avatarUrl",
"binding": "brand.avatarUrl",
"label": "主理人头像",
"input": "image",
"previewTarget": "acheng-campus-food.profile.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "acheng-campus-food_profile_identity_name",
"binding": "brand.name",
"label": "品牌名称",
"input": "text",
"previewTarget": "acheng-campus-food.profile.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "acheng-campus-food_profile_identity_description",
"binding": "brand.description",
"label": "主理人简介",
"input": "textarea",
"previewTarget": "acheng-campus-food.profile.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
}
],
"previewTargets": [
@@ -228,6 +252,14 @@
"label": "封面图片",
"input": "image",
"previewTarget": "acheng-campus-food.home.offering"
},
{
"key": "detailHero",
"binding": "offering.config.detailHero",
"label": "详情主图",
"input": "image",
"previewTarget": "acheng-campus-food.home.offering",
"help": "此图优先用于卡片和详情;未填写时使用封面图片。"
}
],
"previewTargets": [
@@ -356,6 +388,38 @@
"binding": "brand.config.visualPresentation.home.manifestoTitle",
"label": "出餐承诺标题",
"input": "text"
},
{
"key": "food_home_identity_avatarUrl",
"binding": "brand.avatarUrl",
"label": "主理人头像",
"input": "image",
"previewTarget": "food.home.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "food_home_identity_description",
"binding": "brand.description",
"label": "主理人简介",
"input": "textarea",
"previewTarget": "food.home.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "food_home_location_address",
"binding": "brand.address",
"label": "服务地址",
"input": "text",
"previewTarget": "food.home.location",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "food_home_hero_name",
"binding": "brand.name",
"label": "品牌名称",
"input": "text",
"previewTarget": "food.home.hero",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
}
]
},
@@ -369,16 +433,21 @@
{
"key": "processAction",
"binding": "brand.config.visualPresentation.service.processAction",
"label": "流程咨询按钮",
"label": "咨询按钮文字",
"input": "text",
"placeholder": "例如:立即预订",
"previewTarget": "acheng-campus-food.service.service"
"previewTarget": "food.service.process-action"
}
],
"previewTargets": [
{
"key": "acheng-campus-food.service.service",
"label": "出摊服务页说明"
"label": "出摊服务页说明",
"composite": true,
"children": ["food.service.process-action"]
},
{
"key": "food.service.process-action",
"label": "咨询按钮文字"
}
]
},
@@ -416,6 +485,21 @@
"label": "封面图片",
"input": "image",
"previewTarget": "acheng-campus-food.offerings.item"
},
{
"key": "detailHero",
"binding": "offering.config.detailHero",
"label": "详情主图",
"input": "image",
"previewTarget": "acheng-campus-food.offerings.item",
"help": "此图优先用于卡片和详情;未填写时使用封面图片。"
},
{
"key": "categoryLabel",
"binding": "offering.config.categoryLabel",
"label": "餐品类别",
"input": "text",
"previewTarget": "acheng-campus-food.offerings.item"
}
],
"previewTargets": [
@@ -666,21 +750,6 @@
"label": "食材与搭配标题",
"input": "text",
"previewTarget": "acheng-campus-food.detail.detailCopy"
},
{
"key": "inquiryAction",
"binding": "brand.config.visualPresentation.detail.inquiryAction",
"label": "咨询按钮文字",
"input": "text",
"previewTarget": "acheng-campus-food.detail.detailCopy"
},
{
"key": "inquiryHint",
"binding": "brand.config.visualPresentation.detail.inquiryHint",
"label": "咨询后的处理说明",
"help": "只写能够兑现的联系和确认方式。",
"input": "textarea",
"previewTarget": "acheng-campus-food.detail.detailCopy"
}
],
"previewTargets": [
@@ -790,6 +859,58 @@
"label": "咨询记录页"
}
]
},
{
"key": "offerings_detailAction",
"title": "详情按钮文字",
"description": "此页同类按钮共用此文案。",
"page": "offerings",
"target": "brand",
"previewTargets": [
{
"key": "acheng-campus-food.offerings.action",
"label": "详情按钮文字"
}
],
"fields": [
{
"key": "detailAction",
"binding": "brand.config.visualPresentation.offerings.detailAction",
"label": "详情按钮文字",
"input": "text",
"previewTarget": "acheng-campus-food.offerings.action"
}
]
},
{
"key": "detailAction",
"title": "详情页咨询入口",
"description": "公共按钮与提示,对所有业务详情生效。",
"page": "detail",
"target": "brand",
"fields": [
{
"key": "inquiryAction",
"binding": "brand.config.visualPresentation.detail.inquiryAction",
"label": "咨询按钮文字",
"input": "text",
"previewTarget": "acheng-campus-food.detail.action"
},
{
"key": "inquiryHint",
"binding": "brand.config.visualPresentation.detail.inquiryHint",
"label": "咨询后的处理说明",
"help": "只写能够兑现的联系和确认方式。",
"input": "textarea",
"previewTarget": "acheng-campus-food.detail.action"
}
],
"previewTargets": [
{
"key": "acheng-campus-food.detail.action",
"label": "详情页咨询入口"
}
]
}
]
},
+1
View File
@@ -116,6 +116,7 @@ export type TemplateTrustContentType = {
placeholder?: string;
required?: boolean;
configFields?: TemplateAdminField[];
previewTargets?: Array<{ key: string; label: string; page?: string }>;
maxPublishedItems?: number;
hideStandardFields?: Array<"summary" | "content">;
};
@@ -169,7 +169,12 @@ test("shared brand facts have one editor and template-specific offering detail b
const bindings = manifest.admin.sections.flatMap((section) =>
section.fields.map((field) => field.binding),
);
assert.ok(!bindings.some((binding) => sharedBrandBindings.has(binding)), key);
for (const field of manifest.admin.sections.flatMap((section) => section.fields)) {
if (sharedBrandBindings.has(field.binding)) {
assert.ok(field.previewTarget, key + ": shared facts need visual targets");
assert.ok(!field.binding.includes(".config."), "Shared facts must use canonical columns");
}
}
}
const foodRoot = path.join(packageRoot, "template-acheng-campus-food");
const food = JSON.parse(fs.readFileSync(path.join(foodRoot, "template.json"), "utf8"));
@@ -24,6 +24,13 @@ for (const directory of templateDirectories) {
const targets = sections.flatMap((section) =>
(section.previewTargets ?? []).map((target) => ({ ...target, page: section.page, section })),
);
for (const declaration of manifest.trustContentTypes ?? [])
for (const target of declaration.previewTargets ?? [])
targets.push({
...target,
page: declaration.pages?.[0] ?? "home",
section: { fields: declaration.configFields ?? [] },
});
const keys = targets.map((target) => target.key);
assert.equal(new Set(keys).size, keys.length, "preview target keys must be unique");
@@ -32,7 +39,7 @@ for (const directory of templateDirectories) {
assert.ok(field.binding, `${section.key}.${field.key} must have an editable binding`);
assert.ok(field.previewTarget, `${section.key}.${field.key} must map to a visual region`);
assert.ok(
section.previewTargets?.some((target) => target.key === field.previewTarget),
targets.some((target) => target.key === field.previewTarget),
`${section.key}.${field.key} references an undeclared previewTarget`,
);
}
@@ -44,9 +51,11 @@ for (const directory of templateDirectories) {
);
for (const child of target.children)
assert.ok(
section.previewTargets?.some(
(candidate) => candidate.key === child && !candidate.composite,
),
targets.some((candidate) => candidate.key === child && !candidate.composite) ||
(child.startsWith("trust:") &&
(manifest.trustContentTypes ?? []).some(
(declaration) => `trust:${declaration.type}` === child,
)),
`${target.key} references missing or composite child ${child}`,
);
assert.ok(
@@ -69,7 +78,10 @@ for (const directory of templateDirectories) {
for (const target of targets)
if (!target.composite)
assert.ok(
target.section.fields.some((field) => field.previewTarget === target.key),
target.section.fields.some((field) => field.previewTarget === target.key) ||
(manifest.trustContentTypes ?? []).some((declaration) =>
(declaration.configFields ?? []).some((field) => field.previewTarget === target.key),
),
`${target.key} must map to at least one editable field`,
);
@@ -60,7 +60,11 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
>
{credential?.content}
</Text>
<View className="stats">
<View
className="stats"
data-editor-target="editorial.home.proof.stats"
data-editor-record-id={credential?.id}
>
{t.stats?.map((item, index) => (
<View key={index}>
<Text className="stat-value">{item.value}</Text>
@@ -73,12 +77,18 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
<View className="trust" data-editor-target="editorial.home.manifesto">
<Text className="eyebrow">{p.manifestoEyebrow}</Text>
<Text className="section-title light">{p.manifestoTitle}</Text>
{t.pillars?.map((item, index) => (
<View className="pillar" key={index}>
<Text className="pillar-title">{item.title}</Text>
<Text className="pillar-desc">{item.desc}</Text>
</View>
))}
<View
className="pillars-content"
data-editor-target="editorial.home.manifesto.pillars"
data-editor-record-id={credential?.id}
>
{t.pillars?.map((item, index) => (
<View className="pillar" key={index}>
<Text className="pillar-title">{item.title}</Text>
<Text className="pillar-desc">{item.desc}</Text>
</View>
))}
</View>
</View>
<View className="section">
<View className="section-head" data-editor-target="editorial.home.works">
@@ -111,10 +121,14 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
</View>
))}
</View>
<View className="flow">
<View className="flow" data-editor-target="editorial.home.flow">
<Text className="flow-eyebrow">{p.flowEyebrow}</Text>
<Text className="flow-title">{p.flowTitle}</Text>
<View className="flow-grid">
<View
className="flow-grid"
data-editor-target="editorial.home.flow.steps"
data-editor-record-id={credential?.id}
>
{t.serviceFlow?.map((step, index) => (
<View className="flow-item" key={index}>
<Text className="flow-step">{step.step}</Text>
@@ -183,7 +197,11 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
)}
</View>
</View>
<View className="records-card" onClick={() => navigate("records")}>
<View
className="records-card"
data-editor-target="linjing-editorial.profile.records"
onClick={() => navigate("records")}
>
<View className="entry-copy">
<Text>{p.recordsTitle || "我的咨询记录"}</Text>
<Text>{p.recordsSubtitle}</Text>
@@ -191,7 +209,7 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
<Text>查看 ›</Text>
</View>
{rows(config.coverage).length > 0 && (
<View className="info-card">
<View className="info-card" data-editor-target="linjing-editorial.profile.coverage">
<View className="card-title">{p.coverageTitle}</View>
{rows(config.coverage).map((item, index) => (
<View className="note" key={index}>
@@ -202,7 +220,7 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
</View>
)}
{Array.isArray(config.warranty) && config.warranty.length > 0 && (
<View className="info-card">
<View className="info-card" data-editor-target="linjing-editorial.profile.warranty">
<View className="card-title">{p.warrantyTitle}</View>
{config.warranty.map((item, index) => (
<View className="warranty" key={index}>
@@ -233,8 +251,8 @@ function List({ workspace }: { workspace: RuntimeWorkspace }) {
return (
<View className="editorial-list" data-editor-target="linjing-editorial.offerings.cases">
<View className="page">
<Text className="eyebrow">{p.eyebrow}</Text>
<Text className="section-title">{p.title || "作品与服务"}</Text>
<Text className="eyebrow">{p.worksEyebrow}</Text>
<Text className="section-title">{p.worksTitle || "作品与服务"}</Text>
<Text className="subtitle">{p.subtitle}</Text>
{workspace.offerings.map(offering).map((item) => (
<View
@@ -252,7 +270,9 @@ function List({ workspace }: { workspace: RuntimeWorkspace }) {
<Text className="work-name">{item.name}</Text>
<Text className="work-desc">{item.desc}</Text>
<Text className="work-price">{item.priceRange}</Text>
<Text className="more">{p.detailAction || "了解详情 →"}</Text>
<Text className="more" data-editor-target="linjing-editorial.offerings.action">
{p.detailAction || "了解详情 →"}
</Text>
</View>
</View>
))}
@@ -345,7 +365,7 @@ function Detail({ workspace, id }: { workspace: RuntimeWorkspace; id?: string })
))}
</View>
</View>
<View className="bar">
<View className="bar" data-editor-target="linjing-editorial.detail.action">
<Button onClick={() => navigate("inquiry", { offeringId: item.id })}>
{p.inquiryAction}
</Button>
+281 -52
View File
@@ -87,7 +87,7 @@
"key": "designPhilosophy",
"page": "home",
"binding": "brand.config.templateData.designPhilosophy",
"previewTarget": "linjing-editorial.home.home",
"previewTarget": "editorial.home.hero",
"label": "设计理念",
"help": "用一两句话说明你的设计方法。",
"input": "textarea",
@@ -152,6 +152,38 @@
"required": true,
"placeholder": "例如:别墅门系统主理人",
"previewTarget": "linjing-editorial.profile.identity"
},
{
"key": "avatarUrl",
"binding": "brand.avatarUrl",
"label": "主理人头像",
"input": "image",
"previewTarget": "linjing-editorial.profile.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "contactPhone",
"binding": "brand.contactPhone",
"label": "联系电话",
"input": "phone",
"previewTarget": "linjing-editorial.profile.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "contactWechat",
"binding": "brand.contactWechat",
"label": "联系微信",
"input": "text",
"previewTarget": "linjing-editorial.profile.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "address",
"binding": "brand.address",
"label": "联系地址",
"input": "text",
"previewTarget": "linjing-editorial.profile.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
}
],
"previewTargets": [
@@ -175,26 +207,55 @@
"input": "text",
"previewTarget": "linjing-editorial.home.offering"
},
{
"key": "summary",
"binding": "offering.summary",
"label": "简介",
"input": "textarea",
"previewTarget": "linjing-editorial.home.offering"
},
{
"key": "priceText",
"binding": "offering.priceText",
"label": "价格说明",
"input": "text",
"previewTarget": "linjing-editorial.home.offering"
},
{
"key": "coverUrl",
"binding": "offering.coverUrl",
"label": "封面图片",
"input": "image",
"previewTarget": "linjing-editorial.home.offering"
},
{
"key": "detailHero",
"binding": "offering.config.detailHero",
"label": "详情主图",
"input": "image",
"previewTarget": "linjing-editorial.home.offering",
"help": "此图优先用于卡片和详情;未填写时使用封面图片。"
},
{
"key": "categoryLabel",
"binding": "offering.config.categoryLabel",
"label": "案例类别",
"input": "text",
"previewTarget": "linjing-editorial.home.offering"
},
{
"key": "area",
"binding": "offering.config.area",
"label": "项目地点",
"input": "text",
"previewTarget": "linjing-editorial.home.offering"
},
{
"key": "series",
"binding": "offering.config.series",
"label": "产品系列",
"input": "text",
"previewTarget": "linjing-editorial.home.offering"
},
{
"key": "keywords",
"binding": "offering.config.keywords",
"label": "项目关键词",
"input": "list",
"itemValueKey": "value",
"itemFields": [
{
"key": "value",
"label": "关键词"
}
],
"previewTarget": "linjing-editorial.home.offering"
}
],
"previewTargets": [
@@ -213,7 +274,7 @@
"previewTargets": [
{
"key": "editorial.home.identity",
"label": "主理人标签"
"label": "主理人介绍"
},
{
"key": "editorial.home.hero",
@@ -233,7 +294,21 @@
},
{
"key": "linjing-editorial.home.home",
"label": "首页品牌表达"
"label": "首页品牌表达",
"composite": true,
"children": [
"editorial.home.identity",
"editorial.home.hero",
"editorial.home.proof",
"editorial.home.manifesto",
"editorial.home.works",
"editorial.home.flow",
"linjing-editorial.home.offering"
]
},
{
"key": "editorial.home.flow",
"label": "合作流程标题"
}
],
"fields": [
@@ -301,49 +376,105 @@
"binding": "brand.config.visualPresentation.home.worksAction",
"label": "查看案例入口",
"input": "text",
"previewTarget": "linjing-editorial.home.home"
"previewTarget": "editorial.home.works"
},
{
"key": "flowEyebrow",
"binding": "brand.config.visualPresentation.home.flowEyebrow",
"label": "合作流程小标题",
"input": "text",
"previewTarget": "linjing-editorial.home.home"
"previewTarget": "editorial.home.flow"
},
{
"key": "flowTitle",
"binding": "brand.config.visualPresentation.home.flowTitle",
"label": "项目流程标题",
"input": "text",
"previewTarget": "linjing-editorial.home.home"
"previewTarget": "editorial.home.flow"
},
{
"key": "heroTitle",
"binding": "brand.config.homeHero.title",
"label": "首页主标题",
"input": "text",
"previewTarget": "linjing-editorial.home.home"
"previewTarget": "editorial.home.hero"
},
{
"key": "heroEyebrow",
"binding": "brand.config.homeHero.eyebrow",
"label": "主图项目标注",
"input": "text",
"previewTarget": "linjing-editorial.home.home"
"previewTarget": "editorial.home.hero"
},
{
"key": "heroDescription",
"binding": "brand.config.homeHero.slogan",
"label": "首页主图说明",
"input": "textarea",
"previewTarget": "linjing-editorial.home.home"
"previewTarget": "editorial.home.hero"
},
{
"key": "heroAction",
"binding": "brand.config.homeHero.cta",
"label": "主图行动文字",
"input": "text",
"previewTarget": "linjing-editorial.home.home"
"previewTarget": "editorial.home.hero"
},
{
"key": "avatarUrl",
"binding": "brand.avatarUrl",
"label": "主理人头像",
"input": "image",
"previewTarget": "editorial.home.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "founder",
"binding": "brand.config.founder",
"label": "主理人姓名",
"input": "text",
"previewTarget": "editorial.home.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "title",
"binding": "brand.config.title",
"label": "身份或职位",
"input": "text",
"previewTarget": "editorial.home.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "description",
"binding": "brand.description",
"label": "主理人简介",
"input": "textarea",
"previewTarget": "editorial.home.identity",
"help": "共享品牌资料,修改后同步影响其他展示位置。"
},
{
"key": "heroFallback_name",
"binding": "brand.name",
"label": "备用主标题(品牌名称)",
"input": "text",
"previewTarget": "editorial.home.hero",
"help": "共享品牌值;对应主图文案为空时使用。"
},
{
"key": "heroFallback_tagline",
"binding": "brand.tagline",
"label": "备用标注(品牌标语)",
"input": "text",
"previewTarget": "editorial.home.hero",
"help": "共享品牌值;对应主图文案为空时使用。"
},
{
"key": "heroFallback_description",
"binding": "brand.description",
"label": "备用说明(品牌简介)",
"input": "text",
"previewTarget": "editorial.home.hero",
"help": "共享品牌值;对应主图文案为空时使用。"
}
]
},
@@ -370,7 +501,7 @@
"input": "textarea"
}
],
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.coverage"
},
{
"key": "warranty",
@@ -385,83 +516,102 @@
"input": "textarea"
}
],
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.warranty"
},
{
"key": "recordsTitle",
"binding": "brand.config.visualPresentation.profile.recordsTitle",
"label": "咨询记录入口标题",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.records"
},
{
"key": "recordsSubtitle",
"binding": "brand.config.visualPresentation.profile.recordsSubtitle",
"label": "咨询记录入口说明",
"input": "textarea",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.records"
},
{
"key": "coverageTitle",
"binding": "brand.config.visualPresentation.profile.coverageTitle",
"label": "服务区域标题",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.coverage"
},
{
"key": "warrantyTitle",
"binding": "brand.config.visualPresentation.profile.warrantyTitle",
"label": "履约说明标题",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.warranty"
},
{
"key": "phoneLabel",
"binding": "brand.config.visualPresentation.profile.phoneLabel",
"label": "电话标签",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.identity"
},
{
"key": "wechatLabel",
"binding": "brand.config.visualPresentation.profile.wechatLabel",
"label": "微信标签",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.identity"
},
{
"key": "addressLabel",
"binding": "brand.config.visualPresentation.profile.addressLabel",
"label": "地址标签",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.identity"
},
{
"key": "callAction",
"binding": "brand.config.visualPresentation.profile.callAction",
"label": "拨打电话按钮",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.identity"
},
{
"key": "copyAction",
"binding": "brand.config.visualPresentation.profile.copyAction",
"label": "复制微信按钮",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.identity"
},
{
"key": "recordsCountUnit",
"binding": "brand.config.visualPresentation.profile.recordsCountUnit",
"label": "记录数量单位",
"input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
"previewTarget": "linjing-editorial.profile.identity"
}
],
"previewTargets": [
{
"key": "linjing-editorial.profile.profileDetails",
"label": "服务区域与履约说明"
"label": "主理人页面",
"composite": true,
"children": [
"linjing-editorial.profile.identity",
"linjing-editorial.profile.records",
"linjing-editorial.profile.coverage",
"linjing-editorial.profile.warranty"
]
},
{
"key": "linjing-editorial.profile.records",
"label": "咨询记录入口"
},
{
"key": "linjing-editorial.profile.coverage",
"label": "服务区域"
},
{
"key": "linjing-editorial.profile.warranty",
"label": "履约说明"
}
]
},
@@ -499,6 +649,28 @@
"label": "封面图片",
"input": "image",
"previewTarget": "linjing-editorial.offerings.item"
},
{
"key": "detailHero",
"binding": "offering.config.detailHero",
"label": "详情主图",
"input": "image",
"previewTarget": "linjing-editorial.offerings.item",
"help": "此图优先用于卡片和详情;未填写时使用封面图片。"
},
{
"key": "categoryLabel",
"binding": "offering.config.categoryLabel",
"label": "案例类别",
"input": "text",
"previewTarget": "linjing-editorial.offerings.item"
},
{
"key": "area",
"binding": "offering.config.area",
"label": "项目地点",
"input": "text",
"previewTarget": "linjing-editorial.offerings.item"
}
],
"previewTargets": [
@@ -767,21 +939,6 @@
"label": "材料说明标题",
"input": "text",
"previewTarget": "linjing-editorial.detail.detailCopy"
},
{
"key": "inquiryAction",
"binding": "brand.config.visualPresentation.detail.inquiryAction",
"label": "咨询按钮文字",
"input": "text",
"previewTarget": "linjing-editorial.detail.detailCopy"
},
{
"key": "inquiryHint",
"binding": "brand.config.visualPresentation.detail.inquiryHint",
"label": "咨询后的处理说明",
"help": "只填写能兑现的服务安排。",
"input": "textarea",
"previewTarget": "linjing-editorial.detail.detailCopy"
}
],
"previewTargets": [
@@ -891,6 +1048,58 @@
"label": "咨询记录页"
}
]
},
{
"key": "offerings_detailAction",
"title": "详情按钮文字",
"description": "此页同类按钮共用此文案。",
"page": "offerings",
"target": "brand",
"previewTargets": [
{
"key": "linjing-editorial.offerings.action",
"label": "详情按钮文字"
}
],
"fields": [
{
"key": "detailAction",
"binding": "brand.config.visualPresentation.offerings.detailAction",
"label": "详情按钮文字",
"input": "text",
"previewTarget": "linjing-editorial.offerings.action"
}
]
},
{
"key": "detailAction",
"title": "详情页咨询入口",
"description": "公共按钮与提示,对所有业务详情生效。",
"page": "detail",
"target": "brand",
"fields": [
{
"key": "inquiryAction",
"binding": "brand.config.visualPresentation.detail.inquiryAction",
"label": "咨询按钮文字",
"input": "text",
"previewTarget": "linjing-editorial.detail.action"
},
{
"key": "inquiryHint",
"binding": "brand.config.visualPresentation.detail.inquiryHint",
"label": "咨询后的处理说明",
"help": "只填写能兑现的服务安排。",
"input": "textarea",
"previewTarget": "linjing-editorial.detail.action"
}
],
"previewTargets": [
{
"key": "linjing-editorial.detail.action",
"label": "详情页咨询入口"
}
]
}
]
},
@@ -940,12 +1149,30 @@
},
"pages": ["home", "profile"],
"help": "填写经验、资质、专业标准或工作方法。",
"previewTargets": [
{
"key": "editorial.home.proof.stats",
"label": "信任数据",
"page": "home"
},
{
"key": "editorial.home.manifesto.pillars",
"label": "专业方法",
"page": "home"
},
{
"key": "editorial.home.flow.steps",
"label": "合作流程步骤",
"page": "home"
}
],
"configFields": [
{
"key": "stats",
"binding": "trust.config.stats",
"label": "信任数据",
"input": "list",
"previewTarget": "editorial.home.proof.stats",
"itemFields": [
{
"key": "value",
@@ -967,6 +1194,7 @@
"binding": "trust.config.pillars",
"label": "专业方法",
"input": "list",
"previewTarget": "editorial.home.manifesto.pillars",
"itemFields": [
{
"key": "title",
@@ -983,6 +1211,7 @@
"binding": "trust.config.serviceFlow",
"label": "合作流程",
"input": "list",
"previewTarget": "editorial.home.flow.steps",
"itemFields": [
{
"key": "step",
+24 -4
View File
@@ -106,11 +106,31 @@ export function projectBrandAliases(
return {
...brand,
...config,
// 标准品牌事实不能被旧模板 config 中同名残留覆盖。
...Object.fromEntries(
[
"id",
"slug",
"name",
"templateKey",
"tagline",
"description",
"avatarUrl",
"coverUrl",
"hours",
"address",
"deliveryNote",
"contactPhone",
"contactWechat",
]
.filter((key) => Object.prototype.hasOwnProperty.call(brand, key))
.map((key) => [key, brand[key]]),
),
...(typeof brand.tagline === "string" ? { tagline: brand.tagline } : {}),
...(typeof brand.description === "string" ? { slogan: brand.description } : {}),
...(typeof brand.contactPhone === "string" ? { phone: brand.contactPhone } : {}),
...(typeof brand.contactWechat === "string" ? { wechat: brand.contactWechat } : {}),
...(typeof brand.address === "string" ? { studioAddress: brand.address } : {}),
...(Object.hasOwn(brand, "description") ? { slogan: brand.description ?? "" } : {}),
...(Object.hasOwn(brand, "contactPhone") ? { phone: brand.contactPhone ?? "" } : {}),
...(Object.hasOwn(brand, "contactWechat") ? { wechat: brand.contactWechat ?? "" } : {}),
...(Object.hasOwn(brand, "address") ? { studioAddress: brand.address ?? "" } : {}),
};
}
+1 -1
View File
@@ -99,7 +99,7 @@ export interface CapabilityPluginManifest {
export interface RuntimeWorkspace {
schemaVersion: string;
publication?: {
status: "published" | "unpublished";
status: "published" | "unpublished" | "draft";
version: number | null;
publishedAt?: string;
};
@@ -112,3 +112,34 @@ test("legacy profile configuration cannot shadow the declared credential editor"
);
assert.deepEqual(result, { stats });
});
test("标准品牌列和清空值不会被旧 config 同名字段覆盖", () => {
const result = projectBrandAliases(
{
name: "标准名称",
avatarUrl: "标准头像",
contactPhone: "新电话",
description: "新简介",
address: null,
},
{
name: "旧名称",
avatarUrl: "旧头像",
contactPhone: "旧电话",
description: "旧简介",
address: "旧地址",
},
);
assert.equal(result.name, "标准名称");
assert.equal(result.avatarUrl, "标准头像");
assert.equal(result.contactPhone, "新电话");
assert.equal(result.description, "新简介");
assert.equal(result.address, null);
assert.equal(result.studioAddress, "");
const cleared = projectBrandAliases(
{ contactPhone: null, description: null },
{ phone: "旧电话", slogan: "旧简介" },
);
assert.equal(cleared.phone, "");
assert.equal(cleared.slogan, "");
});
+374
View File
@@ -0,0 +1,374 @@
import ts from "typescript";
// 静态检查不推断运行时成功;未知表达式保留为 review。
export function diagnoseTemplate(manifest, source, file = "taro/index.tsx") {
const issues = [];
const regions = [];
const targets = [];
const fields = [];
const add = (code, context, message, severity = "blocker") =>
issues.push({ code, severity, file, ...context, message });
for (const section of manifest.admin?.sections ?? []) {
for (const target of section.previewTargets ?? []) {
const owned = (section.fields ?? []).filter((field) => field.previewTarget === target.key);
// 与 PresentationEditor.previewTargetSource 的优先级一致。
const source =
["offering", "trust", "brand"].find((kind) =>
owned.some((field) => field.binding?.startsWith(kind + ".")),
) ?? section.target;
targets.push({ ...target, page: section.page, source });
}
for (const field of section.fields ?? []) fields.push({ ...field, page: section.page });
}
for (const field of manifest.templateFields ?? []) fields.push(field);
for (const declaration of manifest.trustContentTypes ?? []) {
for (const page of declaration.pages ?? []) {
const key = "trust:" + declaration.type;
targets.push({ key, page, source: "trust", implicit: true });
for (const name of ["title", "summary", "content"])
if (!declaration.hideStandardFields?.includes(name))
fields.push({ binding: "trust." + name, previewTarget: key, page });
for (const field of (declaration.configFields ?? []).filter((field) => {
const target = declaration.previewTargets?.find(
(target) => target.key === field.previewTarget,
);
return !target?.page || target.page === page;
}))
fields.push({ ...field, previewTarget: field.previewTarget ?? key, page });
}
for (const target of declaration.previewTargets ?? []) {
if (!target.page)
add(
"TARGET_PAGE_UNSPECIFIED",
{ target: target.key },
"信任子区域需要明确展示页面,不能自动出现在该类型的全部页面。",
);
targets.push({ ...target, page: target.page ?? declaration.pages?.[0], source: "trust" });
}
}
const matching = (key, page) => targets.find((t) => t.key === key && t.page === page);
for (const field of fields) {
const target = matching(field.previewTarget, field.page);
const context = { page: field.page, target: field.previewTarget, binding: field.binding };
if (!target) add("FIELD_TARGET_MISSING", context, "字段必须绑定同页已声明区域。");
else if (target.composite)
add("COMPOSITE_HAS_FIELDS", context, "组合区域应导航到字段所属子区。");
else if (field.binding?.split(".")[0] !== target.source)
add(
"TARGET_SOURCE_MISMATCH",
context,
"区域来源与字段不一致,现有单记录编辑器无法完整保存。",
);
}
for (const target of targets) {
const context = { page: target.page, target: target.key };
if (targets.filter((t) => t.key === target.key && t.page === target.page).length > 1)
add("DUPLICATE_TARGET", context, "同页区域标识必须唯一。");
if (target.composite) {
if (!target.children?.length) add("COMPOSITE_EMPTY", context, "组合区域必须有子区。");
for (const child of target.children ?? [])
if (!matching(child, target.page) || matching(child, target.page)?.composite)
add("COMPOSITE_CHILD_INVALID", context, "子区必须是同页直接区域:" + child);
}
}
const ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
for (const diagnostic of ast.parseDiagnostics)
add("RENDERER_PARSE_ERROR", {}, ts.flattenDiagnosticMessageText(diagnostic.messageText, " "));
const standardBrand = new Set([
"name",
"tagline",
"description",
"avatarUrl",
"contactPhone",
"contactWechat",
"address",
"hours",
"deliveryNote",
"coverUrl",
]);
const normalize = (path) => {
if (
path.startsWith("brand.") &&
!path.startsWith("brand.config.") &&
!standardBrand.has(path.split(".")[1])
)
return path.replace("brand.", "brand.config.");
return path;
};
function inspectFunction(fn) {
const aliases = new Map([["workspace", "workspace"]]);
const offeringAliases = {
image: "offering.config.detailHero",
desc: "offering.summary",
priceRange: "offering.priceText",
category: "offering.config.categoryLabel",
area: "offering.config.area",
series: "offering.config.series",
keywords: "offering.config.keywords",
details: "offering.config.details",
};
const resolve = (node) => {
if (!node) return undefined;
if (ts.isIdentifier(node)) return aliases.get(node.text);
if (ts.isPropertyAccessExpression(node)) {
const base = resolve(node.expression);
if (!base) return undefined;
if (base === "offering" && offeringAliases[node.name.text])
return offeringAliases[node.name.text];
if (base === "offering.presentation") return "offering.config." + node.name.text;
const path = base + "." + node.name.text;
if (path === "workspace.brand") return "brand";
if (path === "workspace.templateData") return "brand.config.templateData";
if (path === "workspace.trustPresentation") return "trust.config";
if (path === "workspace.offerings") return "offering[]";
if (path === "workspace.trustItems") return "trust[]";
return path;
}
if (ts.isCallExpression(node) && ["object", "rows"].includes(node.expression.getText(ast)))
return resolve(node.arguments[0]);
if (ts.isCallExpression(node) && node.expression.getText(ast) === "offering")
return "offering";
if (ts.isCallExpression(node) && node.expression.getText(ast) === "slot") return "trust";
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
const base = resolve(node.expression.expression);
if (["filter", "slice"].includes(node.expression.name.text)) return base;
if (node.expression.name.text === "find") return base?.replace(/\[\]$/, "");
if (node.expression.name.text === "map" && node.arguments[0]?.getText(ast) === "offering")
return "offering[]";
}
if (
ts.isCallExpression(node) &&
node.expression.getText(ast) === "presentation" &&
node.arguments[1] &&
ts.isStringLiteral(node.arguments[1])
)
return "brand.config.visualPresentation." + node.arguments[1].text;
return undefined;
};
function collect(node) {
if (node !== fn && ts.isFunctionDeclaration(node)) return;
if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) {
const path = resolve(node.initializer);
if (path) aliases.set(node.name.text, path);
}
ts.forEachChild(node, collect);
}
collect(fn);
function visit(node, active) {
if (
ts.isCallExpression(node) &&
ts.isPropertyAccessExpression(node.expression) &&
node.expression.name.text === "map"
) {
const collection = resolve(node.expression.expression);
const callback = node.arguments[0];
if (
collection &&
callback &&
ts.isArrowFunction(callback) &&
callback.parameters[0] &&
ts.isIdentifier(callback.parameters[0].name)
) {
const name = callback.parameters[0].name.text;
const previous = aliases.get(name);
aliases.set(name, collection.replace(/\[\]$/, ""));
visit(callback.body, active);
if (previous) aliases.set(name, previous);
else aliases.delete(name);
return;
}
}
if (ts.isConditionalExpression(node)) {
add(
"CONDITIONAL_RENDER_REVIEW",
{
target: active?.target,
line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1,
},
"条件显示需验证全部分支与空数据入口。",
"review",
);
visit(node.whenTrue, active);
visit(node.whenFalse, active);
return;
}
if (
ts.isBinaryExpression(node) &&
node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken
) {
add(
"CONDITIONAL_RENDER_REVIEW",
{
target: active?.target,
line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1,
},
"条件显示需验证全部分支与空数据入口。",
"review",
);
visit(node.right, active);
return;
}
if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) {
const opening = ts.isJsxElement(node) ? node.openingElement : node;
const attrs = opening.attributes.properties;
const attr = attrs.find(
(a) => ts.isJsxAttribute(a) && a.name.getText(ast) === "data-editor-target",
);
if (attr) {
if (attr.initializer && ts.isStringLiteral(attr.initializer)) {
const key = attr.initializer.text;
const candidates = targets.filter((t) => t.key === key);
active = {
target: key,
page: candidates[0]?.page,
line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1,
bindings: new Set(),
};
regions.push(active);
if (!candidates.length)
add("RENDER_TARGET_UNDECLARED", active, "renderer 区域没有声明。");
if (
candidates.some((t) => ["trust", "offering"].includes(t.source)) &&
!attrs.some(
(a) => ts.isJsxAttribute(a) && a.name.getText(ast) === "data-editor-record-id",
)
)
add(
"RECORD_ID_MISSING",
{ target: key, page: active.page, line: active.line },
"记录区域必须携带实际记录 ID。",
);
} else {
add(
"DYNAMIC_TARGET_REVIEW",
{ line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1 },
"动态目标需用真实 manifest 和实际记录验证分支。",
"review",
);
active = undefined;
}
}
// 属性中的事件和 recordId 不属于展示变量,只检查图片等展示属性。
for (const a of attrs)
if (
ts.isJsxAttribute(a) &&
["src", "title", "placeholder", "value"].includes(a.name.getText(ast)) &&
a.initializer
)
visit(a.initializer, active);
if (ts.isJsxElement(node)) for (const child of node.children) visit(child, active);
return;
}
if (ts.isPropertyAccessExpression(node) && !ts.isPropertyAccessExpression(node.parent)) {
if (ts.isElementAccessExpression(node.parent) && node.parent.expression === node) return;
const path = resolve(node);
if (path && /^(brand|trust|offering)\./.test(path)) {
const binding = normalize(path);
if (active) active.bindings.add(binding);
else
add(
"UNSCOPED_RENDER_VALUE",
{ binding, line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1 },
"展示变量没有可证明的编辑区域。",
"review",
);
} else if (active)
add(
"UNRESOLVED_RENDER_VALUE",
{
target: active.target,
page: active.page,
expression: node.getText(ast),
line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1,
},
"需要核对循环项或间接映射,不能视为已覆盖。",
"review",
);
}
if (ts.isElementAccessExpression(node) && active)
add(
"DYNAMIC_VALUE_REVIEW",
{ target: active.target, page: active.page, expression: node.getText(ast) },
"动态索引必须验证实际分支。",
"review",
);
ts.forEachChild(node, (child) => visit(child, active));
}
// 只从 JSX 开始,避免把数据准备和事件中的读取当成展示值。
function roots(node) {
if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) return visit(node, undefined);
ts.forEachChild(node, roots);
}
roots(fn);
}
for (const statement of ast.statements) {
if (ts.isFunctionDeclaration(statement)) inspectFunction(statement);
else {
const check = (node) => {
if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) {
add(
"UNSUPPORTED_COMPONENT_REVIEW",
{ line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1 },
"非函数声明组件需扩展解析器或补真实交互验证,不能静态认定覆盖。",
"review",
);
return;
}
ts.forEachChild(node, check);
};
check(statement);
}
}
for (const region of regions) {
const context = { page: region.page, target: region.target, line: region.line };
const declared = fields.filter(
(f) => f.previewTarget === region.target && f.page === region.page,
);
for (const binding of region.bindings)
if (
!(
region.page === "detail" && binding.startsWith("offering.")
? fields.filter((f) => f.binding?.startsWith("offering."))
: declared
).some((f) => f.binding === binding || binding.startsWith(f.binding + "."))
)
add(
"REGION_FIELD_MISSING",
{ ...context, binding },
"选区实际展示该变量但当前面板没有对应字段;补真实绑定或明确只读模式。",
);
for (const binding of region.bindings) {
const field = declared.find((f) => f.input === "list" && binding.startsWith(f.binding + "."));
if (!field || field.itemValueKey) continue;
const child = binding.slice(field.binding.length + 1).split(".")[0];
if (["map", "slice", "length", "filter", "join"].includes(child)) continue;
if (!field.itemFields?.some((item) => item.key === child))
add(
"LIST_FIELD_MISSING",
{ ...context, binding },
"列表展示的子字段必须在 itemFields 中提供编辑入口。",
);
}
}
for (const target of targets)
if (!target.implicit && !regions.some((r) => r.target === target.key))
add(
"TARGET_RENDER_UNVERIFIED",
{ page: target.page, target: target.key },
"未找到字面量区域,需验证动态目标或组件路径。",
"review",
);
return {
template: manifest.packageKey,
staticStatus: issues.length ? "fail" : "pass",
completionStatus: "unverified",
requiredEvidence: [
"real-manifest-interaction",
"save-reload-publish-isolation",
"visual-reference",
"empty-error-branches",
],
regions: regions.map((r) => ({ ...r, bindings: [...r.bindings] })),
issues,
};
}
+39
View File
@@ -0,0 +1,39 @@
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { diagnoseTemplate } from "./lib/template-doctor.mjs";
try {
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const args = process.argv.slice(2);
const options = {};
for (let i = 0; i < args.length; i += 2) {
if (!["--template", "--output"].includes(args[i]) || !args[i + 1])
throw new Error("Usage: template-doctor [--template key] [--output path]");
options[args[i]] = args[i + 1];
}
const reports = [];
for (const dir of fs.readdirSync(path.join(root, "packages")).sort()) {
const manifestPath = path.join(root, "packages", dir, "template.json");
if (!dir.startsWith("template-") || !fs.existsSync(manifestPath)) continue;
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
if (options["--template"] && manifest.packageKey !== options["--template"]) continue;
const renderer = path.join(root, "packages", dir, "taro/index.tsx");
if (!fs.existsSync(renderer)) throw new Error("Missing renderer: " + renderer);
reports.push(
diagnoseTemplate(manifest, fs.readFileSync(renderer, "utf8"), path.relative(root, renderer)),
);
}
if (!reports.length) throw new Error("No matching templates found");
const report = { schemaVersion: 1, completionStatus: "unverified", templates: reports };
const output = JSON.stringify(report, null, 2) + "\n";
if (options["--output"]) {
fs.mkdirSync(path.dirname(path.resolve(options["--output"])), { recursive: true });
fs.writeFileSync(options["--output"], output);
}
process.stdout.write(output);
process.exitCode = reports.some((r) => r.staticStatus === "fail") ? 1 : 0;
} catch (error) {
console.error(error.message);
process.exitCode = 2;
}
+273
View File
@@ -0,0 +1,273 @@
import assert from "node:assert/strict";
import test from "node:test";
import fs from "node:fs";
import { spawnSync } from "node:child_process";
import { diagnoseTemplate } from "../lib/template-doctor.mjs";
test("真实模板自动发现并读取完整声明,生成可追溯区域报告", () => {
const root = new URL("../../packages/", import.meta.url);
const dirs = fs
.readdirSync(root)
.filter(
(dir) => dir.startsWith("template-") && fs.existsSync(new URL(dir + "/template.json", root)),
);
assert.ok(dirs.length > 0);
for (const dir of dirs) {
const manifest = JSON.parse(fs.readFileSync(new URL(dir + "/template.json", root), "utf8"));
const source = fs.readFileSync(new URL(dir + "/taro/index.tsx", root), "utf8");
const report = diagnoseTemplate(manifest, source);
assert.equal(report.template, manifest.packageKey);
assert.ok(report.regions.length > 0);
assert.equal(report.completionStatus, "unverified");
for (const region of report.regions) {
for (const binding of region.bindings) {
const fields = [
...manifest.admin.sections.flatMap((s) => s.fields),
...(manifest.templateFields ?? []),
...(manifest.trustContentTypes ?? []).flatMap((t) =>
(t.configFields ?? []).map((f) => ({
...f,
previewTarget: f.previewTarget ?? "trust:" + t.type,
})),
),
...(manifest.trustContentTypes ?? []).flatMap((t) =>
["title", "summary", "content"]
.filter((name) => !t.hideStandardFields?.includes(name))
.map((name) => ({ binding: "trust." + name, previewTarget: "trust:" + t.type })),
),
];
assert.ok(
fields.some(
(f) =>
(f.previewTarget === region.target ||
(region.page === "detail" && f.binding.startsWith("offering."))) &&
(f.binding === binding || binding.startsWith(f.binding + ".")),
) ||
report.issues.some(
(i) =>
i.code === "REGION_FIELD_MISSING" &&
i.target === region.target &&
i.binding === binding,
),
`${manifest.packageKey}: ${region.target} ${binding}`,
);
}
}
}
});
test("CLI 自动发现全部模板,问题退出 1,未知模板退出 2", () => {
const cli = new URL("../template-doctor.mjs", import.meta.url);
const all = spawnSync(process.execPath, [cli.pathname], { encoding: "utf8" });
const report = JSON.parse(all.stdout);
assert.equal(all.status, report.templates.some((t) => t.staticStatus === "fail") ? 1 : 0);
assert.ok(report.templates.length > 0);
const missing = spawnSync(
process.execPath,
[cli.pathname, "--template", "missing-template-fixture"],
{ encoding: "utf8" },
);
assert.equal(missing.status, 2);
});
const manifest = () => ({
packageKey: "independent-template",
admin: {
sections: [
{
page: "home",
target: "brand",
previewTargets: [{ key: "identity", label: "人物介绍" }],
fields: [
{ binding: "brand.config.visualPresentation.home.badge", previewTarget: "identity" },
],
},
],
},
});
const renderer =
'function Home({workspace}) { const b = workspace.brand; const p = presentation(workspace, "home"); return <View data-editor-target="identity"><Text>{b.founder}</Text><Text>{p.badge}</Text></View>; }';
test("整卡仅有标签字段不能通过,报告具体缺失变量", () => {
const result = diagnoseTemplate(manifest(), renderer);
assert.equal(result.staticStatus, "fail");
assert.ok(
result.issues.some(
(i) => i.code === "REGION_FIELD_MISSING" && i.binding === "brand.config.founder",
),
);
});
test("完整字段通过静态检查但不能被宣称模板完成", () => {
const input = manifest();
input.admin.sections[0].fields.push({
binding: "brand.config.founder",
previewTarget: "identity",
});
const result = diagnoseTemplate(input, renderer);
assert.equal(result.staticStatus, "pass");
assert.equal(result.completionStatus, "unverified");
});
test("嵌套子区独立检查,父区字段不能遮蔽子区缺失", () => {
const input = manifest();
input.admin.sections[0].previewTargets.push({ key: "child", label: "姓名" });
input.admin.sections[0].fields.push({
binding: "brand.config.founder",
previewTarget: "identity",
});
const result = diagnoseTemplate(
input,
renderer.replace(
"<Text>{b.founder}</Text>",
'<Text data-editor-target="child">{b.founder}</Text>',
),
);
assert.ok(result.issues.some((i) => i.code === "REGION_FIELD_MISSING" && i.target === "child"));
});
test("组合根上的模板字段同样算误绑", () => {
const input = manifest();
input.admin.sections[0].previewTargets[0].composite = true;
input.templateFields = [
{ page: "home", binding: "brand.config.templateData.method", previewTarget: "identity" },
];
const result = diagnoseTemplate(input, renderer);
assert.ok(
result.issues.some((i) => i.code === "COMPOSITE_HAS_FIELDS" && i.binding.endsWith(".method")),
);
});
test("跨页目标不能作为合法字段入口", () => {
const input = manifest();
input.templateFields = [
{ page: "profile", binding: "brand.config.templateData.method", previewTarget: "identity" },
];
assert.ok(
diagnoseTemplate(input, renderer).issues.some((i) => i.code === "FIELD_TARGET_MISSING"),
);
});
test("信任子目标必须声明页面,品牌字段不可归给 trust 记录编辑器", () => {
const input = manifest();
input.trustContentTypes = [
{
type: "credential",
pages: ["home", "profile"],
previewTargets: [{ key: "stats" }],
configFields: [],
},
];
input.admin.sections[0].fields.push({ binding: "brand.description", previewTarget: "stats" });
const result = diagnoseTemplate(input, renderer);
assert.ok(result.issues.some((i) => i.code === "TARGET_PAGE_UNSPECIFIED"));
assert.ok(result.issues.some((i) => i.code === "TARGET_SOURCE_MISMATCH"));
});
test("动态路径保留 review,不能静默绿色", () => {
const result = diagnoseTemplate(manifest(), renderer.replace("b.founder", "b[key]"));
assert.ok(
result.issues.some((i) => i.code === "DYNAMIC_VALUE_REVIEW" && i.severity === "review"),
);
});
test("记录区域缺失 recordId 会报告", () => {
const input = manifest();
input.admin.sections[0].target = "offering";
input.admin.sections[0].fields = [{ binding: "offering.name", previewTarget: "identity" }];
assert.ok(diagnoseTemplate(input, renderer).issues.some((i) => i.code === "RECORD_ID_MISSING"));
});
test("section 为 inquiry 但字段全是品牌时按运行时推导品牌来源", () => {
const input = manifest();
input.admin.sections[0].target = "inquiry";
input.admin.sections[0].fields.push({
binding: "brand.config.founder",
previewTarget: "identity",
});
assert.equal(diagnoseTemplate(input, renderer).staticStatus, "pass");
});
test("同一区域混合记录和品牌字段不能豁免", () => {
const input = manifest();
input.admin.sections[0].fields.push({ binding: "offering.name", previewTarget: "identity" });
assert.ok(
diagnoseTemplate(input, renderer).issues.some((i) => i.code === "TARGET_SOURCE_MISMATCH"),
);
});
test("箭头组件不能被跳过而静默通过", () => {
assert.ok(
diagnoseTemplate(
manifest(),
'const Home = () => <View data-editor-target="identity">{brand.founder}</View>',
).issues.some((i) => i.code === "UNSUPPORTED_COMPONENT_REVIEW"),
);
});
test("条件只控制子区显示时不误判成父区展示字段", () => {
const input = manifest();
const source =
'function Home({workspace}) { const b=workspace.brand; return <View data-editor-target="identity">{b.avatarUrl && <Text>头像</Text>}</View>; }';
const result = diagnoseTemplate(input, source);
assert.ok(result.issues.some((i) => i.code === "CONDITIONAL_RENDER_REVIEW"));
assert.ok(!result.issues.some((i) => i.code === "REGION_FIELD_MISSING"));
});
test("JSON 合法但 TSX 损坏不能通过诊断", () => {
assert.ok(
diagnoseTemplate(manifest(), "function Home( { return <View>").issues.some(
(i) => i.code === "RENDERER_PARSE_ERROR",
),
);
});
test("循环业务卡片追踪实际字段,删除字段会失败", () => {
const input = manifest();
input.admin.sections[0].target = "offering";
input.admin.sections[0].fields = [{ binding: "offering.name", previewTarget: "identity" }];
const source =
'function Home({workspace}) { return <View>{workspace.offerings.map(offering).map(item => <View data-editor-target="identity" data-editor-record-id={item.id}>{item.name}{item.area}</View>)}</View>; }';
const result = diagnoseTemplate(input, source);
assert.ok(
result.issues.some(
(i) => i.code === "REGION_FIELD_MISSING" && i.binding === "offering.config.area",
),
);
input.admin.sections[0].fields.push({
binding: "offering.config.area",
previewTarget: "identity",
});
assert.ok(!diagnoseTemplate(input, source).issues.some((i) => i.code === "REGION_FIELD_MISSING"));
});
test("结构化信任列表追踪子字段,不跨循环混用别名", () => {
const input = manifest();
input.admin.sections[0].target = "trust";
input.admin.sections[0].fields = [{ binding: "trust.config.stats", previewTarget: "identity" }];
const source =
'function Home({workspace}) { const t=workspace.trustPresentation; return <View data-editor-target="identity" data-editor-record-id="fixture">{t.stats.map(item => <Text>{item.value}</Text>)}</View>; }';
const result = diagnoseTemplate(input, source);
assert.ok(result.regions[0].bindings.includes("trust.config.stats.value"));
assert.ok(!result.issues.some((i) => i.code === "REGION_FIELD_MISSING"));
});
test("动态索引保留待核查,但不把容器对象误当可编辑字段", () => {
const input = manifest();
const source =
'function Home({workspace}) { const b=workspace.brand; return <View data-editor-target="identity">{b.config[key]}</View>; }';
const result = diagnoseTemplate(input, source);
assert.ok(result.issues.some((i) => i.code === "DYNAMIC_VALUE_REVIEW"));
assert.ok(
!result.issues.some((i) => i.code === "REGION_FIELD_MISSING" && i.binding === "brand.config"),
);
});
test("列表声明存在仍须检查每个展示子字段", () => {
const input = manifest();
input.admin.sections[0].target = "trust";
input.admin.sections[0].fields = [
{
binding: "trust.config.stats",
previewTarget: "identity",
input: "list",
itemFields: [{ key: "value" }],
},
];
const source =
'function Home({workspace}) { const t=workspace.trustPresentation; return <View data-editor-target="identity" data-editor-record-id="fixture">{t.stats.map(item => <Text>{item.value}{item.sub}</Text>)}</View>; }';
assert.ok(
diagnoseTemplate(input, source).issues.some(
(i) => i.code === "LIST_FIELD_MISSING" && i.binding === "trust.config.stats.sub",
),
);
input.admin.sections[0].fields[0].itemFields.push({ key: "sub" });
assert.ok(!diagnoseTemplate(input, source).issues.some((i) => i.code === "LIST_FIELD_MISSING"));
});