Compare commits

..
66 changed files with 4653 additions and 459 deletions

No files matched your search

@@ -0,0 +1,30 @@
# Admin 编辑工作区重构
## 目标
把 Admin 的品牌配置与小程序页面编辑整理成一个层级清晰、可持续扩展的工作区。用户能够明确区分品牌基础资料、模板内容、业务记录和页面预览;页面预览、区域选择和字段编辑保持统一行为。
## 交付边界
- 品牌资料页面减少 Card 堆叠,形成连续的配置分组。
- 小程序页面配置成为主要编辑工作区,使用页面导航、预览画布和编辑面板的稳定布局。
- 详情页只提供业务记录选择和动态预览,不出现品牌级详情编辑表单。
- 预览选区、高亮、编辑状态、空状态和错误状态保持一致。
- 不改变后端数据模型和小程序业务语义;模板仍通过 manifest 声明页面、区域和字段。
## 设计原则
- 基础品牌事实只提供一个编辑入口。
- 模板专属字段由模板 manifest 驱动,不在共享页面中写行业逻辑。
- 预览是编辑上下文的一部分,不单独启动每个模板服务。
- 详情页数据来自选中的业务记录,视觉文案只能作为模板配置存在。
- 页面区块使用平面分组和分隔线,只有真正需要独立操作的区域使用 Card。
## 验收标准
- 1920、1280、1024、768 和 390 宽度下布局无横向溢出。
- 品牌资料、页面配置和发布状态的层级可以在首屏理解。
- 首页、业务、服务、详情、咨询、成功和记录页面均可切换并保持稳定高度。
- 点击模板区域后,选区高亮和右侧编辑面板始终同步。
- 详情页只能选择业务记录并预览,不能出现品牌级详情字段编辑。
- 通过 Admin/Taro typecheck、模板契约测试、生产构建和关键浏览器交互测试。
@@ -0,0 +1,40 @@
# Progress
## 保存体验收尾
- 品牌资料、页面字段、记录和咨询字段暴露未保存状态;保存成功清除对应状态,失败保留输入。
- 切换页面/记录提供取消或放弃确认,刷新关闭窗口提供提醒,工作区内链接离开提供确认。
- 保存操作区采用统一的面板底部样式;业务记录与品牌配置继续分别保存到原有接口。
- 浏览器测试补充未保存取消切换与失败重试场景;测试采用独立接口 fixture,不冒充当前数据库的端到端验收。
- 本轮没有重构品牌切换器或新增跨实体批量保存 API,这些不作为已验证能力。
## 工作台重构补充验收
- 上一轮将布局整理判为全部完成不准确,补充真正的工作台任务:视图分离、三栏布局和层级区域导航。
- 默认显示页面编辑,品牌基础表单在“品牌资料”视图访问;两套组件保持挂载,切换不丢弃草稿。
- 区域导航移至左栏,预览居中,属性编辑位于右栏;子区域缩进,选区与导航选中状态同步。
- 顶部区分草稿工作区与检查发布入口,保存仍由各内容表单负责,避免错误承诺跨实体统一保存。
- 已通过 2 项浏览器回归和五种宽度检查,并查看 1920 宽度实际截图。
## 2026-10-10
- 建立 Admin 编辑工作区重构 Epic。
- 当前已知问题:品牌资料上方存在多个连续 Card;小程序页面配置仍是普通 Card;预览区和编辑面板层级不够明确;详情页需要保持动态只读预览;选区高亮需要继续验证真实鼠标路径。
- 当前基线能力:模板 manifest、Taro renderer、RuntimeWorkspace 和 Admin 字段绑定已经形成契约;本 Epic 主要调整 Admin 信息架构与视觉层。
- 第 1 项已完成:确认 `BrandPage` 的两列 Card 结构、页面配置固定最小高度、模板说明右栏和编辑器内部重复导航。
- 第 2 项开始:先整理品牌资料页面层级,减少 Card 作为页面区块容器的使用。
- 第 2 项阶段性完成:`BrandPage` 已将品牌身份、联系合作、模板视觉改为连续分组,模板说明改为右侧辅助 `Alert`,并增加移动端断点。
- 验证:Admin typecheck 通过,`admin-editor.spec.ts` 2 项通过。
- 第 2 项完成,第 3 项开始:`PresentationEditor` 已移除外层 Card 和固定最小高度,改为独立工作区标题区;下一步处理工作区内部布局和视觉状态。
- 工作区完成:品牌配置使用连续分组;模板辅助信息移入基础资料尾部;编辑器使用完整宽度两栏布局,窄屏上下排列。
- 未选中时显示引导,详情页目标列表为空且不显示点选工具。
- 新增 1920/1280/1024/768/390 宽度无溢出断言和截图,已人工查看 1280 与 390 截图。
- 验证通过:Admin/Taro typecheck、Admin lint、全仓 format:check、19 项模板契约测试、Admin build、2 项浏览器测试。
- lint 暴露已有 InquiryPreviewEditor 类型问题,已通过 Form 泛型和普通对象传入修复。
- 保留已知构建 api chunk 超过 500 kB 提示,后续由 Admin 前端打包优化任务负责;记录在 ADR 0021。
- 本轮不涉及新增 API 或数据迁移。
- 最终收尾完成:新增全局未保存离开提醒、切换确认、保存状态和失败保留输入;属性面板保存按钮固定在底部。
- 验证通过:Admin/Taro typecheck、Admin lint、format:check、19 项模板契约、Admin build、浏览器 2 项(含未保存取消切换与失败重试)。
- 构建仍有 api chunk 超过 500 kB 的提示,属于后续打包优化项,不影响构建结果。
@@ -0,0 +1,6 @@
id,title,status,task_type,depends_on,acceptance_criteria,validation_command,task_dir,notes
1,建立现状基线与页面覆盖清单,DONE,single-full,,记录当前布局层级、Card 使用、响应式问题和关键交互,测试基线截图与 DOM 检查,.codex-tasks/admin-editor-workspace/tasks/01-baseline/,已完成代码结构基线与验证记录
2,重构品牌配置的信息架构,DONE,single-full,1,品牌资料按身份联系模板视觉分组且减少卡片嵌套,Admin typecheck; browser brand page test,.codex-tasks/admin-editor-workspace/tasks/02-information-architecture/,已完成分组与模板说明层级调整
3,重构小程序页面编辑工作区,DONE,single-full,1;2,页面导航预览画布编辑面板形成稳定三栏或响应式两栏布局,Admin build; browser editor test,.codex-tasks/admin-editor-workspace/tasks/03-workspace-ui/,完整宽度两栏工作区,窄屏堆叠;详情页只读;未选中显示引导
4,统一编辑器视觉系统与状态样式,DONE,single-full,3,间距层级按钮选区空状态错误状态统一且无 Card 堆叠,Prettier; Admin build; screenshot review,.codex-tasks/admin-editor-workspace/tasks/04-visual-system/,统一导航工具条、画布边界、区域按钮和面板间距;已检查 1280 与 390 截图
5,全页面回归与交付验收,DONE,single-full,2;3;4,关键页面交互和响应式检查通过并记录残余风险,validate:templates; typecheck; build; browser tests,.codex-tasks/admin-editor-workspace/tasks/05-regression/,5 种宽度无溢出;浏览器 2 项、契约 19 项、格式、lint、类型和构建通过
1 id title status task_type depends_on acceptance_criteria validation_command task_dir notes
2 1 建立现状基线与页面覆盖清单 DONE single-full 记录当前布局层级、Card 使用、响应式问题和关键交互 测试基线截图与 DOM 检查 .codex-tasks/admin-editor-workspace/tasks/01-baseline/ 已完成代码结构基线与验证记录
3 2 重构品牌配置的信息架构 DONE single-full 1 品牌资料按身份联系模板视觉分组且减少卡片嵌套 Admin typecheck; browser brand page test .codex-tasks/admin-editor-workspace/tasks/02-information-architecture/ 已完成分组与模板说明层级调整
4 3 重构小程序页面编辑工作区 DONE single-full 1;2 页面导航预览画布编辑面板形成稳定三栏或响应式两栏布局 Admin build; browser editor test .codex-tasks/admin-editor-workspace/tasks/03-workspace-ui/ 完整宽度两栏工作区,窄屏堆叠;详情页只读;未选中显示引导
5 4 统一编辑器视觉系统与状态样式 DONE single-full 3 间距层级按钮选区空状态错误状态统一且无 Card 堆叠 Prettier; Admin build; screenshot review .codex-tasks/admin-editor-workspace/tasks/04-visual-system/ 统一导航工具条、画布边界、区域按钮和面板间距;已检查 1280 与 390 截图
6 5 全页面回归与交付验收 DONE single-full 2;3;4 关键页面交互和响应式检查通过并记录残余风险 validate:templates; typecheck; build; browser tests .codex-tasks/admin-editor-workspace/tasks/05-regression/ 5 种宽度无溢出;浏览器 2 项、契约 19 项、格式、lint、类型和构建通过
@@ -0,0 +1,32 @@
# 当前基线
## 页面结构
- `BrandPage` 使用两列布局:左侧 `xl=16`,右侧 `xl=8`。
- 左侧依次渲染“我是谁”“如何联系与合作”“模板与品牌视觉”三个 `Card`。
- 左侧表单之后渲染“小程序页面配置” `Card`。
- 右侧单独渲染“模板说明” `Card`。
- 页面配置内部还有页面导航、页面预览、详情业务选择器、预览目标按钮和右侧编辑表单。
## 已确认问题
- 配置 Card 与页面编辑 Card 在视觉上处于同一层级,用户难以判断基础资料和页面编辑的关系。
- “模板说明”占据右侧固定列,但对编辑流程帮助有限,造成首屏空间浪费。
- 页面配置使用 `minHeight: 760/620`,内容较少的页面会出现大面积空白。
- 页面配置内部的预览目标按钮与画布选区重复表达同一件事。
- 详情页已经改为动态预览提示,但页面整体仍沿用通用编辑器的表单布局。
- 品牌资料表单保存按钮位于所有配置分组之后,长页面中不够容易发现。
## 现有可复用能力
- 模板 manifest 声明页面、区域、字段和 preview target。
- `RuntimeWorkspace` 为组件预览提供品牌、业务记录、信任内容和咨询表单数据。
- `ComponentTemplatePreview` 支持点选、高亮、组合区域和浏览模式。
- `PresentationEditor` 已支持业务记录编辑、信任内容编辑和咨询字段编辑。
## 基线验证
- `pnpm --filter @personal-brand/admin typecheck`:通过。
- `pnpm --filter @personal-brand/taro typecheck`:通过。
- `pnpm validate:templates`:19 项模板契约测试通过。
- 已有 `admin-editor.spec.ts` 覆盖页面切换、预览选区、业务记录、信任内容、咨询表单和详情页动态预览。
@@ -0,0 +1,7 @@
# 可视化编辑闭环
执行方案:docs/visual-editor-next-steps.md。
基线:feat/admin-component-preview / 541304a。
状态源:本目录 SUBTASKS.csv;旧 visual-editor 任务保留为历史。
当前仅完成规划,实现未开始。各子任务开始前建立 tasks 对应目录的 SPEC.md、TODO.csv、PROGRESS.md,补充具体验证命令和证据。
完成条件:全部子任务通过,业务内容有明确编辑入口,真实保存、发布隔离及生产部署验证完成。
@@ -0,0 +1,13 @@
# 进度记录
2026-10-09:与现有 ADR 0020、后续计划和交付清单对齐,制定四阶段实施计划。
2026-10-09:完成任务 1。盘点两套模板页面与 manifest / renderer 目标,修复餐饮首页身份区点选、咨询页字段过滤和首页业务目标 key;`pnpm validate:templates` 19 项通过,浏览器测试 2 项通过。
2026-10-09:完成任务 2、3、4。区域来源改为按 binding 推导;编辑面板改单列自适应;咨询表单字段可独立点选和编辑。Admin/Taro 类型检查与浏览器测试通过。
- 任务:可视化内容编辑闭环。
- 形态:epic。
- 进度:5/5 子任务完成。
- 当前:本轮计划已完成;后续可继续做真实数据库持久化和发布隔离验收。
- 验证:`pnpm validate:templates`、Admin/Taro typecheck、Admin build、`ADMIN_URL=http://localhost:3005 pnpm --filter @personal-brand/taro test:browser -- admin-editor.spec.ts` 均通过;计划 CSV 未纳入 Prettier 检查。
- 文件:.codex-tasks/visual-editor-closure/SUBTASKS.csv。
- 下一步:使用隔离品牌执行真实 API 保存、发布隔离和重载验证。
@@ -0,0 +1,6 @@
id,task,task_type,status,depends_on,task_dir,acceptance_criteria,validation_command,completed_at,retry_count,notes
1,逐页建立覆盖清单,single-full,DONE,,tasks/coverage,所有页面内容与字段对应且缺陷可复现,pnpm validate:templates; pnpm --filter @personal-brand/taro test:browser -- admin-editor.spec.ts,2026-10-09,0,已盘点两套模板页面;首批缺口已复现并修复:首页身份区目标、咨询品牌字段过滤、餐饮首页目标 key;契约 19 项和浏览器 2 项通过
2,修复通用选区绑定与模板发现,single-full,DONE,1,tasks/contract,混合来源及重复记录映射正确且契约测试通过,pnpm validate:templates; pnpm --filter @personal-brand/admin typecheck; 浏览器测试,2026-10-09,0,区域来源按 binding 推导;餐饮首页身份目标和业务卡片目标对齐;切页及记录失效选择已有清理逻辑
3,整理选区面板与保存交互,single-full,DONE,2,tasks/inspector,布局及失败和未保存切换验证通过,pnpm --filter @personal-brand/admin typecheck; 浏览器测试,2026-10-09,0,选区字段改单列自适应并移除固定最小高度;保持保存失败输入不重置
4,接通咨询字段编辑,single-full,DONE,2;3,tasks/inquiry,配置保存重载一致且历史提交不受损,pnpm --filter @personal-brand/admin typecheck; 浏览器测试,2026-10-09,0,咨询字段可独立点选并编辑标题、类型、必填、选项;预览草稿不提交真实咨询
5,全页面回归与部署验收,single-full,DONE,1;2;3;4,tasks/delivery,覆盖清单及工程门槛和部署验收通过,pnpm validate:templates; pnpm --filter @personal-brand/admin build; pnpm --filter @personal-brand/admin typecheck; pnpm --filter @personal-brand/taro typecheck; 浏览器测试,2026-10-09,0,模板契约 19 项、浏览器 2 项、Admin build、Admin/Taro typecheck 通过;CSV 不交给 Prettier
1 id task task_type status depends_on task_dir acceptance_criteria validation_command completed_at retry_count notes
2 1 逐页建立覆盖清单 single-full DONE tasks/coverage 所有页面内容与字段对应且缺陷可复现 pnpm validate:templates; pnpm --filter @personal-brand/taro test:browser -- admin-editor.spec.ts 2026-10-09 0 已盘点两套模板页面;首批缺口已复现并修复:首页身份区目标、咨询品牌字段过滤、餐饮首页目标 key;契约 19 项和浏览器 2 项通过
3 2 修复通用选区绑定与模板发现 single-full DONE 1 tasks/contract 混合来源及重复记录映射正确且契约测试通过 pnpm validate:templates; pnpm --filter @personal-brand/admin typecheck; 浏览器测试 2026-10-09 0 区域来源按 binding 推导;餐饮首页身份目标和业务卡片目标对齐;切页及记录失效选择已有清理逻辑
4 3 整理选区面板与保存交互 single-full DONE 2 tasks/inspector 布局及失败和未保存切换验证通过 pnpm --filter @personal-brand/admin typecheck; 浏览器测试 2026-10-09 0 选区字段改单列自适应并移除固定最小高度;保持保存失败输入不重置
5 4 接通咨询字段编辑 single-full DONE 2;3 tasks/inquiry 配置保存重载一致且历史提交不受损 pnpm --filter @personal-brand/admin typecheck; 浏览器测试 2026-10-09 0 咨询字段可独立点选并编辑标题、类型、必填、选项;预览草稿不提交真实咨询
6 5 全页面回归与部署验收 single-full DONE 1;2;3;4 tasks/delivery 覆盖清单及工程门槛和部署验收通过 pnpm validate:templates; pnpm --filter @personal-brand/admin build; pnpm --filter @personal-brand/admin typecheck; pnpm --filter @personal-brand/taro typecheck; 浏览器测试 2026-10-09 0 模板契约 19 项、浏览器 2 项、Admin build、Admin/Taro typecheck 通过;CSV 不交给 Prettier
@@ -0,0 +1,13 @@
template,page,visible_content,renderer_target,manifest_editor,source,status,evidence
acheng-campus-food,home,主理人身份、地点、出摊图片、餐品标题、首页操作按钮、承诺、业务卡片,food.home.identity; food.home.location; food.home.hero; food.home.offerings-heading; food.home.actions; food.home.promise-heading; acheng-campus-food.home.offering,对应 sections 已声明并补齐身份与操作目标,brand; offering; trust,已覆盖,契约测试 + 浏览器点选
acheng-campus-food,offerings,菜单说明、业务卡片,acheng-campus-food.offerings.menu; acheng-campus-food.offerings.item,对应 sections 已声明,brand; offering,已覆盖,契约测试 + 浏览器点选
acheng-campus-food,service,出摊说明、日程、配送、流程,acheng-campus-food.service.service; trust:schedule; trust:coverage; trust:process,对应 sections / trust declarations 已声明,brand; trust,待第二阶段复核,已存在浏览器点选路径
acheng-campus-food,profile,主理人与信任内容,acheng-campus-food.profile.identity; trust:credential; trust:case; trust:promise,对应 sections / trust declarations 已声明,brand; trust,待第二阶段复核,已存在 renderer target
acheng-campus-food,detail,餐品详情、详情说明,acheng-campus-food.detail.dishDetail; acheng-campus-food.detail.detailCopy,对应 sections 已声明,offering; brand,已覆盖,浏览器已验证底栏与编辑入口
acheng-campus-food,inquiry,页面文案、访客表单,acheng-campus-food.inquiry.booking,对应 section 已声明;Admin 已允许 inquiry section 编辑,brand; inquiry,首批已修复,浏览器已验证表单展示
acheng-campus-food,success,提交结果文案,acheng-campus-food.success.successCopy,对应 section 已声明,brand,待第二阶段复核,已验证页面可切换
acheng-campus-food,records,记录页文案,acheng-campus-food.records.recordsCopy,对应 section 已声明,brand; records,待第二阶段复核,已验证页面可切换
linjing-editorial,home,身份、主视觉、证明、主张、案例,editorial.home.identity; editorial.home.hero; editorial.home.proof; editorial.home.manifesto; editorial.home.works; linjing-editorial.home.home,对应 sections 已声明,brand; trust; offering,已覆盖,契约测试 + 浏览器点选
linjing-editorial,offerings,案例说明、业务卡片,linjing-editorial.offerings.cases; linjing-editorial.offerings.item,对应 sections 已声明,brand; offering,待第二阶段复核,已有 renderer target
linjing-editorial,profile,身份、履约、联系方式、信任内容,linjing-editorial.profile.identity; linjing-editorial.profile.profileDetails; trust:*,对应 sections / trust declarations 已声明,brand; trust,已覆盖,契约测试 + 浏览器点选
linjing-editorial,detail,案例详情、详情说明,linjing-editorial.detail.projectDetail; linjing-editorial.detail.detailCopy,对应 sections 已声明,offering; brand,待第二阶段复核,已有 renderer target
1 template page visible_content renderer_target manifest_editor source status evidence
2 acheng-campus-food home 主理人身份、地点、出摊图片、餐品标题、首页操作按钮、承诺、业务卡片 food.home.identity; food.home.location; food.home.hero; food.home.offerings-heading; food.home.actions; food.home.promise-heading; acheng-campus-food.home.offering 对应 sections 已声明并补齐身份与操作目标 brand; offering; trust 已覆盖 契约测试 + 浏览器点选
3 acheng-campus-food offerings 菜单说明、业务卡片 acheng-campus-food.offerings.menu; acheng-campus-food.offerings.item 对应 sections 已声明 brand; offering 已覆盖 契约测试 + 浏览器点选
4 acheng-campus-food service 出摊说明、日程、配送、流程 acheng-campus-food.service.service; trust:schedule; trust:coverage; trust:process 对应 sections / trust declarations 已声明 brand; trust 待第二阶段复核 已存在浏览器点选路径
5 acheng-campus-food profile 主理人与信任内容 acheng-campus-food.profile.identity; trust:credential; trust:case; trust:promise 对应 sections / trust declarations 已声明 brand; trust 待第二阶段复核 已存在 renderer target
6 acheng-campus-food detail 餐品详情、详情说明 acheng-campus-food.detail.dishDetail; acheng-campus-food.detail.detailCopy 对应 sections 已声明 offering; brand 已覆盖 浏览器已验证底栏与编辑入口
7 acheng-campus-food inquiry 页面文案、访客表单 acheng-campus-food.inquiry.booking 对应 section 已声明;Admin 已允许 inquiry section 编辑 brand; inquiry 首批已修复 浏览器已验证表单展示
8 acheng-campus-food success 提交结果文案 acheng-campus-food.success.successCopy 对应 section 已声明 brand 待第二阶段复核 已验证页面可切换
9 acheng-campus-food records 记录页文案 acheng-campus-food.records.recordsCopy 对应 section 已声明 brand; records 待第二阶段复核 已验证页面可切换
10 linjing-editorial home 身份、主视觉、证明、主张、案例 editorial.home.identity; editorial.home.hero; editorial.home.proof; editorial.home.manifesto; editorial.home.works; linjing-editorial.home.home 对应 sections 已声明 brand; trust; offering 已覆盖 契约测试 + 浏览器点选
11 linjing-editorial offerings 案例说明、业务卡片 linjing-editorial.offerings.cases; linjing-editorial.offerings.item 对应 sections 已声明 brand; offering 待第二阶段复核 已有 renderer target
12 linjing-editorial profile 身份、履约、联系方式、信任内容 linjing-editorial.profile.identity; linjing-editorial.profile.profileDetails; trust:* 对应 sections / trust declarations 已声明 brand; trust 已覆盖 契约测试 + 浏览器点选
13 linjing-editorial detail 案例详情、详情说明 linjing-editorial.detail.projectDetail; linjing-editorial.detail.detailCopy 对应 sections 已声明 offering; brand 待第二阶段复核 已有 renderer target
+1
View File
@@ -14,6 +14,7 @@ apps/miniapp/project.private.config.json
.worktrees/ .worktrees/
apps/taro/src/assets/ apps/taro/src/assets/
apps/admin/public/template-preview/
apps/taro/test-results/ apps/taro/test-results/
apps/taro/playwright-report/ apps/taro/playwright-report/
+1
View File
@@ -1,6 +1,7 @@
node_modules node_modules
.turbo .turbo
dist dist
apps/admin/public/template-preview
.next .next
prototype prototype
pnpm-lock.yaml pnpm-lock.yaml
+1 -1
View File
@@ -2,4 +2,4 @@ VITE_APP_BASE_PATH=/admin/
VITE_API_BASE_URL=/api VITE_API_BASE_URL=/api
VITE_DEV_API_TARGET=http://localhost:3001 VITE_DEV_API_TARGET=http://localhost:3001
ADMIN_PORT=3000 ADMIN_PORT=3000
VITE_TEMPLATE_PREVIEW_URLS={"acheng-campus-food":"http://localhost:3002","linjing-editorial":"http://localhost:3003"} VITE_TEMPLATE_PREVIEW_URL=http://localhost:3002
@@ -0,0 +1,78 @@
.brand-page__content {
max-width: 960px;
}
.brand-page__content[hidden] {
display: none;
}
.brand-page__toolbar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
padding: 16px 0;
border-bottom: 1px solid #e5e7eb;
margin-bottom: 20px;
}
@media (max-width: 575px) {
.brand-page__toolbar {
flex-wrap: wrap;
}
}
.brand-page__settings {
min-width: 0;
}
.brand-settings-section {
padding: 24px 0;
border-top: 1px solid #f0f0f0;
}
.brand-settings-section:first-child {
padding-top: 8px;
border-top: 0;
}
.brand-settings-section__header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 20px;
}
.brand-settings-section__header .ant-typography {
margin: 0;
}
.brand-settings-section__header .ant-typography + .ant-typography {
display: block;
margin-top: 4px;
}
.brand-page__template-note {
margin-top: 24px;
}
@media (max-width: 1199px) {
.brand-page__content {
display: block;
}
.brand-page__template-note {
position: static;
margin-top: 24px;
}
}
@media (max-width: 575px) {
.brand-settings-section__header {
display: block;
}
.brand-settings-section__header .ant-tag {
display: inline-block;
margin-top: 10px;
}
}
+102 -26
View File
@@ -1,13 +1,33 @@
import { Button, Card, Col, Form, Input, Row, Select, Space, Tag, Typography, message } from "antd"; import {
Alert,
Button,
Col,
Form,
Input,
Row,
Select,
Segmented,
Space,
Tag,
Typography,
message,
} from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { Link } from "react-router-dom";
import type { BrandProfile } from "@personal-brand/api-client"; import type { BrandProfile } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js"; import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js"; import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { ImageUrlField } from "../../components/ImageUrlField.js"; import { ImageUrlField } from "../../components/ImageUrlField.js";
import { MutationError, QueryState } from "../../components/QueryState.js"; import { MutationError, QueryState } from "../../components/QueryState.js";
import { PresentationEditor } from "./PresentationEditor.js"; import { PresentationEditor } from "./PresentationEditor.js";
import "./BrandPage.css";
import { useEditorDraft } from "./use-editor-draft.js";
export function BrandPage() { export function BrandPage() {
const [panel, setPanel] = useState("pages");
const [dirty, setDirty] = useState(false);
useEditorDraft(dirty);
const client = createApiClient(); const client = createApiClient();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const [form] = Form.useForm<BrandProfile>(); const [form] = Form.useForm<BrandProfile>();
@@ -16,6 +36,10 @@ export function BrandPage() {
queryKey: ["admin-workspace"], queryKey: ["admin-workspace"],
queryFn: () => client.getAdminWorkspace(), queryFn: () => client.getAdminWorkspace(),
}); });
const previewWorkspace = useQuery({
queryKey: ["admin-preview-workspace"],
queryFn: () => client.getAdminPreviewWorkspace(),
});
const template = useQuery({ const template = useQuery({
queryKey: ["template", brand.data?.templateKey], queryKey: ["template", brand.data?.templateKey],
queryFn: () => client.getPublicTemplate(brand.data!.templateKey), queryFn: () => client.getPublicTemplate(brand.data!.templateKey),
@@ -24,8 +48,10 @@ export function BrandPage() {
const save = useMutation({ const save = useMutation({
mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values), mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values),
onSuccess: () => { onSuccess: () => {
setDirty(false);
message.success("品牌表达已保存"); message.success("品牌表达已保存");
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] }); void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
}, },
}); });
return ( return (
@@ -33,22 +59,50 @@ export function BrandPage() {
{!brand.data ? null : ( {!brand.data ? null : (
<> <>
<AdminPageHeader <AdminPageHeader
title="品牌资料" title="小程序工作台"
description="先让访客理解你是谁、服务谁,以及为什么值得信任。" description={
template.data?.description
? `先让访客理解你是谁、服务谁,以及为什么值得信任。${template.data.description}`
: "先让访客理解你是谁、服务谁,以及为什么值得信任。"
}
extra={<Tag color="blue">{template.data?.name ?? "当前模板"}</Tag>} extra={<Tag color="blue">{template.data?.name ?? "当前模板"}</Tag>}
/> />
<Row gutter={[24, 24]} align="top"> <div className="brand-page__toolbar">
<Col xs={24} xl={16}> <Segmented
aria-label="工作台视图"
value={panel}
onChange={(value) => setPanel(String(value))}
options={[
{ value: "pages", label: "页面编辑" },
{ value: "brand", label: "品牌资料" },
]}
/>
<Space>
<Tag color={dirty ? "orange" : "default"}>
{dirty ? "品牌资料有未保存修改" : "草稿工作区"}
</Tag>
<Link to="/admin/publication">检查与发布 →</Link>
</Space>
</div>
<div className="brand-page__content" hidden={panel !== "brand"}>
<div className="brand-page__settings">
<Form <Form
form={form} form={form}
layout="vertical" layout="vertical"
initialValues={brand.data} initialValues={brand.data}
onValuesChange={() => setDirty(true)}
onFinish={(values) => save.mutate(values)} onFinish={(values) => save.mutate(values)}
> >
<Card <section className="brand-settings-section" aria-labelledby="brand-identity-title">
title="我是谁" <div className="brand-settings-section__header">
extra={<Typography.Text type="secondary">公开展示</Typography.Text>} <div>
> <Typography.Title id="brand-identity-title" level={4}>
我是谁
</Typography.Title>
<Typography.Text type="secondary">公开展示的品牌身份和定位。</Typography.Text>
</div>
<Tag>品牌基础信息</Tag>
</div>
<Form.Item <Form.Item
name="name" name="name"
label="品牌名称" label="品牌名称"
@@ -73,8 +127,18 @@ export function BrandPage() {
placeholder="让第一次认识你的人快速建立基本信任。" placeholder="让第一次认识你的人快速建立基本信任。"
/> />
</Form.Item> </Form.Item>
</Card> </section>
<Card title="如何联系与合作" style={{ marginTop: 24 }}> <section className="brand-settings-section" aria-labelledby="brand-contact-title">
<div className="brand-settings-section__header">
<div>
<Typography.Title id="brand-contact-title" level={4}>
如何联系与合作
</Typography.Title>
<Typography.Text type="secondary">
让访客知道联系渠道、服务范围和响应预期。
</Typography.Text>
</div>
</div>
<Row gutter={16}> <Row gutter={16}>
<Col xs={24} md={12}> <Col xs={24} md={12}>
<Form.Item name="hours" label="可联系时间"> <Form.Item name="hours" label="可联系时间">
@@ -104,8 +168,18 @@ export function BrandPage() {
> >
<Input.TextArea rows={3} placeholder="例如:收到咨询后 1 个工作日内回复。" /> <Input.TextArea rows={3} placeholder="例如:收到咨询后 1 个工作日内回复。" />
</Form.Item> </Form.Item>
</Card> </section>
<Card title="模板与品牌视觉" style={{ marginTop: 24 }}> <section className="brand-settings-section" aria-labelledby="brand-visual-title">
<div className="brand-settings-section__header">
<div>
<Typography.Title id="brand-visual-title" level={4}>
模板与品牌视觉
</Typography.Title>
<Typography.Text type="secondary">
模板负责业务表达,品牌信息仍由你统一维护。
</Typography.Text>
</div>
</div>
<Form.Item <Form.Item
name="templateKey" name="templateKey"
label="业务表达模板" label="业务表达模板"
@@ -135,7 +209,7 @@ export function BrandPage() {
</Form.Item> </Form.Item>
</Col> </Col>
</Row> </Row>
</Card> </section>
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}> <Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
<MutationError error={save.error} /> <MutationError error={save.error} />
<Button type="primary" htmlType="submit" loading={save.isPending} size="large"> <Button type="primary" htmlType="submit" loading={save.isPending} size="large">
@@ -143,25 +217,27 @@ export function BrandPage() {
</Button> </Button>
</Space> </Space>
</Form> </Form>
</div>
{template.data ? (
<Alert
className="brand-page__template-note"
type="info"
showIcon
message={`当前使用:${template.data.name}`}
description={`适用场景:${template.data.serviceCategories.join("、") || "通用品牌展示"}`}
/>
) : null}
</div>
<div hidden={panel !== "pages"}>
<PresentationEditor <PresentationEditor
templateContent={workspace.data?.templateContent} templateContent={workspace.data?.templateContent}
previewWorkspace={previewWorkspace.data}
config={brand.data.config} config={brand.data.config}
brand={brand.data} brand={brand.data}
loading={workspace.isLoading} loading={workspace.isLoading}
error={workspace.error} error={workspace.error}
/> />
</Col> </div>
<Col xs={24} xl={8}>
{template.data && (
<Card title="模板说明" style={{ marginTop: 24 }}>
<Typography.Paragraph>{template.data.description}</Typography.Paragraph>
<Typography.Text type="secondary">
服务分类:{template.data.serviceCategories.join("、")}
</Typography.Text>
</Card>
)}
</Col>
</Row>
</> </>
)} )}
</QueryState> </QueryState>
@@ -0,0 +1,144 @@
.component-template-preview-shell {
height: 100%;
}
.component-template-preview__tools {
display: flex;
gap: 8px;
padding: 8px 12px;
border-bottom: 1px solid #e8e8e8;
background: #fff;
}
.component-template-preview__tools button {
padding: 4px 12px;
border: 1px solid #d9d9d9;
border-radius: 6px;
background: #fff;
cursor: pointer;
}
.component-template-preview__tools button[aria-pressed="true"] {
border-color: #1677ff;
color: #1677ff;
}
.component-template-preview {
position: relative;
width: 100%;
height: calc(100% - 49px);
min-height: 510px;
padding: 24px 16px;
overflow-x: hidden;
overflow-y: auto;
background: #f3f4f6;
}
.component-template-preview__canvas {
position: relative;
container-type: inline-size;
width: min(100%, 390px);
min-height: calc(100% - 48px);
margin: 0 auto;
overflow: visible;
border-radius: 14px;
background: #fff;
box-shadow:
0 0 0 1px rgba(0, 0, 0, 0.04),
0 10px 30px rgba(0, 0, 0, 0.08);
}
.component-template-preview__canvas,
.component-template-preview__canvas * {
box-sizing: border-box;
}
.component-template-preview__canvas > * {
width: 100%;
max-width: 100%;
}
:where(.component-template-preview__canvas) button {
display: block;
width: -webkit-fill-available;
margin: 0;
padding: 0;
border: 0;
border-radius: 0;
background: transparent;
color: inherit;
font: inherit;
font-size: 4.8cqw;
line-height: 2.55555556;
text-align: center;
}
:where(.component-template-preview__canvas) input {
display: block;
width: 100%;
min-width: 0;
}
.component-template-preview__canvas img {
flex-shrink: 0;
display: block;
max-width: 100%;
object-fit: cover;
}
.component-template-preview[data-editor-mode="edit"] [data-editor-target] {
cursor: pointer;
}
.component-template-preview__outline {
position: absolute;
z-index: 5;
pointer-events: none;
border: 2px solid #91caff;
border-radius: 4px;
}
.component-template-preview__outline.is-selected {
z-index: 6;
border-color: #1677ff;
box-shadow: 0 0 0 3px rgba(22, 119, 255, 0.16);
}
.component-template-preview__composite-select {
position: absolute;
z-index: 7;
width: auto !important;
padding: 2px 8px !important;
border: 1px solid #1677ff !important;
border-radius: 4px !important;
background: #fff !important;
color: #0958d9 !important;
font-size: 12px !important;
line-height: 20px !important;
cursor: pointer;
}
.component-template-preview__outline span {
position: absolute;
bottom: 100%;
left: 0;
max-width: 100%;
padding: 2px 7px;
overflow: hidden;
border-radius: 4px 4px 0 0;
background: #1677ff;
color: #fff;
font-size: 12px;
line-height: 18px;
text-overflow: ellipsis;
white-space: nowrap;
}
.component-template-preview__tools[hidden] {
display: none;
}
.component-template-preview-shell:has(.component-template-preview__tools[hidden])
.component-template-preview {
height: 100%;
}
@@ -0,0 +1,227 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import type { RuntimeWorkspace } from "@personal-brand/api-client";
import { Alert } from "antd";
import { resolveTemplateRenderer } from "./component-renderers.jsx";
import type { PreviewSelection, PreviewTarget } from "./preview-selection.js";
import "../../../../../packages/template-acheng-campus-food/taro/style.css";
import "../../../../../packages/template-linjing-editorial/taro/style.css";
import "./ComponentTemplatePreview.css";
type PreviewProps = {
workspace: RuntimeWorkspace;
page: string;
offeringId?: string;
selection?: PreviewSelection;
targets: PreviewTarget[];
onTargetSelected: (selection?: PreviewSelection) => void;
};
type Outline = { top: number; left: number; width: number; height: number; label: string };
export function ComponentTemplatePreview({
workspace,
page,
offeringId,
selection,
targets,
onTargetSelected,
}: PreviewProps) {
const Renderer = resolveTemplateRenderer(workspace);
const root = useRef<HTMLDivElement>(null);
const [mode, setMode] = useState<"edit" | "browse">("edit");
const [hovered, setHovered] = useState<HTMLElement | null>(null);
const [hoverOutline, setHoverOutline] = useState<Outline | null>(null);
const [selectedOutline, setSelectedOutline] = useState<Outline | null>(null);
const [compositeOutlines, setCompositeOutlines] = useState<Array<Outline & { key: string }>>([]);
const targetFor = useCallback(
(element: Element | null): HTMLElement | null => {
let candidate = element?.closest<HTMLElement>("[data-editor-target]");
let deepest: HTMLElement | null = null;
let composite: HTMLElement | null = null;
while (candidate && root.current?.contains(candidate)) {
const target = targets.find((item) => item.key === candidate?.dataset.editorTarget);
if (target && !deepest) deepest = candidate;
if (target?.composite) composite = candidate;
candidate = candidate.parentElement?.closest<HTMLElement>("[data-editor-target]") ?? null;
}
return composite ?? deepest;
},
[targets],
);
const selectedElement = useCallback(() => {
if (!selection) return null;
return (
Array.from(root.current?.querySelectorAll<HTMLElement>("[data-editor-target]") ?? []).find(
(element) =>
element.dataset.editorTarget === selection.targetKey &&
(element.dataset.editorRecordId || undefined) === selection.recordId,
) ?? null
);
}, [selection]);
const measure = useCallback(
(element: HTMLElement | null): Outline | null => {
const viewport = root.current;
if (!element || !viewport || !viewport.contains(element)) return null;
const box = element.getBoundingClientRect();
const parent = viewport.getBoundingClientRect();
const target = targets.find((item) => item.key === element.dataset.editorTarget);
if (!target || !box.width || !box.height) return null;
return {
top: box.top - parent.top + viewport.scrollTop,
left: box.left - parent.left + viewport.scrollLeft,
width: box.width,
height: box.height,
label: target.label,
};
},
[targets],
);
useLayoutEffect(() => {
const viewport = root.current;
if (!viewport) return;
let frame = 0;
const update = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
setSelectedOutline(measure(selectedElement()));
setHoverOutline(measure(hovered));
setCompositeOutlines(
targets
.filter((target) => target.composite)
.flatMap((target) => {
const element = viewport.querySelector<HTMLElement>(
`[data-editor-target="${CSS.escape(target.key)}"]`,
);
const outline = measure(element);
return outline ? [{ ...outline, key: target.key }] : [];
}),
);
});
};
update();
const resize = new ResizeObserver(update);
resize.observe(viewport);
viewport
.querySelectorAll<HTMLElement>("[data-editor-target]")
.forEach((node) => resize.observe(node));
window.addEventListener("resize", update);
viewport.addEventListener("scroll", update);
viewport.addEventListener("load", update, true);
return () => {
cancelAnimationFrame(frame);
resize.disconnect();
window.removeEventListener("resize", update);
viewport.removeEventListener("scroll", update);
viewport.removeEventListener("load", update, true);
};
}, [hovered, measure, selectedElement, workspace, page]);
useEffect(() => {
selectedElement()?.scrollIntoView({ block: "nearest", behavior: "smooth" });
}, [selectedElement]);
useEffect(() => {
const clear = (event: KeyboardEvent) => {
if (event.key === "Escape") onTargetSelected(undefined);
};
window.addEventListener("keydown", clear);
return () => window.removeEventListener("keydown", clear);
}, [onTargetSelected]);
if (!Renderer)
return <Alert type="warning" showIcon message="此模板尚无组件预览,请使用页面预览" />;
return (
<div className="component-template-preview-shell">
<div
className="component-template-preview__tools"
aria-label="预览操作模式"
hidden={!targets.length}
>
<button type="button" aria-pressed={mode === "edit"} onClick={() => setMode("edit")}>
点选编辑
</button>
<button type="button" aria-pressed={mode === "browse"} onClick={() => setMode("browse")}>
浏览页面
</button>
</div>
<div
ref={root}
className="component-template-preview"
data-active-target={selection?.targetKey}
data-active-record-id={selection?.recordId}
data-editor-mode={mode}
onPointerMoveCapture={(event) => {
if (mode !== "edit" || !targets.length) return;
const next = targetFor(event.target instanceof Element ? event.target : null);
if (next !== hovered) setHovered(next);
}}
onPointerLeave={() => setHovered(null)}
onClickCapture={(event) => {
if (mode !== "edit" || !targets.length) return;
const canvas = root.current?.querySelector(".component-template-preview__canvas");
if (!event.target || !(event.target instanceof Node) || !canvas?.contains(event.target))
return;
const pointTarget = document.elementFromPoint(event.clientX, event.clientY);
const element = targetFor(
pointTarget && canvas.contains(pointTarget) ? pointTarget : null,
);
event.preventDefault();
event.stopPropagation();
onTargetSelected(
element
? {
targetKey: element.dataset.editorTarget!,
...(element.dataset.editorRecordId
? { recordId: element.dataset.editorRecordId }
: {}),
}
: undefined,
);
}}
>
<div className="component-template-preview__canvas">
<Renderer workspace={workspace} page={page} {...(offeringId ? { offeringId } : {})} />
</div>
{mode === "edit"
? compositeOutlines.map((outline) => (
<button
key={outline.key}
type="button"
className="component-template-preview__composite-select"
style={{ top: outline.top + 4, left: outline.left + 4 }}
aria-label={`选择${targets.find((target) => target.key === outline.key)?.label ?? outline.label}`}
onClick={() => onTargetSelected({ targetKey: outline.key })}
>
选择{targets.find((target) => target.key === outline.key)?.label ?? outline.label}
</button>
))
: null}
{mode === "edit" && hoverOutline ? (
<div
className="component-template-preview__outline is-hovered"
style={{
top: hoverOutline.top,
left: hoverOutline.left,
width: hoverOutline.width,
height: hoverOutline.height,
}}
aria-hidden="true"
/>
) : null}
{mode === "edit" && selectedOutline ? (
<div
className="component-template-preview__outline is-selected"
style={{
top: selectedOutline.top,
left: selectedOutline.left,
width: selectedOutline.width,
height: selectedOutline.height,
}}
data-selected-target={selection?.targetKey}
data-selected-record-id={selection?.recordId}
>
<span>{selectedOutline.label}</span>
</div>
) : null}
</div>
</div>
);
}
// @ts-nocheck
@@ -0,0 +1,136 @@
import { Alert, Button, Form, Input, Select, Space, Switch, Typography, message } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import type { RuntimeWorkspace } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { MutationError } from "../../components/QueryState.js";
type RuntimeInquiryForm = RuntimeWorkspace["inquiryForms"][number];
export function InquiryPreviewEditor({
runtime,
fieldKey,
onDraft,
onSaved,
}: {
runtime: RuntimeInquiryForm;
fieldKey: string;
onDraft: (fields: RuntimeInquiryForm["fields"]) => void;
onSaved?: () => void;
}) {
const [form] = Form.useForm<Record<string, unknown>>();
const cache = useQueryClient();
const query = useQuery({
queryKey: ["admin-inquiry-forms"],
queryFn: () => createApiClient().listAdminInquiryForms(),
});
const record = query.data?.find((item) => item.id === runtime.key);
const field = runtime.fields.find((item) => item.key === fieldKey);
useEffect(() => {
if (field) form.setFieldsValue({ ...field });
}, [fieldKey, runtime.key, form]);
const update = (values: Record<string, unknown>) =>
runtime.fields.map((item) => (item.key === fieldKey ? { ...item, ...values } : item));
const save = useMutation({
mutationFn: async (values: Record<string, unknown>) => {
if (!record || !field) throw new Error("表单已不存在,请刷新后重试");
const fieldsSnapshot = record.fieldsSnapshot.map((item) => {
if (!item || typeof item !== "object" || (item as { key?: string }).key !== fieldKey)
return item;
const type =
values.type === "tel"
? "phone"
: values.type === "checkbox"
? "multi-select"
: values.type;
return { ...item, ...values, type };
});
return createApiClient().updateAdminInquiryForm(record.id, { fieldsSnapshot });
},
onSuccess: () => {
onSaved?.();
message.success("表单字段已保存为草稿");
void cache.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
void cache.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
void cache.invalidateQueries({ queryKey: ["publication-readiness"] });
},
});
if (query.isError)
return (
<Alert
type="error"
message="表单读取失败"
action={<Button onClick={() => void query.refetch()}>重试</Button>}
/>
);
if (!record)
return (
<Alert
type="info"
message={query.isPending ? "正在读取表单" : "未找到对应表单,请刷新后重试"}
/>
);
if (!field) return <Alert type="warning" message="字段已不存在" />;
return (
<Form<Record<string, unknown>>
form={form}
layout="vertical"
initialValues={field}
onValuesChange={(_, values) => onDraft(update(values))}
onFinish={(values) => save.mutate(values)}
>
<Typography.Paragraph type="secondary">
{record.name} · 编辑字段:{field.label}
</Typography.Paragraph>
<Form.Item
name="label"
label="字段标题"
rules={[{ required: true, message: "请填写字段标题" }]}
>
<Input />
</Form.Item>
<Form.Item name="type" label="输入方式">
<Select
options={[
{ value: "text", label: "简短文字" },
{ value: "textarea", label: "详细说明" },
{ value: "tel", label: "联系电话" },
{ value: "number", label: "数字" },
{ value: "date", label: "日期" },
{ value: "select", label: "单项选择" },
{ value: "radio", label: "单选按钮" },
{ value: "checkbox", label: "多项选择" },
]}
/>
</Form.Item>
<Form.Item name="required" label="必填" valuePropName="checked">
<Switch />
</Form.Item>
<Form.List name="options">
{(fields, { add, remove }) => (
<div>
{fields.length ? <Typography.Title level={5}>选项</Typography.Title> : null}
{fields.map(({ key, name }) => (
<Space key={key} align="start">
<Form.Item name={[name, "label"]} label="选项名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name={[name, "value"]} label="选项标识" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Button onClick={() => remove(name)}>删除</Button>
</Space>
))}
<Button onClick={() => add({ label: "新选项", value: crypto.randomUUID() })}>
添加选项
</Button>
</div>
)}
</Form.List>
<MutationError error={save.error} />
<Button style={{ marginTop: 24 }} type="primary" htmlType="submit" loading={save.isPending}>
保存表单字段
</Button>
</Form>
);
}
@@ -0,0 +1,161 @@
.presentation-editor {
margin-top: 0;
padding-top: 8px;
}
.presentation-editor__header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 24px;
}
.presentation-editor__header .ant-typography {
margin-top: 0;
}
.presentation-editor__header .ant-typography + .ant-typography {
margin-bottom: 0;
}
.presentation-editor > .ant-space {
display: flex;
width: 100%;
margin-bottom: 24px !important;
padding: 6px;
border: 1px solid #e8e8e8;
border-radius: 10px;
background: #fafafa;
}
@media (max-width: 575px) {
.presentation-editor__header {
display: block;
}
.presentation-editor__header .ant-tag {
display: inline-block;
margin-top: 8px;
}
}
.presentation-editor__workspace {
display: grid;
grid-template-columns: 200px minmax(300px, 1fr) minmax(280px, 360px);
grid-template-areas: "outline preview inspector";
margin: 0 !important;
border: 1px solid #e5e7eb;
border-radius: 12px;
overflow: hidden;
background: #fff;
}
.presentation-editor__preview {
grid-area: preview;
padding: 20px !important;
background: #f8fafc;
min-width: 0;
}
.presentation-editor__inspector {
grid-area: inspector;
padding: 24px !important;
min-width: 0;
border-left: 1px solid #e5e7eb;
}
.presentation-editor__outline {
grid-area: outline;
padding: 20px 12px;
border-right: 1px solid #e5e7eb;
}
.presentation-editor__regions {
display: flex;
flex-direction: column;
width: 100%;
}
.presentation-editor__regions .ant-space-item {
width: 100%;
}
.presentation-editor__regions .ant-btn {
width: 100%;
text-align: left;
border: 0;
box-shadow: none;
padding: 10px 12px;
}
.presentation-editor__regions .is-child-region {
padding-left: 24px;
}
.presentation-editor__regions .ant-btn[aria-pressed="true"] {
background: #e6f4ff;
color: #0958d9;
font-weight: 600;
}
.presentation-editor__preview .template-preview {
height: 680px;
min-height: 0;
border-radius: 10px;
}
.presentation-editor__regions .ant-btn {
height: auto;
padding: 5px 10px;
font-size: 12px;
white-space: normal;
}
.presentation-editor__empty {
padding: 56px 16px;
text-align: center;
}
.presentation-editor__inspector .ant-form-item {
margin-bottom: 24px;
}
.presentation-editor__inspector form > .ant-space:last-child {
position: sticky;
bottom: 0;
z-index: 2;
padding: 16px 0 4px;
border-top: 1px solid #e5e7eb;
background: #fff;
}
.presentation-editor__inspector form > .ant-space:last-child .ant-btn-primary {
min-width: 140px;
}
.presentation-editor__inspector > .ant-tag {
margin-bottom: 20px;
}
@media (max-width: 1199px) {
.presentation-editor__workspace {
grid-template-columns: minmax(0, 1fr);
grid-template-areas: "outline" "preview" "inspector";
}
.presentation-editor__outline {
border-right: 0;
border-bottom: 1px solid #e5e7eb;
}
.presentation-editor__inspector {
border-left: 0;
border-top: 1px solid #e5e7eb;
}
}
@media (max-width: 575px) {
.presentation-editor__preview,
.presentation-editor__inspector {
padding: 12px !important;
}
.presentation-editor__preview .template-preview {
height: 600px;
}
.presentation-editor__navigation {
max-width: 100%;
}
}
@@ -1,7 +1,6 @@
import { import {
Alert, Alert,
Button, Button,
Card,
Divider, Divider,
Col, Col,
Form, Form,
@@ -16,32 +15,93 @@ import {
Typography, Typography,
message, message,
} from "antd"; } from "antd";
import { useMutation, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import type { AdminTemplateContent, TemplateAdminField } from "@personal-brand/api-client"; import type {
AdminTemplateContent,
RuntimeWorkspace,
TemplateAdminField,
TemplateAdminSection,
Offering,
TrustContent,
} from "@personal-brand/api-client";
import type { BrandProfile } from "@personal-brand/api-client"; import type { BrandProfile } from "@personal-brand/api-client";
import { projectBrandAliases, projectTrustPresentation } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js"; import { createApiClient } from "../../lib/api.js";
import { ImageUrlField } from "../../components/ImageUrlField.js"; import { ImageUrlField } from "../../components/ImageUrlField.js";
import { TemplateListField } from "../../components/TemplateListField.js"; import { TemplateListField } from "../../components/TemplateListField.js";
import { MutationError } from "../../components/QueryState.js"; import { MutationError } from "../../components/QueryState.js";
import { TemplatePreview } from "./TemplatePreview.js"; import { TemplatePreview } from "./TemplatePreview.js";
import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js";
import { import {
resolvePreviewSelection,
type PreviewSelection,
type PreviewTarget,
} from "./preview-selection.js";
import {
applyBrandPreviewValues,
applyStandardBrandValues,
applyStandardEntityValues,
applyPresentationValues, applyPresentationValues,
filterSectionsForPreviewTarget, filterSectionsForPreviewTarget,
presentationFieldName, presentationFieldName,
readPresentationValue, readPresentationValue,
type PresentationValues, type PresentationValues,
} from "./presentation-bindings.js"; } from "./presentation-bindings.js";
import "./PresentationEditor.css";
import { useEditorDraft } from "./use-editor-draft.js";
interface PresentationEditorProps { interface PresentationEditorProps {
templateContent: AdminTemplateContent | null | undefined; templateContent: AdminTemplateContent | null | undefined;
previewWorkspace?: RuntimeWorkspace | undefined;
config: Record<string, unknown> | null | undefined; config: Record<string, unknown> | null | undefined;
brand: BrandProfile; brand: BrandProfile;
loading?: boolean; loading?: boolean;
error?: unknown; error?: unknown;
} }
function trustSection(
declaration: NonNullable<AdminTemplateContent["trustContentTypes"]>[number],
page: string,
): TemplateAdminSection {
const key = `trust:${declaration.type}`;
return {
key,
title: declaration.label,
description: declaration.help ?? "编辑当前展示内容。",
page,
target: "trust",
previewTargets: [{ key, label: declaration.label }],
fields: [
{
key: "title",
binding: "trust.title",
label: declaration.adminFields.title,
input: "text" as const,
required: true,
},
...(["summary", "content"] as const)
.filter((field) => !declaration.hideStandardFields?.includes(field))
.map((field) => ({
key: field,
binding: `trust.${field}`,
label: declaration.adminFields[field],
input: "textarea" as const,
previewTarget: `trust:${declaration.type}`,
...(field === "summary" && declaration.adminFields.summaryHelp
? { help: declaration.adminFields.summaryHelp }
: {}),
...(field === "content" && declaration.required ? { required: true } : {}),
})),
...(declaration.configFields ?? []).map((field) => ({
...field,
previewTarget: `trust:${declaration.type}`,
})),
].map((field) => ({ ...field, previewTarget: `trust:${declaration.type}` })),
};
}
function renderField(field: TemplateAdminField) { function renderField(field: TemplateAdminField) {
if (field.input === "textarea") if (field.input === "textarea")
return ( return (
@@ -81,8 +141,20 @@ function renderField(field: TemplateAdminField) {
); );
} }
function previewTargetSource(
section: TemplateAdminSection,
targetKey: string,
): "brand" | "offering" | "trust" | "inquiry" {
const fields = section.fields.filter((field) => field.previewTarget === targetKey);
if (fields.some((field) => field.binding.startsWith("offering."))) return "offering";
if (fields.some((field) => field.binding.startsWith("trust."))) return "trust";
if (fields.some((field) => field.binding.startsWith("brand."))) return "brand";
return section.target;
}
export function PresentationEditor({ export function PresentationEditor({
templateContent, templateContent,
previewWorkspace,
config, config,
brand, brand,
loading, loading,
@@ -93,7 +165,20 @@ export function PresentationEditor({
const navigate = useNavigate(); const navigate = useNavigate();
const breakpoints = Grid.useBreakpoint(); const breakpoints = Grid.useBreakpoint();
const [activePage, setActivePage] = useState<string>(); const [activePage, setActivePage] = useState<string>();
const [activeTarget, setActiveTarget] = useState<string>(); const [selection, setSelection] = useState<PreviewSelection>();
const [detailOfferingId, setDetailOfferingId] = useState<string>();
const [recordDraft, setRecordDraft] = useState<{
source: "offering" | "trust";
id: string;
values: PresentationValues;
}>();
const [previewConfig, setPreviewConfig] = useState(config ?? {});
const [previewBrandValues, setPreviewBrandValues] = useState<Record<string, unknown>>({});
const [inquiryDraft, setInquiryDraft] =
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
const [brandDirty, setBrandDirty] = useState(false);
const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft);
const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand");
const sections = useMemo(() => { const sections = useMemo(() => {
const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({ const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({
...field, ...field,
@@ -113,8 +198,7 @@ export function PresentationEditor({
] ]
: []), : []),
...(templateContent?.admin.sections ?? []), ...(templateContent?.admin.sections ?? []),
] ].map((section) => ({
.map((section) => ({
...section, ...section,
fields: section.fields.filter( fields: section.fields.filter(
(field) => (field) =>
@@ -127,8 +211,7 @@ export function PresentationEditor({
"brand.address", "brand.address",
].includes(field.binding), ].includes(field.binding),
), ),
})) }));
.filter((section) => section.fields.length > 0);
}, [templateContent]); }, [templateContent]);
const pageOptions = useMemo(() => { const pageOptions = useMemo(() => {
const pages = new Map<string, string>(); const pages = new Map<string, string>();
@@ -143,13 +226,110 @@ export function PresentationEditor({
const selectedPage = pageOptions.some((item) => item.value === activePage) const selectedPage = pageOptions.some((item) => item.value === activePage)
? activePage ? activePage
: pageOptions[0]?.value; : pageOptions[0]?.value;
const visibleSections = sections.filter((section) => section.page === selectedPage); const visibleSections = sections.filter(
const visibleTargets = visibleSections.flatMap((section) => (section) =>
(section.previewTargets ?? []).map((target) => ({ ...target, page: section.page })), section.page === selectedPage &&
// 详情页内容来自所选业务记录;不再展示一套额外的品牌级详情编辑器。
!(selectedPage === "detail" && section.target === "brand"),
); );
const recordSections = useMemo(
() =>
(templateContent?.trustContentTypes ?? [])
.filter((item) => item.pages?.includes(selectedPage ?? ""))
.map((item) => trustSection(item, selectedPage ?? "home")),
[templateContent, selectedPage],
);
const visibleTargets = useMemo<PreviewTarget[]>(
() =>
[...(templateContent?.admin.sections ?? []), ...recordSections]
.filter((section) => section.page === selectedPage && selectedPage !== "detail")
.flatMap((section) =>
(section.previewTargets ?? []).map((target) => ({
...target,
page: section.page,
source: previewTargetSource(section, target.key),
})),
)
.concat(
selectedPage === "inquiry" && inquiryRuntime
? inquiryRuntime.fields.map((field) => ({
key: `inquiry-field:${field.key}`,
label: field.label,
page: "inquiry",
source: "inquiry" as const,
}))
: [],
),
[templateContent, selectedPage, recordSections, inquiryRuntime],
);
const activeTarget = selection?.targetKey;
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget); const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
const editableSections = filterSectionsForPreviewTarget(visibleSections, selectedTarget?.key); const selectedSection = [...(templateContent?.admin.sections ?? []), ...recordSections].find(
const handleTargetSelected = useCallback((key: string) => setActiveTarget(key), []); (section) =>
section.page === selectedPage &&
section.previewTargets?.some((target) => target.key === selectedTarget?.key),
);
const selectedRecordSource =
selectedTarget?.source === "offering" || selectedTarget?.source === "trust"
? selectedTarget.source
: undefined;
const offeringsQuery = useQuery({
queryKey: ["admin-offerings"],
queryFn: () => createApiClient().listAdminOfferings(),
enabled: selectedRecordSource === "offering",
});
const trustQuery = useQuery({
queryKey: ["trust-content"],
queryFn: () => createApiClient().listAdminTrustContent(),
enabled: selectedRecordSource === "trust",
});
const selectedRecord =
selectedRecordSource === "offering"
? offeringsQuery.data?.find((item) => item.id === selection?.recordId)
: selectedRecordSource === "trust"
? trustQuery.data?.find((item) => item.id === selection?.recordId)
: undefined;
const editableSections = filterSectionsForPreviewTarget(
visibleSections.filter((section) =>
section.fields.some((field) => field.binding.startsWith("brand.")),
),
selectedTarget?.key,
);
const recordSection = useMemo(
() =>
selectedSection && selection?.targetKey
? {
...selectedSection,
fields: selectedSection.fields.filter(
(field) => field.previewTarget === selection.targetKey,
),
}
: undefined,
[selectedSection, selection?.targetKey],
);
const handleTargetSelected = useCallback(
(next?: PreviewSelection) => {
const select = () =>
setSelection(
next
? resolvePreviewSelection(
next.targetKey,
next.recordId,
visibleTargets,
selectedPage ?? "home",
)
: undefined,
);
if (recordDraft || inquiryDraft)
guardDraft(() => {
setInquiryDraft(undefined);
setRecordDraft(undefined);
select();
});
else select();
},
[visibleTargets, selectedPage, recordDraft, inquiryDraft, guardDraft],
);
const relatedTargets = [ const relatedTargets = [
...(templateContent?.admin.sections ?? []) ...(templateContent?.admin.sections ?? [])
.filter((section) => section.page === selectedPage && section.target !== "brand") .filter((section) => section.page === selectedPage && section.target !== "brand")
@@ -180,6 +360,12 @@ export function PresentationEditor({
}, },
], ],
); );
const relevantPageLinks = selectedSection
? pageLinks.filter((item) => {
if (item.target.startsWith("trust:")) return selectedSection.target === "trust";
return item.target === selectedSection.target;
})
: pageLinks;
const initialValues = useMemo(() => { const initialValues = useMemo(() => {
const values: PresentationValues = {}; const values: PresentationValues = {};
for (const section of sections) { for (const section of sections) {
@@ -188,6 +374,7 @@ export function PresentationEditor({
config, config,
field.binding, field.binding,
field, field,
brand as unknown as Record<string, unknown>,
); );
} }
} }
@@ -197,13 +384,18 @@ export function PresentationEditor({
const save = useMutation({ const save = useMutation({
mutationFn: (values: PresentationValues) => { mutationFn: (values: PresentationValues) => {
const nextConfig = applyPresentationValues(config, sections, values); const nextConfig = applyPresentationValues(config, sections, values);
return createApiClient().updateAdminBrand({ config: nextConfig }); return createApiClient().updateAdminBrand({
config: nextConfig,
...applyStandardBrandValues(brand as unknown as Record<string, unknown>, sections, values),
});
}, },
onSuccess: () => { onSuccess: () => {
setBrandDirty(false);
message.success("页面内容已保存为草稿,发布后小程序才会更新"); message.success("页面内容已保存为草稿,发布后小程序才会更新");
window.dispatchEvent(new Event("template-preview-refresh")); window.dispatchEvent(new Event("template-preview-refresh"));
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] }); void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] }); void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["publication-readiness"] }); void queryClient.invalidateQueries({ queryKey: ["publication-readiness"] });
}, },
@@ -217,18 +409,155 @@ export function PresentationEditor({
if (!pageOptions.some((item) => item.value === activePage)) if (!pageOptions.some((item) => item.value === activePage))
setActivePage(pageOptions[0]?.value); setActivePage(pageOptions[0]?.value);
}, [activePage, pageOptions]); }, [activePage, pageOptions]);
useEffect(() => setActiveTarget(undefined), [selectedPage]); useEffect(() => setSelection(undefined), [selectedPage, templateContent?.displayName]);
useEffect(() => {
if (!selection?.recordId) return;
const records =
selectedTarget?.source === "trust"
? previewWorkspace?.trustItems
: previewWorkspace?.offerings;
if (records && !records.some((item) => item.id === selection.recordId)) setSelection(undefined);
}, [
previewWorkspace?.offerings,
previewWorkspace?.trustItems,
selectedTarget?.source,
selection,
]);
useEffect(
() => setRecordDraft(undefined),
[selection?.targetKey, selection?.recordId, selectedPage],
);
useEffect(() => {
setPreviewConfig(config ?? {});
setPreviewBrandValues({});
}, [config]);
const previewBrand = useMemo(
() => ({ ...brand, ...previewBrandValues, config: previewConfig }),
[brand, previewBrandValues, previewConfig],
);
const handleValuesChange = useCallback(
(_changed: PresentationValues, allValues: PresentationValues) => {
setBrandDirty(true);
const next = applyBrandPreviewValues(
brand as unknown as Record<string, unknown>,
config,
sections,
allValues,
);
setPreviewConfig((next.config as Record<string, unknown>) ?? {});
setPreviewBrandValues(next);
},
[brand, config, sections],
);
const draftWorkspace = useMemo(() => {
if (!previewWorkspace) return undefined;
const next: RuntimeWorkspace = {
...previewWorkspace,
inquiryForms: previewWorkspace.inquiryForms.map((item) =>
item.key === inquiryRuntime?.key && inquiryDraft ? { ...item, fields: inquiryDraft } : item,
),
brand: projectBrandAliases(
{
...previewWorkspace.brand,
...(previewBrand as unknown as Record<string, unknown>),
config: previewConfig,
},
previewConfig,
),
};
if (!recordDraft || !selectedRecord || !recordSection || recordDraft.id !== selectedRecord.id)
return next;
const values = recordDraft.values;
const config = applyPresentationValues(selectedRecord.config, [recordSection], values);
const standard = applyStandardEntityValues(
selectedRecord as unknown as Record<string, unknown>,
recordDraft.source,
[recordSection],
values,
);
if (recordDraft.source === "trust") {
next.trustItems = next.trustItems.map((item) =>
item.id === recordDraft.id
? {
...item,
title: typeof standard.title === "string" ? standard.title : item.title,
summary: typeof standard.summary === "string" ? standard.summary : item.summary,
content: typeof standard.content === "string" ? standard.content : item.content,
config,
}
: item,
);
next.trustPresentation = projectTrustPresentation(
next.trustItems,
templateContent?.trustContentTypes ?? [],
);
} else {
next.offerings = next.offerings.map((item) =>
item.id === recordDraft.id
? {
...item,
name: typeof standard.name === "string" ? standard.name : item.name,
summary:
typeof standard.summary === "string"
? standard.summary
: typeof standard.description === "string"
? standard.description
: item.summary,
priceText: typeof standard.priceText === "string" ? standard.priceText : null,
coverUrl: typeof standard.coverUrl === "string" ? standard.coverUrl : null,
presentation: {
...item.presentation,
...config,
...(config.presentation && typeof config.presentation === "object"
? (config.presentation as Record<string, unknown>)
: {}),
heroImage:
typeof config.detailHero === "string"
? config.detailHero
: typeof standard.coverUrl === "string"
? standard.coverUrl
: null,
details: {
...item.presentation.details,
...(config.details && typeof config.details === "object"
? (config.details as Record<string, unknown>)
: {}),
},
},
}
: item,
);
}
return next;
}, [
previewWorkspace,
previewBrand,
previewConfig,
recordDraft,
selectedRecord,
recordSection,
templateContent,
inquiryDraft,
inquiryRuntime,
]);
const selectedDetailOfferingId =
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
? detailOfferingId
: draftWorkspace?.offerings[0]?.id;
return ( return (
<Card <section className="presentation-editor" aria-labelledby="presentation-editor-title">
title="小程序页面配置" <div className="presentation-editor__header">
extra={templateContent ? <Tag color="blue">{templateContent.displayName}</Tag> : null} <div>
style={{ marginTop: 32 }} <Typography.Title id="presentation-editor-title" level={3}>
styles={{ body: { minHeight: breakpoints.md ? 760 : 620 } }} 小程序页面配置
> </Typography.Title>
<Typography.Paragraph type="secondary"> <Typography.Paragraph type="secondary">
按小程序页面查找内容。这里修改的是草稿,发布后访客才会看到更新。 按页面查找内容。这里修改的是草稿,发布后访客才会看到更新。
</Typography.Paragraph> </Typography.Paragraph>
</div>
{templateContent ? <Tag color="blue">{templateContent.displayName}</Tag> : null}
</div>
{loading ? <Alert type="info" showIcon message="正在读取当前模板的编辑项目" /> : null} {loading ? <Alert type="info" showIcon message="正在读取当前模板的编辑项目" /> : null}
{error ? ( {error ? (
<Alert type="warning" showIcon message="模板编辑项目读取失败,请刷新后重试。" /> <Alert type="warning" showIcon message="模板编辑项目读取失败,请刷新后重试。" />
@@ -238,57 +567,261 @@ export function PresentationEditor({
) : null} ) : null}
{templateContent ? ( {templateContent ? (
<> <>
<Space wrap style={{ marginBottom: 24 }}> <Space className="presentation-editor__navigation" wrap>
{breakpoints.xs ? ( {breakpoints.xs ? (
<Select <Select
aria-label="选择小程序页面" aria-label="选择小程序页面"
value={selectedPage} value={selectedPage}
options={pageOptions} options={pageOptions}
onChange={setActivePage} onChange={(value) =>
guardDraft(() => {
setBrandDirty(false);
form.setFieldsValue(initialValues);
setPreviewConfig(config ?? {});
setPreviewBrandValues({});
setRecordDraft(undefined);
setInquiryDraft(undefined);
setActivePage(value);
})
}
style={{ minWidth: 180 }} style={{ minWidth: 180 }}
/> />
) : ( ) : (
<Segmented <Segmented
value={selectedPage} value={selectedPage}
options={pageOptions} options={pageOptions}
onChange={(value) => setActivePage(String(value))} onChange={(value) =>
guardDraft(() => {
setBrandDirty(false);
form.setFieldsValue(initialValues);
setPreviewConfig(config ?? {});
setPreviewBrandValues({});
setRecordDraft(undefined);
setInquiryDraft(undefined);
setActivePage(String(value));
})
}
/> />
)} )}
</Space> </Space>
<Row gutter={[24, 24]} align="top"> <div className="presentation-editor__workspace">
<Col xs={24} xl={12}> <div className="presentation-editor__preview">
<Typography.Title level={5}>页面预览</Typography.Title> <Typography.Title level={5}>页面预览</Typography.Title>
{selectedPage === "detail" && draftWorkspace?.offerings.length ? (
<Select
aria-label="选择详情页业务内容"
style={{ width: "100%", marginBottom: 12 }}
value={selectedDetailOfferingId}
options={draftWorkspace.offerings.map((item) => ({
value: item.id,
label: item.name,
}))}
onChange={(value) => {
setDetailOfferingId(value);
setSelection(undefined);
}}
/>
) : null}
<TemplatePreview <TemplatePreview
brand={brand} brand={previewBrand}
{...(draftWorkspace ? { workspace: draftWorkspace } : {})}
page={selectedPage ?? "home"} page={selectedPage ?? "home"}
route={`/pages/${encodeURIComponent(selectedPage ?? "home")}/index`} {...(selectedPage === "detail" && selectedDetailOfferingId
? { offeringId: selectedDetailOfferingId }
: {})}
{...(activeTarget ? { targetKey: activeTarget } : {})} {...(activeTarget ? { targetKey: activeTarget } : {})}
{...(selection ? { selection } : {})}
targets={visibleTargets}
onTargetSelected={handleTargetSelected} onTargetSelected={handleTargetSelected}
/> />
</div>
<aside className="presentation-editor__outline" aria-label="页面区域">
<Typography.Title level={5}>页面区域</Typography.Title>
<Typography.Paragraph type="secondary">选择区域,编辑对应内容</Typography.Paragraph>
{visibleTargets.length ? ( {visibleTargets.length ? (
<Space wrap style={{ marginTop: 16 }}> <Space className="presentation-editor__regions" wrap style={{ marginTop: 16 }}>
{visibleTargets.map((target) => ( {visibleTargets.map((target) => (
<Button <Button
key={target.key} key={target.key}
className={
visibleTargets.some((parent) => parent.children?.includes(target.key))
? "is-child-region"
: ""
}
aria-pressed={activeTarget === target.key}
type={activeTarget === target.key ? "primary" : "default"} type={activeTarget === target.key ? "primary" : "default"}
onClick={() => setActiveTarget(target.key)} onClick={() => {
const recordId =
target.source === "offering"
? selectedPage === "detail"
? selectedDetailOfferingId
: draftWorkspace?.offerings[0]?.id
: target.source === "trust"
? draftWorkspace?.trustItems.find(
(item) => target.key === `trust:${item.type}`,
)?.id
: undefined;
handleTargetSelected({
targetKey: target.key,
...(recordId ? { recordId } : {}),
});
}}
> >
{target.label} {target.label}
</Button> </Button>
))} ))}
</Space> </Space>
) : null} ) : null}
</Col> {!visibleTargets.length ? (
<Col xs={24} xl={12}> <Typography.Text type="secondary">此页为动态预览</Typography.Text>
) : null}
</aside>
<div className="presentation-editor__inspector">
<Typography.Title level={5}> <Typography.Title level={5}>
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")} {selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
</Typography.Title> </Typography.Title>
<Tag color={brandDirty || recordDraft || inquiryDraft ? "orange" : "default"}>
{save.isPending
? "正在保存"
: save.isError
? "保存失败,请重试"
: brandDirty || recordDraft || inquiryDraft
? "有未保存修改"
: "草稿已同步"}
</Tag>
{selectedPage === "detail" ? (
<Alert
type="info"
showIcon
message="详情页由所选业务内容动态生成"
description="选择不同的业务内容即可预览对应详情;内容请在业务提供项中维护。"
/>
) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? (
<InquiryPreviewEditor
runtime={
draftWorkspace?.inquiryForms.find((item) => item.key === inquiryRuntime.key) ??
inquiryRuntime
}
fieldKey={activeTarget.slice("inquiry-field:".length)}
onDraft={setInquiryDraft}
onSaved={() => setInquiryDraft(undefined)}
/>
) : selectedTarget?.composite ? (
<Alert
type="info"
showIcon
message="这是一个组合区域"
description={
<Space wrap>
{(selectedTarget.children ?? []).map((childKey) => {
const child = visibleTargets.find((item) => item.key === childKey);
if (!child) return null;
return (
<Button
key={child.key}
onClick={() => {
const recordId =
child.source === "offering"
? selectedPage === "detail"
? selectedDetailOfferingId
: draftWorkspace?.offerings[0]?.id
: child.source === "trust"
? draftWorkspace?.trustItems.find(
(item) => child.key === `trust:${item.type}`,
)?.id
: undefined;
handleTargetSelected({
targetKey: child.key,
...(recordId ? { recordId } : {}),
});
}}
>
编辑{child.label}
</Button>
);
})}
</Space>
}
/>
) : selectedRecordSource && selection?.recordId && selectedSection ? (
selectedRecord ? (
<RecordEditor
key={`${selectedRecordSource}:${selectedRecord.id}:${selectedSection.key}`}
source={selectedRecordSource}
record={selectedRecord}
section={recordSection!}
onDraft={(values) =>
setRecordDraft({
source: selectedRecordSource,
id: selectedRecord.id,
values,
})
}
onSaved={() => setRecordDraft(undefined)}
/>
) : (
<Alert
type={
(
selectedRecordSource === "offering"
? offeringsQuery.isError
: trustQuery.isError
)
? "error"
: "info"
}
message={
(
selectedRecordSource === "offering"
? offeringsQuery.isError
: trustQuery.isError
)
? "内容读取失败"
: (
selectedRecordSource === "offering"
? offeringsQuery.isSuccess
: trustQuery.isSuccess
)
? "对应内容已不存在,请重新选择页面中的区域"
: "正在读取对应内容"
}
{...((
selectedRecordSource === "offering"
? offeringsQuery.isError
: trustQuery.isError
)
? {
action: (
<Button
size="small"
onClick={() => {
if (selectedRecordSource === "offering")
void offeringsQuery.refetch();
else void trustQuery.refetch();
}}
>
重试
</Button>
),
}
: {})}
/>
)
) : !selectedTarget ? (
<div className="presentation-editor__empty">
<Typography.Title level={5}>选择要编辑的区域</Typography.Title>
<Typography.Paragraph type="secondary">
点击预览中的内容,或使用区域列表,查看并修改对应字段。
</Typography.Paragraph>
</div>
) : (
<Form <Form
form={form} form={form}
layout="vertical" layout="vertical"
initialValues={initialValues} initialValues={initialValues}
onValuesChange={handleValuesChange}
onFinish={(values) => save.mutate(values)} onFinish={(values) => save.mutate(values)}
style={{ minHeight: 540, display: "flex", flexDirection: "column" }} style={{ minHeight: 0, display: "flex", flexDirection: "column" }}
> >
<div style={{ flex: 1 }}> <div style={{ flex: 1 }}>
{editableSections.map((section, index) => ( {editableSections.map((section, index) => (
@@ -306,11 +839,7 @@ export function PresentationEditor({
) : null} ) : null}
<Row gutter={16}> <Row gutter={16}>
{section.fields.map((field) => ( {section.fields.map((field) => (
<Col <Col key={field.key} xs={24} md={24}>
key={field.key}
xs={24}
md={field.input === "textarea" || field.input === "list" ? 24 : 12}
>
{field.input === "list" ? ( {field.input === "list" ? (
<TemplateListField <TemplateListField
field={field} field={field}
@@ -322,7 +851,11 @@ export function PresentationEditor({
label={field.label} label={field.label}
{...(field.help ? { help: field.help } : {})} {...(field.help ? { help: field.help } : {})}
{...(field.required {...(field.required
? { rules: [{ required: true, message: `请填写${field.label}` }] } ? {
rules: [
{ required: true, message: `请填写${field.label}` },
],
}
: {})} : {})}
> >
{renderField(field)} {renderField(field)}
@@ -333,7 +866,7 @@ export function PresentationEditor({
</Row> </Row>
</section> </section>
))} ))}
{pageLinks.length ? ( {relevantPageLinks.length ? (
<Alert <Alert
type="info" type="info"
showIcon showIcon
@@ -341,7 +874,7 @@ export function PresentationEditor({
message="这个页面还有关联内容" message="这个页面还有关联内容"
description={ description={
<Space wrap> <Space wrap>
{pageLinks.map((item) => ( {relevantPageLinks.map((item) => (
<Button <Button
key={item.target} key={item.target}
type="link" type="link"
@@ -367,11 +900,19 @@ export function PresentationEditor({
} }
/> />
) : null} ) : null}
{!editableSections.length && !pageLinks.length ? ( {!editableSections.some((section) => section.fields.length) &&
!relevantPageLinks.length ? (
<Typography.Paragraph type="secondary"> <Typography.Paragraph type="secondary">
这个页面没有单独的品牌文案配置。 这个页面没有单独的品牌文案配置。
</Typography.Paragraph> </Typography.Paragraph>
) : null} ) : null}
{selectedTarget &&
!editableSections.some((section) => section.fields.length) &&
relevantPageLinks.length ? (
<Typography.Paragraph type="secondary">
此区域内容由对应的业务管理页面维护。
</Typography.Paragraph>
) : null}
</div> </div>
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}> <Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
<MutationError error={save.error} /> <MutationError error={save.error} />
@@ -380,11 +921,119 @@ export function PresentationEditor({
</Button> </Button>
</Space> </Space>
</Form> </Form>
</Col> )}
</Row> </div>
</div>
</> </>
) : null} ) : null}
</Card> </section>
);
}
function RecordEditor({
source,
record,
section,
onDraft,
onSaved,
}: {
source: "offering" | "trust";
record: Offering | TrustContent;
section: TemplateAdminSection;
onDraft: (values: PresentationValues) => void;
onSaved: () => void;
}) {
const [form] = Form.useForm<PresentationValues>();
const queryClient = useQueryClient();
const initialValues = useMemo(
() =>
Object.fromEntries(
section.fields.map((field) => [
presentationFieldName(section.key, field.key),
readPresentationValue(
record.config,
field.binding,
field,
record as unknown as Record<string, unknown>,
),
]),
),
[record, section],
);
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
const save = useMutation({
mutationFn: async (values: PresentationValues): Promise<void> => {
const config = applyPresentationValues(record.config, [section], values);
const standard = applyStandardEntityValues(
record as unknown as Record<string, unknown>,
source,
[section],
values,
);
const changed = Object.fromEntries(
Object.entries(standard).filter(
([key, value]) =>
key !== "config" && value !== (record as unknown as Record<string, unknown>)[key],
),
);
const client = createApiClient();
if (source === "offering")
await client.updateAdminOffering(record.id, { ...changed, config });
else await client.updateAdminTrustContent(record.id, { ...changed, config });
},
onSuccess: () => {
message.success("内容已保存为草稿,发布后访客才会看到更新");
onSaved();
void queryClient.invalidateQueries({
queryKey: [source === "offering" ? "admin-offerings" : "trust-content"],
});
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
},
});
return (
<Form
form={form}
layout="vertical"
initialValues={initialValues}
onValuesChange={(_, values) => onDraft(values)}
onFinish={(values) => save.mutate(values)}
style={{ minHeight: 0, display: "flex", flexDirection: "column" }}
>
{save.isPending ? <Typography.Text type="secondary">正在保存内容…</Typography.Text> : null}
<Typography.Paragraph type="secondary">{section.description}</Typography.Paragraph>
<div style={{ flex: 1 }}>
<Row gutter={16}>
{section.fields.map((field) => (
<Col key={field.key} xs={24} md={24}>
{field.input === "list" ? (
<TemplateListField
field={field}
name={presentationFieldName(section.key, field.key)}
/>
) : (
<Form.Item
name={presentationFieldName(section.key, field.key)}
label={field.label}
{...(field.help ? { help: field.help } : {})}
{...(field.required
? { rules: [{ required: true, message: `请填写${field.label}` }] }
: {})}
>
{renderField(field)}
</Form.Item>
)}
</Col>
))}
</Row>
</div>
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
<MutationError error={save.error} />
<Button type="primary" htmlType="submit" loading={save.isPending}>
保存此项内容
</Button>
</Space>
</Form>
); );
} }
@@ -4,42 +4,51 @@ import type {
BrandProfile, BrandProfile,
EditorPreviewFrameMessage, EditorPreviewFrameMessage,
EditorPreviewHostMessage, EditorPreviewHostMessage,
RuntimeWorkspace,
} from "@personal-brand/api-client"; } from "@personal-brand/api-client";
import { templatePreviewUrl } from "../../lib/template-preview.js"; import { templatePreviewUrl } from "../../lib/template-preview.js";
import { ComponentTemplatePreview } from "./ComponentTemplatePreview.js";
import { resolveTemplateRenderer } from "./component-renderers.jsx";
import type { PreviewSelection, PreviewTarget } from "./preview-selection.js";
import "./TemplatePreview.css"; import "./TemplatePreview.css";
export function TemplatePreview({ export function TemplatePreview({
brand, brand,
workspace,
page, page,
offeringId,
targetKey, targetKey,
route, selection,
targets,
onTargetSelected, onTargetSelected,
}: { }: {
brand: BrandProfile; brand: BrandProfile;
workspace?: RuntimeWorkspace;
page: string; page: string;
offeringId?: string;
targetKey?: string; targetKey?: string;
route: string; selection?: PreviewSelection;
onTargetSelected: (key: string) => void; targets: PreviewTarget[];
onTargetSelected: (selection?: PreviewSelection) => void;
}) { }) {
const frame = useRef<HTMLIFrameElement>(null); const frame = useRef<HTMLIFrameElement>(null);
const useComponent = Boolean(workspace && resolveTemplateRenderer(workspace));
const [ready, setReady] = useState(false); const [ready, setReady] = useState(false);
const [error, setError] = useState(""); const [error, setError] = useState("");
const [reloadKey, setReloadKey] = useState(0); const [reloadKey, setReloadKey] = useState(0);
const config = brand.config ?? {}; const url = useMemo(() => {
const templateKey = const value = templatePreviewUrl(
typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : brand.templateKey;
const url = useMemo(
() =>
templatePreviewUrl(
templateKey,
brand.slug, brand.slug,
page, page,
import.meta.env.VITE_TEMPLATE_PREVIEW_URLS, import.meta.env.VITE_TEMPLATE_PREVIEW_URL || "/template-preview/index.html",
window.location.origin, window.location.origin,
route, `/pages/${encodeURIComponent(page)}/index`,
),
[brand.slug, page, reloadKey, route, templateKey],
); );
if (!value) return undefined;
const preview = new URL(value);
preview.searchParams.set("refresh", String(reloadKey));
return preview.toString();
}, [brand.slug, page, reloadKey]);
const origin = useMemo(() => (url ? new URL(url).origin : ""), [url]); const origin = useMemo(() => (url ? new URL(url).origin : ""), [url]);
const brandDraft = useMemo( const brandDraft = useMemo(
() => ({ () => ({
@@ -70,7 +79,7 @@ export function TemplatePreview({
if (message?.protocol !== "personal-brand-editor-preview" || message.version !== 1) return; if (message?.protocol !== "personal-brand-editor-preview" || message.version !== 1) return;
if (message.type === "ready") setReady(true); if (message.type === "ready") setReady(true);
if (message.type === "targetSelected" && message.page === page) if (message.type === "targetSelected" && message.page === page)
onTargetSelected(message.targetKey); onTargetSelected({ targetKey: message.targetKey });
}; };
window.addEventListener("message", onMessage); window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage); return () => window.removeEventListener("message", onMessage);
@@ -80,12 +89,21 @@ export function TemplatePreview({
if (!ready || !frame.current?.contentWindow || !origin) return; if (!ready || !frame.current?.contentWindow || !origin) return;
const send = (message: EditorPreviewHostMessage) => const send = (message: EditorPreviewHostMessage) =>
frame.current?.contentWindow?.postMessage(message, origin); frame.current?.contentWindow?.postMessage(message, origin);
if (workspace) {
send({
protocol: "personal-brand-editor-preview",
version: 1,
type: "workspaceDraft",
workspace,
});
} else {
send({ send({
protocol: "personal-brand-editor-preview", protocol: "personal-brand-editor-preview",
version: 1, version: 1,
type: "brandDraft", type: "brandDraft",
brand: brandDraft, brand: brandDraft,
}); });
}
if (targetKey) if (targetKey)
send({ send({
protocol: "personal-brand-editor-preview", protocol: "personal-brand-editor-preview",
@@ -93,7 +111,7 @@ export function TemplatePreview({
type: "focusTarget", type: "focusTarget",
targetKey, targetKey,
}); });
}, [brandDraft, origin, ready, targetKey]); }, [brandDraft, origin, ready, targetKey, workspace]);
useEffect(() => { useEffect(() => {
const refresh = () => setReloadKey((value) => value + 1); const refresh = () => setReloadKey((value) => value + 1);
@@ -101,18 +119,31 @@ export function TemplatePreview({
return () => window.removeEventListener("template-preview-refresh", refresh); return () => window.removeEventListener("template-preview-refresh", refresh);
}, []); }, []);
if (!url) if (!useComponent && !url)
return ( return (
<Alert <Alert
type="warning" type="warning"
showIcon showIcon
message="尚未配置模板预览服务" message="页面预览暂不可用"
description="请在 Admin 环境变量 VITE_TEMPLATE_PREVIEW_URLS 中为模板配置 H5 预览地址。" description="请确认模板预览资源已构建并发布,或本地预览服务正在运行。"
/> />
); );
return ( return (
<div className="template-preview"> <div className="template-preview">
{workspace && useComponent ? (
<ComponentTemplatePreview
workspace={workspace}
page={page}
{...(offeringId ? { offeringId } : {})}
{...(targetKey ? { targetKey } : {})}
{...(selection ? { selection } : {})}
targets={targets}
onTargetSelected={onTargetSelected}
/>
) : null}
{!useComponent ? (
<>
{!ready && !error ? ( {!ready && !error ? (
<div className="template-preview__loading"> <div className="template-preview__loading">
<Spin tip="正在加载页面预览" /> <Spin tip="正在加载页面预览" />
@@ -130,6 +161,8 @@ export function TemplatePreview({
onError={() => setError("请检查预览服务地址和网络连接。")} onError={() => setError("请检查预览服务地址和网络连接。")}
style={{ opacity: ready ? 1 : 0 }} style={{ opacity: ready ? 1 : 0 }}
/> />
</>
) : null}
</div> </div>
); );
} }
+10
View File
@@ -0,0 +1,10 @@
import type { ComponentType } from "react";
import type { RuntimeWorkspace } from "@personal-brand/api-client";
declare module "./component-renderers.jsx" {
export function resolveTemplateRenderer(workspace: RuntimeWorkspace): ComponentType<{
workspace: RuntimeWorkspace;
page: string;
offeringId?: string;
}> | null;
}
@@ -0,0 +1,40 @@
import { TemplatePage as FoodTemplatePage } from "../../../../../packages/template-acheng-campus-food/taro/index.tsx";
import { TemplatePage as EditorialTemplatePage } from "../../../../../packages/template-linjing-editorial/taro/index.tsx";
import React from "react";
import { Inquiry } from "../../../../taro/src/components/Inquiry.tsx";
import { Records } from "../../../../taro/src/components/Records.tsx";
import { Success } from "../../../../taro/src/components/Success.tsx";
import { TemplateAssetContext } from "./taro-web-components.jsx";
function pageContent({ workspace, page }) {
if (page === "inquiry") return <Inquiry workspace={workspace} preview />;
if (page === "records") return <Records workspace={workspace} preview />;
if (page === "success") return <Success workspace={workspace} preview />;
return null;
}
function FoodPreview(props) {
return (
<TemplateAssetContext.Provider value="acheng-campus-food">
<FoodTemplatePage {...props}>{pageContent(props)}</FoodTemplatePage>
</TemplateAssetContext.Provider>
);
}
function EditorialPreview(props) {
return (
<TemplateAssetContext.Provider value="linjing-editorial">
<EditorialTemplatePage {...props}>{pageContent(props)}</EditorialTemplatePage>
</TemplateAssetContext.Provider>
);
}
export function resolveTemplateRenderer(workspace) {
const config = workspace?.brand?.config;
const key =
config && typeof config === "object" && !Array.isArray(config)
? config.visualTemplateKey
: undefined;
if (key === "acheng-campus-food") return FoodPreview;
if (key === "linjing-editorial") return EditorialPreview;
return null;
}
@@ -31,11 +31,14 @@ function asObject(value: unknown): Record<string, unknown> {
} }
function safePath(binding: string): string[] | null { function safePath(binding: string): string[] | null {
const prefix = ["brand.config.", "offering.config.", "trust.config."].find((candidate) => const prefixes = ["brand.config.", "offering.config.", "trust.config."];
binding.startsWith(candidate), 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(
binding,
); );
if (!prefix) return null; if (!prefix && !standardField) return null;
const path = binding.slice(prefix.length).split("."); const path = prefix ? binding.slice(prefix.length).split(".") : [binding.split(".")[1] ?? ""];
if (path.some((part) => !part || ["__proto__", "prototype", "constructor"].includes(part))) if (path.some((part) => !part || ["__proto__", "prototype", "constructor"].includes(part)))
return null; return null;
return path; return path;
@@ -49,10 +52,15 @@ export function readPresentationValue(
config: Record<string, unknown> | null | undefined, config: Record<string, unknown> | null | undefined,
binding: string, binding: string,
field?: PresentationField, field?: PresentationField,
brand?: Record<string, unknown>,
): unknown { ): unknown {
const path = safePath(binding); const path = safePath(binding);
if (!path) return undefined; if (!path) return undefined;
let value: unknown = asObject(config); const isConfigBinding =
binding.startsWith("brand.config.") ||
binding.startsWith("offering.config.") ||
binding.startsWith("trust.config.");
let value: unknown = isConfigBinding ? asObject(config) : asObject(brand);
for (const part of path) value = asObject(value)[part]; for (const part of path) value = asObject(value)[part];
if (field?.input === "list") { if (field?.input === "list") {
if (!Array.isArray(value)) return []; if (!Array.isArray(value)) return [];
@@ -88,6 +96,7 @@ export function applyPresentationValues(
let nextConfig = { ...asObject(config) }; let nextConfig = { ...asObject(config) };
for (const section of sections) { for (const section of sections) {
for (const field of section.fields) { for (const field of section.fields) {
if (!field.binding.includes(".config.")) continue;
const path = safePath(field.binding); const path = safePath(field.binding);
if (!path) continue; if (!path) continue;
const raw = values[presentationFieldName(section.key, field.key)]; const raw = values[presentationFieldName(section.key, field.key)];
@@ -104,3 +113,51 @@ export function applyPresentationValues(
} }
return nextConfig; return nextConfig;
} }
export function applyStandardBrandValues(
brand: Record<string, unknown>,
sections: PresentationSection[],
values: PresentationValues,
): Record<string, unknown> {
const next = { ...brand };
for (const section of sections) {
for (const field of section.fields) {
if (!field.binding.startsWith("brand.") || field.binding.startsWith("brand.config."))
continue;
const value = values[presentationFieldName(section.key, field.key)];
if (value !== undefined) next[field.binding.slice("brand.".length)] = value;
}
}
return next;
}
export function applyStandardEntityValues(
entity: Record<string, unknown>,
entityType: "offering" | "trust",
sections: PresentationSection[],
values: PresentationValues,
): Record<string, unknown> {
const next = { ...entity };
for (const section of sections) {
for (const field of section.fields) {
if (!field.binding.startsWith(`${entityType}.`) || field.binding.includes(".config."))
continue;
const value = values[presentationFieldName(section.key, field.key)];
if (value !== undefined) next[field.binding.slice(entityType.length + 1)] = value;
}
}
return next;
}
export function applyBrandPreviewValues(
brand: Record<string, unknown>,
config: Record<string, unknown> | null | undefined,
sections: PresentationSection[],
values: PresentationValues,
): Record<string, unknown> {
const nextBrand = applyStandardBrandValues(brand, sections, values);
return {
...nextBrand,
config: applyPresentationValues(config, sections, values),
};
}
@@ -0,0 +1,23 @@
export type PreviewSelection = { targetKey: string; recordId?: string };
export type PreviewTarget = {
key: string;
label: string;
source: "brand" | "offering" | "trust" | "inquiry";
page: string;
composite?: boolean;
children?: string[];
};
export function resolvePreviewSelection(
targetKey: string,
recordId: string | undefined,
targets: PreviewTarget[],
page: string,
): PreviewSelection | undefined {
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 };
}
@@ -0,0 +1,108 @@
import React from "react";
export const TemplateAssetContext = React.createContext("");
const templateAssets = import.meta.glob("../../../../../packages/template-*/miniapp/assets/**/*", {
eager: true,
query: "?url",
import: "default",
});
function resolveImageSource(src, templateKey) {
if (typeof src !== "string" || !src.startsWith("/assets/")) return src;
const relative = src.slice("/assets/".length);
for (const [file, url] of Object.entries(templateAssets)) {
const parts = file.split("/packages/template-")[1]?.split("/miniapp/assets/");
if (!parts) continue;
const [key, asset] = parts;
if (relative === key + "/" + asset || (key === templateKey && relative === asset)) return url;
}
return src;
}
const element = (tag) =>
React.forwardRef(({ children, className, style, onClick, ...props }, ref) =>
React.createElement(tag, { ...props, ref, className, style, onClick }, children),
);
export const View = element("div");
export const Text = element("span");
export const Button = element("button");
export const Input = React.forwardRef(({ onInput, ...props }, ref) =>
React.createElement("input", {
...props,
ref,
onInput: (event) => onInput?.({ detail: { value: event.currentTarget.value } }),
}),
);
export const Textarea = React.forwardRef(({ onInput, maxlength, ...props }, ref) =>
React.createElement("textarea", {
...props,
ref,
maxLength: maxlength,
onInput: (event) => onInput?.({ detail: { value: event.currentTarget.value } }),
}),
);
export function Picker({ children, mode, range = [], value, onChange }) {
return (
<div style={{ position: "relative" }}>
{children}
{mode === "date" ? (
<input
aria-label="选择日期"
type="date"
value={value || ""}
onChange={(event) => onChange?.({ detail: { value: event.currentTarget.value } })}
style={{ position: "absolute", inset: 0, width: "100%", opacity: 0, cursor: "pointer" }}
/>
) : (
<select
aria-label="选择选项"
value={value ?? 0}
onChange={(event) => onChange?.({ detail: { value: event.currentTarget.value } })}
style={{ position: "absolute", inset: 0, width: "100%", opacity: 0, cursor: "pointer" }}
>
{range.map((label, index) => (
<option key={index} value={index}>
{label}
</option>
))}
</select>
)}
</div>
);
}
const CheckboxContext = React.createContext(null);
export function CheckboxGroup({ children, onChange }) {
const [selected, setSelected] = React.useState([]);
const update = (value, checked) => {
const next = checked ? [...selected, value] : selected.filter((item) => item !== value);
setSelected(next);
onChange?.({ detail: { value: next } });
};
return (
<CheckboxContext.Provider value={update}>
<div>{children}</div>
</CheckboxContext.Provider>
);
}
export function Checkbox({ value, checked }) {
const update = React.useContext(CheckboxContext);
return (
<input
type="checkbox"
value={value}
checked={Boolean(checked)}
onChange={(event) => update?.(value, event.currentTarget.checked)}
/>
);
}
export const Label = element("label");
export const Image = React.forwardRef(({ mode, src, style, ...props }, ref) => {
const key = React.useContext(TemplateAssetContext);
return React.createElement("img", {
...props,
ref,
src: resolveImageSource(src, key),
style: { objectFit: mode === "aspectFit" ? "contain" : "cover", ...style },
});
});
@@ -0,0 +1,14 @@
import React from "react";
const noop = () => Promise.resolve();
export const useRouter = () => ({ params: {} });
export const useDidShow = (callback) => React.useEffect(callback, []);
const Taro = {
setStorageSync() {},
getStorageSync() {
return undefined;
},
removeStorageSync() {},
switchTab: noop,
navigateTo: noop,
};
export default Taro;
@@ -0,0 +1,51 @@
import { useEffect } from "react";
import { Modal } from "antd";
import { useNavigate } from "react-router-dom";
export function useEditorDraft(dirty: boolean) {
const navigate = useNavigate();
useEffect(() => {
if (!dirty) return;
const beforeUnload = (event: BeforeUnloadEvent) => {
event.preventDefault();
event.returnValue = "";
};
window.addEventListener("beforeunload", beforeUnload);
const leave = (event: MouseEvent) => {
if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey)
return;
const anchor =
event.target instanceof Element ? event.target.closest<HTMLAnchorElement>("a[href]") : null;
if (!anchor || anchor.target === "_blank" || anchor.hasAttribute("download")) return;
const url = new URL(anchor.href, window.location.href);
if (url.origin !== window.location.origin || url.pathname === window.location.pathname)
return;
event.preventDefault();
event.stopImmediatePropagation();
Modal.confirm({
title: "有尚未保存的修改",
content: "离开工作台会丢失未保存内容。请先保存,或确认放弃修改。",
okText: "放弃修改并继续",
cancelText: "继续编辑",
onOk: () => {
void navigate(`${url.pathname}${url.search}${url.hash}`);
},
});
};
document.addEventListener("click", leave, true);
return () => {
window.removeEventListener("beforeunload", beforeUnload);
document.removeEventListener("click", leave, true);
};
}, [dirty, navigate]);
return (action: () => void) => {
if (!dirty) return action();
Modal.confirm({
title: "有尚未保存的修改",
content: "切换后当前内容可能丢失。请先保存,或确认放弃修改。",
okText: "放弃修改并继续",
cancelText: "继续编辑",
onOk: action,
});
};
}
+2 -14
View File
@@ -1,25 +1,13 @@
export function templatePreviewUrl( export function templatePreviewUrl(
templateKey: string,
brandSlug: string | undefined, brandSlug: string | undefined,
page: string, page: string,
configured: string | undefined, configured: string | undefined,
parentOrigin?: string, parentOrigin?: string,
route?: string, route?: string,
): string | undefined { ): string | undefined {
let urls: Record<string, unknown>; const raw = configured || "http://localhost:3002";
try { try {
const parsed: unknown = configured ? JSON.parse(configured) : {}; const url = new URL(raw, parentOrigin);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
return undefined;
}
urls = parsed as Record<string, unknown>;
} catch {
return undefined;
}
const raw = urls[templateKey];
if (typeof raw !== "string" || !raw) return undefined;
try {
const url = new URL(raw);
url.searchParams.set("editor", "1"); url.searchParams.set("editor", "1");
if (parentOrigin) url.searchParams.set("parentOrigin", parentOrigin); if (parentOrigin) url.searchParams.set("parentOrigin", parentOrigin);
if (brandSlug) url.searchParams.set("brand", brandSlug); if (brandSlug) url.searchParams.set("brand", brandSlug);
+3 -1
View File
@@ -1,7 +1,9 @@
interface ImportMetaEnv { interface ImportMetaEnv {
readonly DEV: boolean;
readonly PROD: boolean;
readonly VITE_API_BASE_URL?: string; readonly VITE_API_BASE_URL?: string;
readonly VITE_APP_BASE_PATH?: string; readonly VITE_APP_BASE_PATH?: string;
readonly VITE_TEMPLATE_PREVIEW_URLS?: string; readonly VITE_TEMPLATE_PREVIEW_URL?: string;
} }
interface ImportMeta { interface ImportMeta {
+39
View File
@@ -0,0 +1,39 @@
// 模板 CSS 使用 Taro 的 750 设计宽度,转换到预览容器单位。
export function templatePreviewCss() {
return {
postcssPlugin: "template-preview-css",
Once(root) {
const file = root.source?.input.file || "";
const templateStyle =
file.includes("/packages/template-") && file.endsWith("/taro/style.css");
const sharedFormStyle = file.endsWith("/apps/taro/src/components/forms.css");
if (!templateStyle && !sharedFormStyle) return;
root.walkRules((rule) => {
rule.selector = rule.selector
.split(",")
.map(
(selector) =>
".component-template-preview__canvas " +
selector
.trim()
.replace(
/(^|[ >+~])(image|text|view)(?=[ .#:[>+~)]|$)/g,
(_, prefix, tag) => prefix + { image: "img", text: "span", view: "div" }[tag],
),
)
.join(", ");
});
root.walkDecls((declaration) => {
// 组件预览中的固定按钮必须以页面画布为定位基准。
if (declaration.prop === "position" && declaration.value === "fixed")
declaration.value = "absolute";
// 模板页面的视口高度按手机画布宽度计算,避免引用 Admin 浏览器高度。
declaration.value = declaration.value.replace(/100vh/g, "178cqw");
declaration.value = declaration.value.replace(
/(-?(?:[0-9]*[.])?[0-9]+)px/g,
(_, value) => Number((Number(value) / 7.5).toFixed(8)) + "cqw",
);
});
},
};
}
@@ -1,10 +1,13 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { import {
applyPresentationValues, applyPresentationValues,
applyBrandPreviewValues,
applyStandardEntityValues,
filterSectionsForPreviewTarget, filterSectionsForPreviewTarget,
presentationFieldName, presentationFieldName,
readPresentationValue, readPresentationValue,
} from "../src/features/brand/presentation-bindings.ts"; } from "../src/features/brand/presentation-bindings.ts";
import { resolvePreviewSelection } from "../src/features/brand/preview-selection.ts";
const config = { const config = {
founder: "阿成", founder: "阿成",
@@ -124,3 +127,63 @@ const offering = applyPresentationValues(
{ [presentationFieldName("offering", "background")]: "新背景" }, { [presentationFieldName("offering", "background")]: "新背景" },
); );
assert.deepEqual(offering.details, { background: "新背景", preserve: "保留" }); assert.deepEqual(offering.details, { background: "新背景", preserve: "保留" });
const brandDraft = applyBrandPreviewValues(
{ description: "旧简介", address: "旧地址", config: { visualPresentation: {} } },
{ visualPresentation: {} },
[
{
key: "identity",
fields: [
{ key: "description", binding: "brand.description" },
{ key: "address", binding: "brand.address" },
{ key: "headline", binding: "brand.config.visualPresentation.home.title" },
],
},
],
{
[presentationFieldName("identity", "description")]: "新简介",
[presentationFieldName("identity", "address")]: "新地址",
[presentationFieldName("identity", "headline")]: "新标题",
},
);
assert.equal(brandDraft.description, "新简介");
assert.equal(brandDraft.address, "新地址");
assert.equal(brandDraft.config.visualPresentation.home.title, "新标题");
const entitySection = [
{
key: "card",
fields: [
{ key: "name", binding: "offering.name" },
{ key: "summary", binding: "offering.summary" },
{ key: "category", binding: "offering.config.categoryLabel" },
],
},
];
const updatedEntity = applyStandardEntityValues(
{ id: "one", name: "旧名称", summary: "旧简介", config: { categoryLabel: "分类" } },
"offering",
entitySection,
{ "card:name": "新名称", "card:summary": "新简介", "card:category": "新分类" },
);
assert.equal(updatedEntity.name, "新名称");
assert.equal(updatedEntity.summary, "新简介");
assert.equal(updatedEntity.id, "one");
assert.deepEqual(updatedEntity.config, { categoryLabel: "分类" });
assert.equal(readPresentationValue({}, "offering.name", undefined, updatedEntity), "新名称");
const targets = [
{ key: "brand.hero", label: "主视觉", source: "brand", page: "home" },
{ key: "offering.card", label: "餐品", source: "offering", page: "offerings" },
];
assert.deepEqual(resolvePreviewSelection("brand.hero", undefined, targets, "home"), {
targetKey: "brand.hero",
});
assert.deepEqual(resolvePreviewSelection("offering.card", "one", targets, "offerings"), {
targetKey: "offering.card",
recordId: "one",
});
assert.equal(resolvePreviewSelection("offering.card", undefined, targets, "offerings"), undefined);
assert.equal(resolvePreviewSelection("brand.hero", "one", targets, "home"), undefined);
assert.equal(resolvePreviewSelection("brand.hero", undefined, targets, "offerings"), undefined);
+14 -8
View File
@@ -2,12 +2,11 @@ import assert from "node:assert/strict";
import test from "node:test"; import test from "node:test";
import { templatePreviewUrl } from "../src/lib/template-preview.ts"; import { templatePreviewUrl } from "../src/lib/template-preview.ts";
test("template preview URL is resolved from generic deployment configuration", () => { test("template preview URL is resolved from one shared deployment address", () => {
const url = templatePreviewUrl( const url = templatePreviewUrl(
"new-template",
"brand-a", "brand-a",
"profile", "profile",
JSON.stringify({ "new-template": "https://preview.example.test/app/" }), "https://preview.example.test/app/",
"https://admin.example.test", "https://admin.example.test",
"/pages/profile/index", "/pages/profile/index",
); );
@@ -17,11 +16,18 @@ test("template preview URL is resolved from generic deployment configuration", (
); );
}); });
test("missing, malformed or invalid template preview configuration fails closed", () => { test("the shared same-origin preview address is the default", () => {
assert.equal(templatePreviewUrl("missing", "brand-a", "home", undefined), undefined);
assert.equal(templatePreviewUrl("missing", "brand-a", "home", "{"), undefined);
assert.equal( assert.equal(
templatePreviewUrl("broken", "brand-a", "home", JSON.stringify({ broken: "not a URL" })), templatePreviewUrl("brand-a", "home", undefined),
undefined, "http://localhost:3002/?editor=1&brand=brand-a#/pages/home/index",
);
assert.equal(templatePreviewUrl("brand-a", "home", "{"), undefined);
assert.equal(templatePreviewUrl("brand-a", "home", "not a URL"), undefined);
});
test("same-origin static preview uses its explicit entry document", () => {
assert.equal(
templatePreviewUrl("brand-a", "home", "/template-preview/index.html", "http://localhost:3005"),
"http://localhost:3005/template-preview/index.html?editor=1&parentOrigin=http%3A%2F%2Flocalhost%3A3005&brand=brand-a#/pages/home/index",
); );
}); });
+14
View File
@@ -1,9 +1,23 @@
import { defineConfig } from "vite"; import { defineConfig } from "vite";
import react from "@vitejs/plugin-react"; import react from "@vitejs/plugin-react";
import { templatePreviewCss } from "./template-preview-css.mjs";
export default defineConfig({ export default defineConfig({
plugins: [react()], plugins: [react()],
css: { postcss: { plugins: [templatePreviewCss()] } },
base: process.env.VITE_APP_BASE_PATH ?? "/", base: process.env.VITE_APP_BASE_PATH ?? "/",
resolve: {
alias: {
"@tarojs/components": `${process.cwd()}/src/features/brand/taro-web-components.jsx`,
"@tarojs/taro": `${process.cwd()}/src/features/brand/taro-web-runtime.jsx`,
},
},
define: {
"process.env.TARO_PLATFORM": JSON.stringify("web"),
"process.env.TARO_ENV": JSON.stringify("h5"),
PREVIEW_ALL_TEMPLATES: JSON.stringify(true),
TEMPLATE_MANIFEST: JSON.stringify({ navigation: [] }),
},
server: { server: {
host: "0.0.0.0", host: "0.0.0.0",
port: Number(process.env.ADMIN_PORT ?? 3000), port: Number(process.env.ADMIN_PORT ?? 3000),
@@ -36,12 +36,14 @@ import {
} from "@personal-brand/config"; } from "@personal-brand/config";
import { TemplateWorkspaceService } from "./template-workspace.service.js"; import { TemplateWorkspaceService } from "./template-workspace.service.js";
import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation"; import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation";
import { PublicWorkspaceService } from "./modules/public/public-workspace.controller.js";
@Controller("admin/workspace") @Controller("admin/workspace")
class AdminWorkspaceController { class AdminWorkspaceController {
constructor( constructor(
private readonly prisma: PrismaService, private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService, private readonly templateWorkspace: TemplateWorkspaceService,
private readonly publicWorkspace: PublicWorkspaceService,
) {} ) {}
private brandId(): string { private brandId(): string {
return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001"; return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
@@ -194,6 +196,11 @@ class AdminWorkspaceController {
: null, : null,
}; };
} }
@Get("preview")
async getPreviewWorkspace(@Req() request: FastifyRequest): Promise<unknown> {
const { brandId } = this.requireAdmin(request);
return this.publicWorkspace.getForBrandId(brandId);
}
private jsonObject(value: unknown): Record<string, unknown> { private jsonObject(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value) return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>) ? (value as Record<string, unknown>)
+5 -1
View File
@@ -7,7 +7,10 @@ import { BookingService } from "./booking.service.js";
import { AdminAuthService } from "./admin-auth.service.js"; import { AdminAuthService } from "./admin-auth.service.js";
import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js"; import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js";
import { AdminWorkspaceController } from "./admin-workspace.controller.js"; import { AdminWorkspaceController } from "./admin-workspace.controller.js";
import { PublicWorkspaceController } from "./modules/public/public-workspace.controller.js"; import {
PublicWorkspaceController,
PublicWorkspaceService,
} from "./modules/public/public-workspace.controller.js";
import { PublicBrandContextService } from "./modules/public/public-brand-context.service.js"; import { PublicBrandContextService } from "./modules/public/public-brand-context.service.js";
import { AdminConfigController } from "./modules/admin/admin-config.controller.js"; import { AdminConfigController } from "./modules/admin/admin-config.controller.js";
import { PublicOfferingController } from "./modules/public/public-offering.controller.js"; import { PublicOfferingController } from "./modules/public/public-offering.controller.js";
@@ -70,6 +73,7 @@ export class HealthController {
BrandReleaseService, BrandReleaseService,
BrandReleaseApiService, BrandReleaseApiService,
PublicBrandContextService, PublicBrandContextService,
PublicWorkspaceService,
], ],
exports: [PrismaService, WechatAuthService], exports: [PrismaService, WechatAuthService],
}) })
@@ -1,4 +1,4 @@
import { Controller, Get, Query } from "@nestjs/common"; import { Controller, Get, Injectable, Query } from "@nestjs/common";
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { PrismaService } from "../../prisma.service.js"; import { PrismaService } from "../../prisma.service.js";
import { PublicBrandContextService } from "./public-brand-context.service.js"; import { PublicBrandContextService } from "./public-brand-context.service.js";
@@ -26,15 +26,11 @@ import {
projectTrustPresentation, projectTrustPresentation,
} from "@personal-brand/types"; } from "@personal-brand/types";
@Controller("public/workspace") @Injectable()
export class PublicWorkspaceController { export class PublicWorkspaceService {
constructor( constructor(private readonly prisma: PrismaService) {}
private readonly prisma: PrismaService,
private readonly brandContext: PublicBrandContextService, async getForBrandId(brandId: string): Promise<unknown> {
) {}
@Get()
async get(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
const brandId = await this.brandContext.resolveId(brandSlug);
const release = await this.prisma.brandRelease.findFirst({ const release = await this.prisma.brandRelease.findFirst({
where: { brandId, status: "published" }, where: { brandId, status: "published" },
orderBy: { version: "desc" }, orderBy: { version: "desc" },
@@ -370,3 +366,17 @@ export class PublicWorkspaceController {
return value === "create-booking" || value === "create-quote" ? value : "create-inquiry"; return value === "create-booking" || value === "create-quote" ? value : "create-inquiry";
} }
} }
@Controller("public/workspace")
export class PublicWorkspaceController {
constructor(
private readonly brandContext: PublicBrandContextService,
private readonly workspaceService: PublicWorkspaceService,
) {}
@Get()
async get(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
const brandId = await this.brandContext.resolveId(brandSlug);
return this.workspaceService.getForBrandId(brandId);
}
}
+22
View File
@@ -1325,6 +1325,28 @@ 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 () => {
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 wrongRole = await request("/admin/workspace/preview", {
headers: { authorization: `Bearer ${customerToken}` },
});
assert.equal(wrongRole.statusCode, 403);
const authorized = await request("/admin/workspace/preview", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(authorized.statusCode, 200);
const workspace = JSON.parse(authorized.body);
assert.equal(workspace.publication?.status, "published");
assert.equal(
workspace.brand.slug,
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).slug,
);
assert.equal(workspace.brand.visualTemplateKey, "acheng-campus-food");
});
test("admin can customize workspace fields with brand isolation", async () => { test("admin can customize workspace fields with brand isolation", async () => {
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } }); await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } }); await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
+21 -3
View File
@@ -4,6 +4,7 @@ import fs from "node:fs";
const root = path.resolve(__dirname, "../../.."); const root = path.resolve(__dirname, "../../..");
const key = process.env.TEMPLATE_KEY || "acheng-campus-food"; const key = process.env.TEMPLATE_KEY || "acheng-campus-food";
const previewAllTemplates = process.env.PREVIEW_ALL_TEMPLATES === "true";
const templates = fs const templates = fs
.readdirSync(path.join(root, "packages")) .readdirSync(path.join(root, "packages"))
.filter( .filter(
@@ -30,20 +31,33 @@ export default defineConfig({
designWidth: 750, designWidth: 750,
deviceRatio: { 750: 1 }, deviceRatio: { 750: 1 },
sourceRoot: "src", sourceRoot: "src",
outputRoot: `dist/${key}/${process.env.TARO_ENV || "weapp"}`, outputRoot: previewAllTemplates
? "dist/template-preview/h5"
: `dist/${key}/${process.env.TARO_ENV || "weapp"}`,
framework: "react", framework: "react",
compiler: { type: "vite" }, compiler: { type: "vite" },
plugins: [], plugins: [],
alias: { "@template": path.join(template, "taro") }, alias: {
"@template": previewAllTemplates
? path.resolve(__dirname, "../src/runtime/template-preview-entry.tsx")
: path.join(template, "taro"),
},
defineConstants: { defineConstants: {
TEMPLATE_KEY: JSON.stringify(key), TEMPLATE_KEY: JSON.stringify(key),
BRAND_SLUG: JSON.stringify(brand), BRAND_SLUG: JSON.stringify(brand),
API_BASE_URL: JSON.stringify(process.env.API_BASE_URL || "http://localhost:3001"), API_BASE_URL: JSON.stringify(process.env.API_BASE_URL || "http://localhost:3001"),
TEMPLATE_MANIFEST: JSON.stringify(manifest), TEMPLATE_MANIFEST: JSON.stringify(manifest),
PREVIEW_ALL_TEMPLATES: JSON.stringify(previewAllTemplates),
}, },
copy: { copy: {
options: {}, options: {},
patterns: [ patterns: [
...(previewAllTemplates
? templates.map((templateKey) => ({
from: path.join(root, "packages", `template-${templateKey}`, "miniapp/assets"),
to: `dist/template-preview/h5/assets/${templateKey}`,
}))
: []),
...(process.env.TARO_ENV === "weapp" ...(process.env.TARO_ENV === "weapp"
? [ ? [
{ {
@@ -52,15 +66,19 @@ export default defineConfig({
}, },
] ]
: []), : []),
...(!previewAllTemplates
? [
{ {
from: path.join(template, "miniapp/assets"), from: path.join(template, "miniapp/assets"),
to: `dist/${key}/${process.env.TARO_ENV || "weapp"}/assets`, to: `dist/${key}/${process.env.TARO_ENV || "weapp"}/assets`,
}, },
]
: []),
], ],
}, },
mini: {}, mini: {},
h5: { h5: {
publicPath: "/", publicPath: process.env.PREVIEW_PUBLIC_PATH || "/",
router: { mode: "hash" }, router: { mode: "hash" },
devServer: { host: "0.0.0.0", port: Number(process.env.PREVIEW_PORT || 3002) }, devServer: { host: "0.0.0.0", port: Number(process.env.PREVIEW_PORT || 3002) },
}, },
+2
View File
@@ -3,7 +3,9 @@
"private": true, "private": true,
"scripts": { "scripts": {
"dev:h5": "taro build --type h5 --watch", "dev:h5": "taro build --type h5 --watch",
"dev:preview": "PREVIEW_ALL_TEMPLATES=true taro build --type h5 --watch",
"build:h5": "taro build --type h5", "build:h5": "taro build --type h5",
"build:preview": "PREVIEW_ALL_TEMPLATES=true taro build --type h5",
"build:weapp": "taro build --type weapp", "build:weapp": "taro build --type weapp",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"lint": "pnpm --workspace-root exec eslint apps/taro/src apps/taro/config packages/template-acheng-campus-food/taro packages/template-linjing-editorial/taro", "lint": "pnpm --workspace-root exec eslint apps/taro/src apps/taro/config packages/template-acheng-campus-food/taro packages/template-linjing-editorial/taro",
+4
View File
@@ -21,6 +21,8 @@ export default defineAppConfig({
navigationBarBackgroundColor: "#ffffff", navigationBarBackgroundColor: "#ffffff",
navigationBarTextStyle: "black", navigationBarTextStyle: "black",
}, },
...(!PREVIEW_ALL_TEMPLATES
? {
tabBar: { tabBar: {
color: "#8b8178", color: "#8b8178",
selectedColor: "#3b2118", selectedColor: "#3b2118",
@@ -32,4 +34,6 @@ export default defineAppConfig({
selectedIconPath: tab.selectedIconPath, selectedIconPath: tab.selectedIconPath,
})), })),
}, },
}
: {}),
}); });
+10 -2
View File
@@ -17,7 +17,13 @@ import type { Values } from "../runtime/content";
import { ensureSession, request, brandSlug } from "../runtime/api"; import { ensureSession, request, brandSlug } from "../runtime/api";
import { takeQuery, navigate } from "../runtime/navigation"; import { takeQuery, navigate } from "../runtime/navigation";
import "./forms.css"; import "./forms.css";
export function Inquiry({ workspace }: { workspace: RuntimeWorkspace }) { export function Inquiry({
workspace,
preview = false,
}: {
workspace: RuntimeWorkspace;
preview?: boolean;
}) {
const router = useRouter(); const router = useRouter();
const [offeringId, setOfferingId] = useState(router.params.offeringId || ""); const [offeringId, setOfferingId] = useState(router.params.offeringId || "");
const form: RuntimeInquiryForm | undefined = const form: RuntimeInquiryForm | undefined =
@@ -28,7 +34,7 @@ export function Inquiry({ workspace }: { workspace: RuntimeWorkspace }) {
const [sending, setSending] = useState(false); const [sending, setSending] = useState(false);
const busy = useRef(false); const busy = useRef(false);
const p = presentation(workspace, "inquiry"); const p = presentation(workspace, "inquiry");
const food = TEMPLATE_KEY === "acheng-campus-food"; const food = workspace.brand.visualTemplateKey === "acheng-campus-food";
useDidShow(() => { useDidShow(() => {
const query = takeQuery("inquiry"); const query = takeQuery("inquiry");
if (query.offeringId) setOfferingId(query.offeringId); if (query.offeringId) setOfferingId(query.offeringId);
@@ -40,6 +46,7 @@ export function Inquiry({ workspace }: { workspace: RuntimeWorkspace }) {
const setValue = (key: string, value: string | string[]) => const setValue = (key: string, value: string | string[]) =>
setValues((current) => ({ ...current, [key]: value })); setValues((current) => ({ ...current, [key]: value }));
async function submit() { async function submit() {
if (preview) return;
if (busy.current) return; if (busy.current) return;
if (!form) { if (!form) {
setError("咨询表单暂不可用,请稍后重试"); setError("咨询表单暂不可用,请稍后重试");
@@ -96,6 +103,7 @@ export function Inquiry({ workspace }: { workspace: RuntimeWorkspace }) {
<View <View
className={`form-field ${food && ["people", "date", "budget", "delivery"].includes(field.key) ? "half-field" : ""}`} className={`form-field ${food && ["people", "date", "budget", "delivery"].includes(field.key) ? "half-field" : ""}`}
key={field.key} key={field.key}
data-editor-target={preview ? `inquiry-field:${field.key}` : undefined}
> >
<Text className="field-label"> <Text className="field-label">
{field.label} {field.label}
+3 -2
View File
@@ -9,7 +9,7 @@ import { Inquiry } from "./Inquiry";
import { Records } from "./Records"; import { Records } from "./Records";
import { Success } from "./Success"; import { Success } from "./Success";
export function Page({ page }: { page: PageKey }) { export function Page({ page }: { page: PageKey }) {
const { workspace, error, loading, reload, setBrandDraft } = useWorkspace(); const { workspace, error, loading, reload, setBrandDraft, setWorkspaceDraft } = useWorkspace();
const router = useRouter(); const router = useRouter();
useEffect(() => { useEffect(() => {
if (process.env.TARO_ENV !== "h5" || window.parent === window) return; if (process.env.TARO_ENV !== "h5" || window.parent === window) return;
@@ -27,6 +27,7 @@ export function Page({ page }: { page: PageKey }) {
if (event.source !== window.parent || event.origin !== parentOrigin) return; if (event.source !== window.parent || event.origin !== parentOrigin) return;
const message = event.data; const message = event.data;
if (message?.protocol !== "personal-brand-editor-preview" || message.version !== 1) return; if (message?.protocol !== "personal-brand-editor-preview" || message.version !== 1) return;
if (message.type === "workspaceDraft") setWorkspaceDraft(message.workspace);
if (message.type === "brandDraft") setBrandDraft(message.brand); if (message.type === "brandDraft") setBrandDraft(message.brand);
if (message.type === "focusTarget") { if (message.type === "focusTarget") {
document.querySelectorAll<HTMLElement>("[data-editor-target]").forEach((element) => { document.querySelectorAll<HTMLElement>("[data-editor-target]").forEach((element) => {
@@ -63,7 +64,7 @@ export function Page({ page }: { page: PageKey }) {
window.removeEventListener("message", onMessage); window.removeEventListener("message", onMessage);
document.removeEventListener("click", onClick, true); document.removeEventListener("click", onClick, true);
}; };
}, [setBrandDraft]); }, [setBrandDraft, setWorkspaceDraft]);
if (loading) return <View className="runtime-state">正在加载…</View>; if (loading) return <View className="runtime-state">正在加载…</View>;
if (error || !workspace) if (error || !workspace)
return ( return (
+10 -3
View File
@@ -25,13 +25,20 @@ const labels: Record<string, string> = {
converted: "已转化", converted: "已转化",
closed: "已关闭", closed: "已关闭",
}; };
export function Records({ workspace }: { workspace: RuntimeWorkspace }) { export function Records({
workspace,
preview = false,
}: {
workspace: RuntimeWorkspace;
preview?: boolean;
}) {
const [records, setRecords] = useState<RecordItem[]>([]); const [records, setRecords] = useState<RecordItem[]>([]);
const [error, setError] = useState(""); const [error, setError] = useState("");
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [authenticated, setAuthenticated] = useState(hasSession()); const [authenticated, setAuthenticated] = useState(preview ? false : hasSession());
const p = presentation(workspace, "records"); const p = presentation(workspace, "records");
const load = useCallback(() => { const load = useCallback(() => {
if (preview) return;
if (!hasSession()) { if (!hasSession()) {
setAuthenticated(false); setAuthenticated(false);
setRecords([]); setRecords([]);
@@ -46,7 +53,7 @@ export function Records({ workspace }: { workspace: RuntimeWorkspace }) {
setAuthenticated(hasSession()); setAuthenticated(hasSession());
}) })
.finally(() => setLoading(false)); .finally(() => setLoading(false));
}, []); }, [preview]);
useDidShow(load); useDidShow(load);
return ( return (
<View className="records-page"> <View className="records-page">
+11 -3
View File
@@ -4,10 +4,18 @@ import type { RuntimeWorkspace } from "@personal-brand/types";
import { presentation, object, text } from "../runtime/content"; import { presentation, object, text } from "../runtime/content";
import { brandSlug } from "../runtime/api"; import { brandSlug } from "../runtime/api";
import { navigate } from "../runtime/navigation"; import { navigate } from "../runtime/navigation";
export function Success({ workspace }: { workspace: RuntimeWorkspace }) { export function Success({
workspace,
preview = false,
}: {
workspace: RuntimeWorkspace;
preview?: boolean;
}) {
const p = presentation(workspace, "success"); const p = presentation(workspace, "success");
const result = object(Taro.getStorageSync<unknown>(`latestInquiry:${brandSlug()}`)); const submitted =
if (!text(result.id)) preview ||
Boolean(text(object(Taro.getStorageSync<unknown>(`latestInquiry:${brandSlug()}`)).id));
if (!submitted)
return ( return (
<View className="runtime-state"> <View className="runtime-state">
尚未提交咨询<Button onClick={() => navigate("inquiry")}>填写需求</Button> 尚未提交咨询<Button onClick={() => navigate("inquiry")}>填写需求</Button>
+4
View File
@@ -12,7 +12,11 @@ declare const TEMPLATE_MANIFEST: {
selectedIconPath: string; selectedIconPath: string;
}[]; }[];
}; };
declare const PREVIEW_ALL_TEMPLATES: boolean;
declare module "*.css"; declare module "*.css";
interface ImportMeta {
glob<T = unknown>(pattern: string, options?: { eager?: boolean }): Record<string, T>;
}
declare module "@template" { declare module "@template" {
export { TemplatePage } from "../../../packages/template-acheng-campus-food/taro"; export { TemplatePage } from "../../../packages/template-acheng-campus-food/taro";
} }
+9 -4
View File
@@ -7,6 +7,12 @@ export function brandSlug() {
} }
return BRAND_SLUG; return BRAND_SLUG;
} }
function isEditorPreview() {
return (
process.env.TARO_ENV === "h5" &&
new URLSearchParams(window.location.search).get("editor") === "1"
);
}
export const tokenKey = () => `customerToken:${brandSlug()}`; export const tokenKey = () => `customerToken:${brandSlug()}`;
export function hasSession() { export function hasSession() {
return Boolean(Taro.getStorageSync<string>(tokenKey())); return Boolean(Taro.getStorageSync<string>(tokenKey()));
@@ -16,7 +22,8 @@ export async function request<T>(
options: { method?: "GET" | "POST"; data?: unknown; customer?: boolean } = {}, options: { method?: "GET" | "POST"; data?: unknown; customer?: boolean } = {},
): Promise<T> { ): Promise<T> {
const context = path.startsWith("/public/") || path.startsWith("/customer/session/wechat"); const context = path.startsWith("/public/") || path.startsWith("/customer/session/wechat");
const query = context const query =
context && !(isEditorPreview() && path === "/public/workspace")
? `${path.includes("?") ? "&" : "?"}brandSlug=${encodeURIComponent(brandSlug())}` ? `${path.includes("?") ? "&" : "?"}brandSlug=${encodeURIComponent(brandSlug())}`
: ""; : "";
const response = await Taro.request<T & { error?: { message?: string; requestId?: string } }>({ const response = await Taro.request<T & { error?: { message?: string; requestId?: string } }>({
@@ -38,9 +45,7 @@ export async function request<T>(
} }
export async function loadWorkspace() { export async function loadWorkspace() {
const data = await request<RuntimeWorkspace>("/public/workspace"); const data = await request<RuntimeWorkspace>("/public/workspace");
const editorPreview = const editorPreview = isEditorPreview();
process.env.TARO_ENV === "h5" &&
new URLSearchParams(window.location.search).get("editor") === "1";
if (!editorPreview && data.publication?.status !== "published") throw new Error("品牌尚未发布"); if (!editorPreview && data.publication?.status !== "published") throw new Error("品牌尚未发布");
if (!editorPreview && data.brand.visualTemplateKey !== TEMPLATE_KEY) if (!editorPreview && data.brand.visualTemplateKey !== TEMPLATE_KEY)
throw new Error("该品牌使用其他模板,请选择匹配的模板预览地址"); throw new Error("该品牌使用其他模板,请选择匹配的模板预览地址");
@@ -0,0 +1,23 @@
import type { ComponentType } from "react";
import type { TemplateProps } from "./template";
type TemplateRenderer = ComponentType<TemplateProps>;
const renderers = import.meta.glob<{
TemplatePage: TemplateRenderer;
}>("../../../../packages/template-*/taro/index.tsx", { eager: true });
export function TemplatePage(props: TemplateProps) {
const config = props.workspace.brand.config;
const visualTemplateKey =
config && typeof config === "object" && !Array.isArray(config)
? (config as Record<string, unknown>).visualTemplateKey
: undefined;
const templateKey = typeof visualTemplateKey === "string" ? visualTemplateKey : TEMPLATE_KEY;
const suffix = `/template-${templateKey}/taro/index.tsx`;
const rendererModule = Object.entries(renderers).find(([path]) => path.endsWith(suffix))?.[1];
if (!rendererModule)
return <div className="runtime-state">当前模板没有可用的 H5 预览 renderer</div>;
const Renderer = rendererModule.TemplatePage;
return <Renderer {...props} />;
}
+31 -9
View File
@@ -8,19 +8,22 @@ const Context = createContext<{
error: string; error: string;
loading: boolean; loading: boolean;
setBrandDraft: (brand: Partial<RuntimeWorkspace["brand"]>) => void; setBrandDraft: (brand: Partial<RuntimeWorkspace["brand"]>) => void;
setWorkspaceDraft: (workspace: RuntimeWorkspace) => void;
reload: () => void; reload: () => void;
}>({ error: "", loading: true, setBrandDraft() {}, reload() {} }); }>({ error: "", loading: true, setBrandDraft() {}, setWorkspaceDraft() {}, reload() {} });
export function WorkspaceProvider({ children }: PropsWithChildren) { export function WorkspaceProvider({ children }: PropsWithChildren) {
const [baseWorkspace, setBaseWorkspace] = useState<RuntimeWorkspace>(); const [baseWorkspace, setBaseWorkspace] = useState<RuntimeWorkspace>();
const [brandDraft, setBrandDraft] = useState<Partial<RuntimeWorkspace["brand"]>>({}); const [brandDraft, setBrandDraft] = useState<Partial<RuntimeWorkspace["brand"]>>({});
const workspace = baseWorkspace const [workspaceDraft, setWorkspaceDraft] = useState<RuntimeWorkspace>();
const workspace = workspaceDraft ?? baseWorkspace;
const resolvedWorkspace = workspace
? { ? {
...baseWorkspace, ...workspace,
brand: projectBrandAliases( brand: projectBrandAliases(
{ ...baseWorkspace.brand, ...brandDraft }, { ...workspace.brand, ...brandDraft },
brandDraft.config && typeof brandDraft.config === "object" brandDraft.config && typeof brandDraft.config === "object"
? (brandDraft.config as Record<string, unknown>) ? (brandDraft.config as Record<string, unknown>)
: ((baseWorkspace.brand.config as Record<string, unknown> | undefined) ?? {}), : ((workspace.brand.config as Record<string, unknown> | undefined) ?? {}),
), ),
} }
: undefined; : undefined;
@@ -29,16 +32,35 @@ export function WorkspaceProvider({ children }: PropsWithChildren) {
const reload = useCallback(() => { const reload = useCallback(() => {
setLoading(true); setLoading(true);
setError(""); setError("");
void loadWorkspace() const editorPreview =
.then(setBaseWorkspace) process.env.TARO_ENV === "h5" &&
new URLSearchParams(window.location.search).get("editor") === "1";
const workspacePromise = editorPreview ? Promise.resolve(undefined) : loadWorkspace();
void workspacePromise
.then((value) => {
if (value) setBaseWorkspace(value);
})
.catch((error: unknown) => .catch((error: unknown) =>
setError(error instanceof Error ? error.message : "加载失败,请重试"), setError(error instanceof Error ? error.message : "加载失败,请重试"),
) )
.finally(() => setLoading(false)); .finally(() => setLoading(!editorPreview));
}, []); }, []);
useEffect(reload, [reload]); useEffect(reload, [reload]);
return ( return (
<Context.Provider value={{ workspace, error, loading, setBrandDraft, reload }}> <Context.Provider
value={{
workspace: resolvedWorkspace,
error,
loading:
process.env.TARO_ENV === "h5" &&
new URLSearchParams(window.location.search).get("editor") === "1"
? !workspace
: loading,
setBrandDraft,
setWorkspaceDraft,
reload,
}}
>
{children} {children}
</Context.Provider> </Context.Provider>
); );
+541 -13
View File
@@ -1,6 +1,6 @@
import { test, expect } from "@playwright/test"; import { test, expect } from "@playwright/test";
const adminOrigin = "http://localhost:3011"; const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
const brand = { const brand = {
id: "brand-fixture", id: "brand-fixture",
slug: "preview-fixture", slug: "preview-fixture",
@@ -8,7 +8,7 @@ const brand = {
templateKey: "food", templateKey: "food",
tagline: "校园家常餐", tagline: "校园家常餐",
description: "认真做好每一餐", description: "认真做好每一餐",
avatarUrl: "", avatarUrl: "/assets/owner/portrait.jpg",
coverUrl: "", coverUrl: "",
hours: "每日 17:00", hours: "每日 17:00",
address: "东门附近", address: "东门附近",
@@ -23,6 +23,33 @@ const brand = {
visualPresentation: { home: { stallTitle: "原服务地点", worksTitle: "原餐品标题" } }, visualPresentation: { home: { stallTitle: "原服务地点", worksTitle: "原餐品标题" } },
}, },
}; };
const adminOffering = {
id: "menu-fixture",
kind: "service",
name: "家庭聚餐定制",
summary: "为同学聚餐、家庭聚会提供常见的私房菜定制。",
description: "餐品详情",
priceText: "88.88",
coverUrl: brand.avatarUrl,
isEnabled: true,
sortOrder: 0,
config: { categoryLabel: "业务提供项" },
};
const adminTrust = {
id: "schedule-fixture",
type: "schedule",
title: "出摊安排",
summary: "工作日安排",
content: "周末安排",
sortOrder: 0,
isPublished: true,
config: {
weekdayLabel: "周一至周五",
weekdayDetail: "东门附近",
weekendLabel: "周六至周日",
weekendDetail: "周末晚间出摊",
},
};
const runtimeWorkspace = { const runtimeWorkspace = {
schemaVersion: "1.0.0", schemaVersion: "1.0.0",
publication: { status: "published", version: 1 }, publication: { status: "published", version: 1 },
@@ -35,20 +62,128 @@ const runtimeWorkspace = {
}, },
templateData: {}, templateData: {},
navigation: { tabs: [] }, navigation: { tabs: [] },
offerings: [], offerings: [
inquiryForms: [], {
trustItems: [], id: adminOffering.id,
name: adminOffering.name,
summary: adminOffering.summary,
priceText: adminOffering.priceText,
coverUrl: adminOffering.coverUrl,
presentation: {
categoryLabel: "业务提供项",
keywords: [],
details: { background: "餐品详情", designConcept: "", crafts: [], materialsList: [] },
},
},
],
inquiryForms: [
{
key: "brand-inquiry",
version: "1",
purpose: "inquiry",
target: "brand",
submissionAction: "create-inquiry",
fields: [
{ key: "name", label: "称呼", type: "text", required: true },
{ key: "message", label: "需求说明", type: "textarea", required: true },
],
},
],
trustItems: [{ ...adminTrust }],
trustPresentation: {}, trustPresentation: {},
capabilities: [], capabilities: [],
theme: { colors: {} }, theme: { colors: {} },
}; };
const templateContent = { const templateContent = {
displayName: "餐饮模板", displayName: "餐饮模板",
navigation: [{ key: "home", page: "home", label: "首页" }], 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: [], assetSlots: [],
trustContentTypes: [], 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: { admin: {
sections: [ 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", key: "home",
title: "首页内容", title: "首页内容",
@@ -56,10 +191,25 @@ const templateContent = {
page: "home", page: "home",
target: "brand", target: "brand",
previewTargets: [ 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.location", label: "服务地点" },
{ key: "food.home.offerings-heading", label: "餐品区域标题" }, { key: "food.home.offerings-heading", label: "餐品区域标题" },
{ key: "food.home.actions", label: "首页操作按钮" },
], ],
fields: [ fields: [
{
key: "identity",
binding: "brand.config.founder",
previewTarget: "food.home.identity",
label: "主理人姓名",
input: "text",
},
{ {
key: "stallTitle", key: "stallTitle",
binding: "brand.config.visualPresentation.home.stallTitle", binding: "brand.config.visualPresentation.home.stallTitle",
@@ -81,6 +231,13 @@ const templateContent = {
label: "招牌餐品标题", label: "招牌餐品标题",
input: "text", input: "text",
}, },
{
key: "primaryAction",
binding: "brand.config.visualPresentation.home.primaryAction",
previewTarget: "food.home.actions",
label: "咨询按钮",
input: "text",
},
], ],
}, },
], ],
@@ -88,6 +245,8 @@ const templateContent = {
}; };
test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ page }) => { test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ page }) => {
let rejectOfferingSave = false;
await page.setViewportSize({ width: 1920, height: 1000 });
await page.route("http://localhost:3001/public/workspace**", (route) => await page.route("http://localhost:3001/public/workspace**", (route) =>
route.fulfill({ json: runtimeWorkspace }), route.fulfill({ json: runtimeWorkspace }),
); );
@@ -112,10 +271,62 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
return route.fulfill({ json: brand }); return route.fulfill({ json: brand });
} }
if (url.pathname === "/admin/config/brand") return route.fulfill({ json: brand }); if (url.pathname === "/admin/config/brand") return route.fulfill({ json: brand });
if (url.pathname === "/admin/workspace/offerings")
return route.fulfill({ json: [adminOffering] });
if (url.pathname === "/admin/workspace/forms")
return route.fulfill({
json: [
{
id: "brand-inquiry",
name: "品牌咨询",
version: 1,
isEnabled: true,
purpose: "inquiry",
targetType: "brand",
submissionAction: "create-inquiry",
fieldsSnapshot: runtimeWorkspace.inquiryForms[0].fields,
},
],
});
if (
url.pathname === `/admin/workspace/offerings/${adminOffering.id}` &&
request.method() === "PATCH"
) {
if (rejectOfferingSave) {
rejectOfferingSave = false;
return route.fulfill({
status: 500,
json: {
error: { message: "保存暂时失败,请重试", code: "TEST_FAILURE", requestId: "fixture" },
},
});
}
Object.assign(adminOffering, request.postDataJSON());
Object.assign(runtimeWorkspace.offerings[0], {
name: adminOffering.name,
summary: adminOffering.summary,
});
return route.fulfill({ json: adminOffering });
}
if (url.pathname === "/admin/config/trust-content")
return route.fulfill({ json: [adminTrust] });
if (
url.pathname === `/admin/config/trust-content/${adminTrust.id}` &&
request.method() === "PATCH"
) {
Object.assign(adminTrust, request.postDataJSON());
Object.assign(runtimeWorkspace.trustItems[0], {
title: adminTrust.title,
config: adminTrust.config,
});
return route.fulfill({ json: adminTrust });
}
if (url.pathname === "/admin/workspace") if (url.pathname === "/admin/workspace")
return route.fulfill({ return route.fulfill({
json: { brand, installations: [], fields: [], offerings: [], forms: [], templateContent }, json: { brand, installations: [], fields: [], offerings: [], forms: [], templateContent },
}); });
if (url.pathname === "/admin/workspace/preview")
return route.fulfill({ json: runtimeWorkspace });
if (url.pathname === "/public/templates/food") if (url.pathname === "/public/templates/food")
return route.fulfill({ return route.fulfill({
json: { name: "餐饮模板", description: "fixture", serviceCategories: [] }, json: { name: "餐饮模板", description: "fixture", serviceCategories: [] },
@@ -129,16 +340,333 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
await page.getByLabel("密码").fill("fixture-password"); await page.getByLabel("密码").fill("fixture-password");
await page.locator('button[type="submit"]').click(); await page.locator('button[type="submit"]').click();
await expect(page.getByText("小程序页面配置")).toBeVisible(); await expect(page.getByText("小程序页面配置")).toBeVisible();
const frame = page.frameLocator('iframe[title="小程序页面预览"]'); await expect(page.getByLabel("品牌名称", { exact: true })).toBeHidden();
await expect(frame.locator(".food-home .name")).toContainText("测试主理人"); await page.getByText("品牌资料", { exact: true }).last().click();
await frame.locator('[data-editor-target="food.home.location"]').click(); await expect(page.getByLabel("品牌名称", { exact: true })).toBeVisible();
await page.getByText("页面编辑", { exact: true }).click();
const preview = page.locator(".component-template-preview");
await expect(preview.locator(".food-home .name")).toContainText("测试主理人");
await expect(page.getByText("选择要编辑的区域", { exact: true })).toBeVisible();
for (const width of [1920, 1280, 1024, 768, 390]) {
await page.setViewportSize({ width, height: 1000 });
const editor = page.locator(".presentation-editor");
await editor.scrollIntoViewIfNeeded();
await expect
.poll(() => editor.evaluate((element) => element.scrollWidth - element.clientWidth))
.toBeLessThanOrEqual(1);
await editor.screenshot({
path: "../../.codex-tasks/admin-editor-workspace/raw/editor-" + width + ".png",
});
}
await page.setViewportSize({ width: 1920, height: 1000 });
await page.getByRole("button", { name: "选择品牌信息区" }).click();
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
"data-selected-target",
"food.home.brand-card",
);
await expect(page.getByRole("button", { name: "编辑主理人身份" })).toBeVisible();
await page.getByRole("button", { name: "编辑服务地点" }).click();
await expect(page.getByLabel("出摊信息标题")).toBeVisible();
await page.getByRole("button", { name: "选择品牌信息区" }).click();
await page.getByRole("button", { name: "编辑主理人身份" }).click();
await expect(page.getByLabel("主理人姓名")).toBeVisible();
await page.keyboard.press("Escape");
const dimensions = await preview.evaluate((element) => {
const canvas = element.querySelector(".component-template-preview__canvas")!;
const name = element.querySelector(".name")!;
const avatar = element.querySelector(".identity img")!;
return {
width: canvas.getBoundingClientRect().width,
font: parseFloat(getComputedStyle(name).fontSize),
avatar: avatar.getBoundingClientRect().width,
transform: getComputedStyle(canvas.firstElementChild!).transform,
};
});
expect(dimensions.font / dimensions.width).toBeCloseTo(32 / 750, 3);
expect(dimensions.avatar / dimensions.width).toBeCloseTo(128 / 750, 3);
expect(dimensions.transform).toBe("none");
await expect
.poll(() =>
preview.locator(".identity img").evaluate((image: HTMLImageElement) => image.naturalWidth),
)
.toBeGreaterThan(0);
await preview.screenshot({ path: "../../.codex-tasks/preview-proportion/home.png" });
const actionButtons = preview.locator(".food-home .actions button");
await expect(actionButtons).toHaveCount(2);
const previewBox = await preview.locator(".component-template-preview__canvas").boundingBox();
const firstActionBox = await actionButtons.nth(0).boundingBox();
const secondActionBox = await actionButtons.nth(1).boundingBox();
expect(previewBox && firstActionBox && secondActionBox).toBeTruthy();
expect(firstActionBox!.x).toBeGreaterThanOrEqual(previewBox!.x);
expect(secondActionBox!.x + secondActionBox!.width).toBeLessThanOrEqual(
previewBox!.x + previewBox!.width,
);
await expect(actionButtons.nth(0)).toContainText("咨询 / 预订");
await expect(actionButtons.nth(1)).toContainText("查看餐品");
await page.getByRole("button", { name: "选择品牌信息区" }).click();
await page.getByRole("button", { name: "编辑首页操作按钮" }).click();
await expect(page.getByLabel("咨询按钮")).toBeVisible();
await page.keyboard.press("Escape");
await page.getByRole("button", { name: "选择品牌信息区" }).click();
await page.getByRole("button", { name: "编辑服务地点" }).click();
await expect(page.getByText("出摊信息标题")).toBeVisible(); await expect(page.getByText("出摊信息标题")).toBeVisible();
await expect(page.getByText("招牌餐品标题")).toHaveCount(0); await expect(page.getByText("招牌餐品标题")).toHaveCount(0);
await page.getByLabel("出摊信息标题").fill("后台草稿地点"); await page.getByLabel("出摊信息标题").fill("后台草稿地点");
await expect(preview.locator(".notice-title")).toContainText("后台草稿地点");
await page.getByRole("button", { name: "保存页面内容" }).click(); await page.getByRole("button", { name: "保存页面内容" }).click();
await expect(page.getByText("页面内容已保存为草稿,发布后小程序才会更新")).toBeVisible(); await expect(page.getByText("页面内容已保存为草稿,发布后小程序才会更新")).toBeVisible();
await expect(frame.locator(".notice-title")).toContainText("后台草稿地点"); await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
await expect(frame.locator('[data-editor-target="food.home.location"]')).toHaveClass( "data-selected-target",
/editor-target-selected/, "food.home.location",
); );
await page.getByRole("button", { name: "浏览页面" }).click();
await preview.locator(".food-home .actions button").nth(1).click();
await expect(page.getByText("招牌餐品标题")).toHaveCount(0);
await page.getByRole("button", { name: "点选编辑" }).click();
await page.getByRole("button", { name: "选择品牌信息区" }).click();
await page.getByRole("button", { name: "编辑服务地点" }).click();
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
"data-selected-target",
"food.home.location",
);
await page.keyboard.press("Escape");
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveCount(0);
await page.getByText("套餐餐品", { exact: true }).click();
await expect(preview.locator(".offering-card")).toHaveCount(1);
await preview.locator('[data-editor-target="acheng-campus-food.offerings.item"]').click();
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
"data-selected-record-id",
adminOffering.id,
);
await page.getByLabel("餐品名称").fill("编辑后的家庭餐");
await expect(page.getByText("有未保存修改", { exact: true })).toBeVisible();
await page.getByText("出摊服务", { exact: true }).click();
await expect(page.getByRole("dialog", { name: "有尚未保存的修改" })).toBeVisible();
await page.getByRole("button", { name: "继续编辑" }).click();
await expect(page.getByLabel("餐品名称")).toHaveValue("编辑后的家庭餐");
await expect(preview.locator(".offering-card")).toContainText("编辑后的家庭餐");
rejectOfferingSave = true;
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect(page.getByText("保存暂时失败,请重试", { exact: true })).toBeVisible();
await expect(page.getByLabel("餐品名称")).toHaveValue("编辑后的家庭餐");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect.poll(() => adminOffering.name).toBe("编辑后的家庭餐");
await page.reload();
await page.getByText("套餐餐品", { exact: true }).click();
await expect(preview.locator(".offering-card")).toContainText("编辑后的家庭餐");
await page.getByText("出摊服务", { exact: true }).click();
await preview.locator('[data-editor-target="trust:schedule"]').click();
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
"data-selected-record-id",
adminTrust.id,
);
await page.getByLabel("工作日标题").fill("周一到周五营业");
await expect(preview.locator(".schedule-card")).toContainText("周一到周五营业");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect.poll(() => adminTrust.config.weekdayLabel).toBe("周一到周五营业");
await page.reload();
await page.getByText("出摊服务", { exact: true }).click();
await expect(preview.locator(".schedule-card")).toContainText("周一到周五营业");
await page.getByText("详情页", { exact: true }).click();
await expect(page.locator(".component-template-preview")).toHaveCount(1);
await expect(preview.locator(".component-template-preview__canvas")).toHaveCount(1);
await expect(preview.locator(".food-detail")).toHaveCount(1);
const detailBounds = await preview.evaluate((element) => {
const canvas = element.querySelector(".component-template-preview__canvas")!;
const bar = element.querySelector(".food-detail .bar")!;
const canvasBox = canvas.getBoundingClientRect();
const barBox = bar.getBoundingClientRect();
return {
position: getComputedStyle(bar).position,
left: barBox.left - canvasBox.left,
right: canvasBox.right - barBox.right,
bottom: canvasBox.bottom - barBox.bottom,
};
});
expect(detailBounds.position).toBe("absolute");
expect(detailBounds.left).toBeGreaterThanOrEqual(-1);
expect(detailBounds.right).toBeGreaterThanOrEqual(-1);
expect(detailBounds.bottom).toBeGreaterThanOrEqual(-1);
await preview.locator(".food-detail .bar").scrollIntoViewIfNeeded();
await expect(preview.locator(".food-detail .bar button")).toBeVisible();
await preview.screenshot({ path: "../../.codex-tasks/preview-proportion/detail.png" });
await expect(page.getByText("详情页由所选业务内容动态生成")).toBeVisible();
await expect(page.getByRole("button", { name: "点选编辑" })).toHaveCount(0);
await expect(page.getByLabel("价格标题")).toHaveCount(0);
await expect(page.getByLabel("餐品介绍")).toHaveCount(0);
await page.getByText("定制/咨询", { exact: true }).click();
await expect(preview.locator(".inquiry-form .form-field")).toHaveCount(2);
await expect(preview.locator(".inquiry-form")).toContainText("称呼");
await expect(preview.locator(".inquiry-form")).toContainText("需求说明");
await preview.locator('[data-editor-target="inquiry-field:name"]').click();
await expect(page.getByLabel("字段标题")).toHaveValue("称呼");
await preview.locator(".inquiry-form").scrollIntoViewIfNeeded();
await preview.screenshot({ path: "../../.codex-tasks/preview-proportion/inquiry.png" });
const formOverflow = await preview
.locator(".inquiry-form")
.evaluate((form) => form.scrollWidth - form.clientWidth);
expect(formOverflow).toBeLessThanOrEqual(1);
await page.getByRole("button", { name: "浏览页面" }).click();
await preview.locator(".inquiry-form input").first().fill("预览访客");
await expect(preview.locator(".inquiry-form input").first()).toHaveValue("预览访客");
await page.getByText("提交成功页", { exact: true }).click();
await expect(preview.locator(".success-page")).toBeVisible();
await expect(preview.locator(".success-page")).toContainText("已收到你的需求");
await page.getByText("记录页", { exact: true }).click();
await expect(preview.locator(".records-page")).toBeVisible();
await expect(preview.locator(".records-page")).toContainText("请在微信小程序内登录查看");
await page.getByText("套餐餐品", { exact: true }).click();
await page.getByRole("button", { name: "点选编辑" }).click();
await expect
.poll(() =>
preview.locator(".dish-media img").evaluate((image: HTMLImageElement) => image.naturalWidth),
)
.toBeGreaterThan(0);
for (const width of [390, 320]) {
await preview.locator(".component-template-preview__canvas").evaluate((element, size) => {
(element as HTMLElement).style.width = size + "px";
}, width);
const layout = await preview.evaluate((element) => {
const canvas = element.querySelector(".component-template-preview__canvas")!;
const card = element.querySelector(".offering-card")!;
const media = element.querySelector(".dish-media")!;
return {
canvas: canvas.getBoundingClientRect().width,
overflow: card.scrollWidth - card.clientWidth,
media: media.getBoundingClientRect().width,
};
});
expect(layout.overflow).toBeLessThanOrEqual(1);
expect(layout.media / layout.canvas).toBeCloseTo(224 / 750, 3);
await preview.screenshot({
path: "../../.codex-tasks/preview-proportion/menu-" + width + ".png",
});
}
});
test("林境模板支持首页和主理人区域点选", async ({ page }) => {
await page.setViewportSize({ width: 1600, height: 900 });
const editorialBrand = {
...structuredClone(brand),
templateKey: "personal",
config: {
visualTemplateKey: "linjing-editorial",
founder: "林境主理人",
title: "建筑设计师",
heroImage: "/assets/tab/home.png",
homeHero: { title: "林境作品" },
},
};
const editorialWorkspace = {
...structuredClone(runtimeWorkspace),
brand: {
...structuredClone(runtimeWorkspace.brand),
...editorialBrand,
founder: "林境主理人",
title: "建筑设计师",
heroImage: "/assets/tab/home.png",
homeHero: { title: "林境作品" },
},
offerings: [],
trustItems: [],
};
const editorialContent = {
displayName: "林境模板",
navigation: [
{ key: "home", page: "home", label: "首页" },
{ key: "profile", page: "profile", label: "主理人与我" },
],
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",
},
],
},
],
},
};
await page.route("**/api/**", (route) => {
const url = new URL(route.request().url());
const path = url.pathname.replace(/^\/api/, "");
if (path === "/admin/session/login")
return route.fulfill({
json: { token: "fixture-token", displayName: "测试管理员", role: "owner" },
});
if (path === "/admin/brands")
return route.fulfill({
json: [{ id: editorialBrand.id, role: "owner", brand: editorialBrand }],
});
if (path === "/admin/config/brand") return route.fulfill({ json: editorialBrand });
if (path === "/public/templates/personal")
return route.fulfill({
json: { name: "个人品牌", description: "林境模板", serviceCategories: [] },
});
if (path === "/admin/workspace")
return route.fulfill({
json: {
brand: editorialBrand,
installations: [],
fields: [],
offerings: [],
forms: [],
templateContent: editorialContent,
},
});
if (path === "/admin/workspace/preview" || path === "/public/workspace")
return route.fulfill({ json: editorialWorkspace });
return route.fulfill({ json: {} });
});
await page.goto(adminOrigin + "/admin/brand");
await page.getByLabel("账号").fill("admin");
await page.getByLabel("密码").fill("fixture-password");
await page.locator('button[type="submit"]').click();
const preview = page.locator(".component-template-preview");
await expect(preview.locator(".editorial-home")).toBeVisible();
await expect(preview.locator(".hero-title")).toContainText("林境作品");
await expect
.poll(() =>
preview.locator(".hero-image").evaluate((image: HTMLImageElement) => image.naturalWidth),
)
.toBeGreaterThan(0);
await preview.locator('[data-editor-target="editorial.home.hero"]').click();
await expect(page.getByLabel("首页标题")).toBeVisible();
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.getByLabel("主理人姓名")).toBeVisible();
await page.getByLabel("主理人姓名").fill("修改后的主理人");
await expect(preview.locator(".editorial-profile .founder")).toContainText("修改后的主理人");
}); });
+42
View File
@@ -0,0 +1,42 @@
# 0020:后台可视化页面编辑预览
## Context
后台已能根据模板 manifest 展示字段,但管理员难以判断字段对应小程序的哪个区块。Taro H5 renderer 可复用小程序页面结构;按模板分别构建和运行 H5 服务、编译时固定单个 renderer,则无法支撑多个品牌和模板的生产部署。
## Decision
采用基于模板 renderer 的可视化编辑器,并将 H5 预览作为同一套 Admin 产品的静态运行时:
1. `admin.sections` 是编辑字段分组,不等同 DOM 区块。section 声明稳定的 `previewTargets`,字段声明 `previewTarget`。
2. renderer 在可编辑区域输出 `data-editor-target`。新增模板必须为所有页面字段声明 binding 和 target,并通过自动发现的契约测试。
3. 一个 H5 预览应用在构建时收集所有带 Taro renderer 的模板包,运行时根据品牌当前模板选择 renderer。
4. 本地开发只启动一个 Vite H5 预览服务。生产构建将 H5 静态文件复制到 Admin `/template-preview/`,与 Admin 一起部署;线上不运行 Vite,也不按模板运行服务。
5. Admin iframe 与 renderer 使用带版本的 `postMessage` 协议,校验 origin、source 和协议版本。Admin 发送品牌草稿和 target focus;renderer 回传 target 选择。
6. 表单输入立即投影到预览草稿,保存仍是显式动作。失败时保留用户输入和草稿。
7. Admin 按模板契约运行,不按模板 key、行业名或字段名增加业务分支。
8. 信任内容、业务提供项、咨询表单等记录数据继续由通用 Admin feature 编辑;它们的页面区域需提供明确的对应编辑入口,不能冒充品牌 config 字段。
9. 不支持拖拽布局或持久化 HTML。
## Alternatives
- 在 Admin 复制一套 React 预览:会造成后台和小程序视觉分叉,弃用。
- 每模板单独构建并运行 H5 服务:开发和部署负担随模板数量增长,弃用。
- 生产环境运行 Vite:不是静态部署方案且扩大运行时依赖,弃用。
- 将 HTML 存进数据库:无法保持模板升级和字段 binding 一致,弃用。
- 一开始建设完整低代码画布:范围过大,暂缓。
## Consequences
- Preview build、静态资源打包和部署路径是 Admin 发布门槛。
- renderer 需要显式标记可编辑区域;漏掉的字段由模板契约测试拒绝。
- H5 iframe 使用当前已发布 workspace 作为底稿,管理员草稿只在客户端预览,不伪造已发布状态。
- 新模板新增 renderer 后自动进入 preview build;未实现 Taro renderer 的模板必须明确显示不支持,不能显示空白预览。
## Migration Plan
### 组件预览阶段补充
Admin 有 workspace 时直接复用 Taro renderer,iframe 保留为 H5 回退。组件预览必须补齐原运行环境的尺寸、元素选择器及资源映射:750 设计宽度通过容器单位转换,image/text/view 选择器映射到对应 DOM,模板静态资源经 Vite 打包。不得通过猜测 transform 系数修复单位不一致。此方案避免额外预览服务,但仍需验证所有模板的适配能力;当前 renderer 注册尚为显式列表,自动发现纳入后续任务。详见 `docs/visual-editor-next-steps.md`。
先实现单一多模板 H5 静态构建和 Admin 同源部署;补齐现有模板所有页面字段 target;验证即时草稿、保存失败和业务记录编辑入口;再将 preview build 纳入正式部署流水线。
+29
View File
@@ -0,0 +1,29 @@
# 0021 Admin 品牌配置与页面编辑工作区
## 背景
品牌基础资料、模板说明和可视化编辑被多个 Card 包裹,预览仅占页面的一部分。用户难以理解编辑入口与实际展示之间的关系。
## 决策
工作台默认进入页面编辑,通过顶部视图切换访问品牌资料。编辑器采用左侧区域导航、中间预览、右侧属性编辑三栏布局,窄屏堆叠。组合区域的子区域在导航中缩进,并与画布选区同步。视图切换保持组件挂载,避免丢弃未保存输入。发布操作通过顶部入口进入已有发布流程。
品牌基础资料使用连续的身份、联系合作和视觉分组。模板说明作为基础配置的辅助信息。页面编辑工作区使用完整页面宽度,页面导航位于顶部,预览与选区面板并列,窄屏上下排列。未选择区域时提供明确的点选引导,避免展示整页字段。
详情页只提供业务记录选择和动态预览,隐藏区域列表和点选工具;业务记录在业务提供项中维护。模板 manifest 的字段声明继续供业务内容编辑器和模板校验使用。
## 替代方案
继续嵌套 Card 会保留视觉层级混乱。单独建立第二套预览页面会造成 renderer 与模板实际展示分离。采用现有 renderer 和表单机制可以复用既有契约。
## 后果
配置与预览的空间更明确,区域编辑仍由模板声明驱动。基础品牌信息与模板区域保存仍分别执行,保存后的内容是草稿,需要发布才能公开展示。没有可编辑区域的页面不显示点选工具。
## 迁移计划
仅调整 Admin 布局与详情页编辑入口,不迁移数据库。使用已有字段绑定和 API,并通过多宽度截图、真实鼠标交互、类型检查、lint 和生产构建验收。
## 已知后续项
Admin 生产构建的共享 api chunk 超过 500 kB。由 Admin 前端后续打包优化任务负责拆分,当前构建成功。
+13 -2
View File
@@ -21,10 +21,21 @@ location /api/ {
} }
``` ```
构建管理后台时使用: 生产构建会先把所有已接入模板的 H5 renderer 编译进一个静态预览应用,再将其放到 Admin 的 `/template-preview/` 下。线上无需启动 Vite,也无需为每个模板运行单独服务。构建管理后台与预览应用时使用:
```bash ```bash
VITE_APP_BASE_PATH=/admin/ VITE_API_BASE_URL=/api pnpm --filter @personal-brand/admin build pnpm build:admin:preview
``` ```
部署时将 `apps/admin/dist` 作为同一个静态站点发布。预览 iframe 与 Admin 同源,运行时根据品牌公开工作区中的 `visualTemplateKey` 选择已打包的模板 renderer,并通过 `/api` 读取已发布数据;管理员正在编辑的草稿由 Admin 经 `postMessage` 投影到 iframe,不会写回公开 API。
本地开发只需启动一个多模板 H5 服务和 Admin:
```bash
pnpm preview:templates
VITE_APP_BASE_PATH=/ ADMIN_PORT=3000 pnpm --filter @personal-brand/admin dev
```
本地 Admin 默认连接 `http://localhost:3002` 上的统一预览服务。`VITE_TEMPLATE_PREVIEW_URL` 只用于部署时覆盖预览应用地址,不再按模板配置 URL map。
如果希望 API 服务自身也带前缀,可设置 `API_PREFIX=api`。使用 Nginx 去前缀转发时保持默认空值即可,避免重复 `/api/api`。 如果希望 API 服务自身也带前缀,可设置 `API_PREFIX=api`。使用 Nginx 去前缀转发时保持默认空值即可,避免重复 `/api/api`。
+78
View File
@@ -0,0 +1,78 @@
# 可视化编辑后续任务
## 当前基线
Admin 直接复用 Taro renderer,模板原始 CSS 按 750 设计宽度转换为预览容器单位,模板图片经 Vite 打包。已有区域点击、选中样式、品牌字段筛选、即时草稿和显式保存;保留 H5 iframe 作为回退。当前不代表所有页面、记录与字段均已完成编辑闭环。
## 1. 统一选区契约
- 统一 selection 为模板、页面、targetKey、实体类型、recordId;重复餐品和信任卡片必须带记录标识。
- 从 manifest 解析中文名称、binding、编辑能力,不在 Admin 中新增行业条件分支。
- 校验 target 存在、binding 可解析、页面归属正确;切页、删记录和换模板清理无效选区。
- 验收:嵌套区块选最近目标,重复卡片准确选中对应记录,未知目标不打开错误表单。
## 2. 完成点选与高亮交互
- 区分浏览模式与编辑模式;编辑模式阻止咨询提交、导航等真实操作。
- 使用独立覆盖层显示悬停边框、选中边框及中文区域名,避免改变模板背景、尺寸和布局。
- 覆盖层随滚动、容器尺寸、图片加载和字段换行更新;支持空白取消、Escape 取消及键盘选择。
- 验收:320/390 画布、长页面、滚动及图片加载后边框仍准确,不遮挡按钮和表单。
## 3. 打通绑定值编辑
- 右侧固定显示区域名称、数据来源、对应字段、未保存状态;点字段时定位关联区域。
- 品牌配置、业务记录、信任内容、咨询表单使用各自现有 API 和验证规则;记录 ID 由选区携带。
- 把当前仅跳转管理页的记录区域接入对应编辑器,复用原有表单与 mutation。
- 图片、列表、条件字段按模板声明渲染;空值、默认值、继承值明确区分。
- 验收:改值即时预览;保存后重新读取仍一致;失败保留输入并可重试;未保存切页给出明确选择。
## 4. 自动化验收和部署
- 按模板包自动发现 renderer、页面与资源,去掉现有 renderer 注册的手工二选一;未知模板明确显示不支持。
- 对每个模板覆盖首页、列表、详情、信任区及表单:选择→字段→草稿→保存→重载。
- 覆盖非空真实结构数据、嵌套/重复目标、授权失败、图片实际解码、样式尺寸和溢出;仅 DOM 存在不能作为视觉通过。
- 校验发布前后隔离:草稿不影响公开页面,发布后访客读取新值;受保护接口覆盖无凭证、错误角色及成功路径。
- 验收生产静态构建及子路径部署,不按模板新增 Vite 服务。
## 推进顺序
以下计划以 feat/admin-component-preview / 541304a 为基线。已有交互仅部分通过测试,不能视为逐页完成。实施状态以 `.codex-tasks/visual-editor-closure/SUBTASKS.csv` 为准,旧任务记录保留。
### 第一阶段:覆盖清单与绑定修复
1. 逐页盘点餐饮、林境模板,建立 coverage.csv:模板、页面、区域、实际读取字段、声明 binding、实体来源、记录定位、编辑入口、缺陷和验证证据。区分业务内容、访客输入、导航及装饰;空数据区域也纳入。
2. 优先复现首页身份区域缺少点选标记、咨询区域标为 inquiry 却包含 brand 文案导致字段过滤、咨询字段缺少独立目标。继续逐页排查,不将这些示例视为全部缺陷。
3. 补充 ADR 0020 后统一解析:区域表示页面位置,binding 决定字段来源;记录用稳定 ID,咨询字段用表单 ID 与字段 key。混合来源不能依赖 section.target 单一分类。模板包声明,Admin 通用解析。
4. 修复嵌套目标、重复记录、无效选区与空区域新增入口;模板和 renderer 从包目录发现,建立可主动检出缺失映射的契约测试。
验收:所有声明页面进入清单;首页身份、咨询文案和重复卡片可准确定位;有意破坏映射时测试失败。
### 第二阶段:区域编辑面板
- 显示页面、区域、具体记录和未保存状态。未选择时显示区域导航,选中后只显示对应字段。
- 普通字段默认单列,图片有预览与替换入口,列表支持逐项增删排序。依据面板宽度安排布局,消除强制双列和固定空白,不堆叠重复卡片。
- 字段焦点与选区双向定位,高亮随滚动、图片加载、长文本更新且不改变模板布局。
- 保存范围明确;失败保留值并可重试;有草稿时切区域、页面或品牌提供保存、放弃、取消选择。
验收:窄面板无溢出,长表单操作可达;图片、长文本、列表及保存失败、切换路径均有浏览器验证。
### 第三阶段:咨询表单编辑
- 区分页面文案、表单结构和访客试填。点击具体字段后编辑标题、提示、必填、类型及适用选项,复用现有验证规则。
- 支持增删排序、空表单创建及条件显隐配置,检查条件引用有效性。
- 复用 InquiryForm API、版本与发布语义;类型变更和删除不得破坏历史提交快照。预览不创建真实咨询、不读取客户记录。
验收:修改即时展示且保存重载一致;选择题、日期、长文本、条件字段、空状态均覆盖。接口若有变更,必须覆盖授权、品牌隔离、校验失败及成功持久化。
### 第四阶段:全页面与部署验收
- 按清单逐项验证点选、字段、草稿、保存、刷新;结合自动发现的契约检查与关键浏览器场景,不仅检查 DOM 存在。
- 使用隔离品牌验证真实 API 保存、草稿与公开内容隔离、发布后读取一致,不覆盖用户开发数据。
- 对照两套模板视觉;验证 320/390 画布、图片解码、页脚、表单;运行 H5 和小程序构建检查共享组件回归。
- 运行 format:check、lint、相关 typecheck、validate:templates、Admin tests/build、浏览器测试及涉及的 API/API Client 测试。生产静态与子路径部署可用,无按模板单独运行服务需求。
验收:本轮覆盖项都有通过证据;未完成项保持显式状态。按依赖提交可运行单元,提供预览与验证记录,合并仍等待用户确认。
## 本轮边界
本次先制定计划,功能实施尚未开始。聚焦内容编辑,不做任意拖拽布局或 HTML 入库。保留模板视觉和 H5 回退;不重置数据库或 seed,必要结构调整先制定兼容迁移。
+5
View File
@@ -12,6 +12,7 @@ export default tseslint.config(
"apps/api/test/**/*.test.js", "apps/api/test/**/*.test.js",
"apps/api/test/**/*.cjs", "apps/api/test/**/*.cjs",
"apps/admin/test/**/*.test.mjs", "apps/admin/test/**/*.test.mjs",
"apps/admin/public/**",
"packages/types/test/**/*.test.mjs", "packages/types/test/**/*.test.mjs",
"apps/taro/test/**/*.test.mjs", "apps/taro/test/**/*.test.mjs",
"apps/taro/src/assets/**", "apps/taro/src/assets/**",
@@ -53,4 +54,8 @@ export default tseslint.config(
"@typescript-eslint/require-await": "off", "@typescript-eslint/require-await": "off",
}, },
}, },
{
...tseslint.configs.disableTypeChecked,
files: ["apps/admin/template-preview-css.mjs"],
},
); );
+2
View File
@@ -26,6 +26,8 @@
"clean": "turbo run clean && rimraf node_modules .turbo", "clean": "turbo run clean && rimraf node_modules .turbo",
"preview:food": "pnpm --filter @personal-brand/taro dev:h5", "preview:food": "pnpm --filter @personal-brand/taro dev:h5",
"preview:linjing": "TEMPLATE_KEY=linjing-editorial PREVIEW_PORT=3003 pnpm --filter @personal-brand/taro dev:h5", "preview:linjing": "TEMPLATE_KEY=linjing-editorial PREVIEW_PORT=3003 pnpm --filter @personal-brand/taro dev:h5",
"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: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"
}, },
+15 -2
View File
@@ -11,10 +11,15 @@ import type {
RuntimeTrustItem, RuntimeTrustItem,
ThemeManifest, ThemeManifest,
} from "@personal-brand/types"; } from "@personal-brand/types";
export { projectBrandAliases, projectTrustPresentation } from "@personal-brand/types";
export type { PublicOffering } from "@personal-brand/types"; export type { PublicOffering } from "@personal-brand/types";
export type { BookingStatus } from "@personal-brand/types"; export type { BookingStatus } from "@personal-brand/types";
export type { BrandTemplateKey } from "@personal-brand/types"; export type { BrandTemplateKey } from "@personal-brand/types";
export type { EditorPreviewFrameMessage, EditorPreviewHostMessage } from "@personal-brand/types"; export type {
EditorPreviewFrameMessage,
EditorPreviewHostMessage,
RuntimeWorkspace,
} from "@personal-brand/types";
export interface BrandProfile { export interface BrandProfile {
id: string; id: string;
@@ -102,7 +107,12 @@ export interface TemplateAdminSection {
description: string; description: string;
page: string; page: string;
target: "brand" | "offering" | "trust" | "inquiry"; target: "brand" | "offering" | "trust" | "inquiry";
previewTargets?: Array<{ key: string; label: string }>; previewTargets?: Array<{
key: string;
label: string;
composite?: boolean;
children?: string[];
}>;
fields: TemplateAdminField[]; fields: TemplateAdminField[];
} }
@@ -688,6 +698,9 @@ export class ApiClient {
}> { }> {
return this.request("/admin/workspace"); return this.request("/admin/workspace");
} }
getAdminPreviewWorkspace(): Promise<import("@personal-brand/types").RuntimeWorkspace> {
return this.request("/admin/workspace/preview");
}
listAdminReleases(): Promise<BrandReleaseSummary[]> { listAdminReleases(): Promise<BrandReleaseSummary[]> {
return this.request("/admin/releases"); return this.request("/admin/releases");
} }
File diff suppressed because it is too large. Load diff
@@ -6,7 +6,8 @@ import { navigate } from "../../../apps/taro/src/runtime/navigation";
import { presentation, offering, slot, text, rows } from "../../../apps/taro/src/runtime/content"; import { presentation, offering, slot, text, rows } from "../../../apps/taro/src/runtime/content";
import type { RuntimeWorkspace } from "@personal-brand/types"; import type { RuntimeWorkspace } from "@personal-brand/types";
import "./style.css"; import "./style.css";
const asset = (name: string) => `/assets/${name}`; const asset = (name: string) =>
`/assets/${PREVIEW_ALL_TEMPLATES ? "acheng-campus-food/" : ""}${name}`;
function Home({ workspace }: { workspace: RuntimeWorkspace }) { function Home({ workspace }: { workspace: RuntimeWorkspace }) {
const brand = workspace.brand; const brand = workspace.brand;
const p = presentation(workspace, "home"); const p = presentation(workspace, "home");
@@ -14,8 +15,8 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
return ( return (
<View className="food-home"> <View className="food-home">
<View className="page"> <View className="page">
<View className="brand-card"> <View className="brand-card" data-editor-target="food.home.brand-card">
<View className="identity"> <View className="identity" data-editor-target="food.home.identity">
{text(brand.avatarUrl) && <Image src={text(brand.avatarUrl)} mode="aspectFill" />} {text(brand.avatarUrl) && <Image src={text(brand.avatarUrl)} mode="aspectFill" />}
<View> <View>
<Text className="name">{text(brand.founder)}</Text> <Text className="name">{text(brand.founder)}</Text>
@@ -28,12 +29,12 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
<Text>{text(brand.address)}</Text> <Text>{text(brand.address)}</Text>
{p.stallTime && <Text className="notice-time">{p.stallTime}</Text>} {p.stallTime && <Text className="notice-time">{p.stallTime}</Text>}
</View> </View>
<View className="actions"> <View className="actions" data-editor-target="food.home.actions">
<Button className="home-action" onClick={() => navigate("inquiry")}> <Button className="home-action" onClick={() => navigate("inquiry")}>
咨询 / 预订 {p.primaryAction || "咨询 / 预订"}
</Button> </Button>
<Button className="home-action muted" onClick={() => navigate("offerings")}> <Button className="home-action muted" onClick={() => navigate("offerings")}>
查看餐品 {p.secondaryAction || "查看餐品"}
</Button> </Button>
</View> </View>
</View> </View>
@@ -56,7 +57,7 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
<Text className="heading">{p.worksTitle || "可选餐品"}</Text> <Text className="heading">{p.worksTitle || "可选餐品"}</Text>
</View> </View>
<Text className="more" onClick={() => navigate("offerings")}> <Text className="more" onClick={() => navigate("offerings")}>
查看全部 › {p.moreAction || "查看全部"} ›
</Text> </Text>
</View> </View>
<View className="dish-grid"> <View className="dish-grid">
@@ -64,6 +65,8 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
<View <View
className="dish" className="dish"
key={item.id} key={item.id}
data-editor-target="acheng-campus-food.home.offering"
data-editor-record-id={item.id}
onClick={() => navigate("detail", { id: item.id })} onClick={() => navigate("detail", { id: item.id })}
> >
<Image src={item.image} mode="aspectFill" /> <Image src={item.image} mode="aspectFill" />
@@ -81,7 +84,12 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
{workspace.trustItems {workspace.trustItems
.filter((item) => ["promise", "case"].includes(item.type)) .filter((item) => ["promise", "case"].includes(item.type))
.map((item) => ( .map((item) => (
<View className="promise" key={item.id}> <View
className="promise"
key={item.id}
data-editor-target={`trust:${item.type}`}
data-editor-record-id={item.id}
>
<Text className="eyebrow light">{item.title}</Text> <Text className="eyebrow light">{item.title}</Text>
{item.summary && <Text className="promise-title">{item.summary}</Text>} {item.summary && <Text className="promise-title">{item.summary}</Text>}
<Text className="quote">{item.content}</Text> <Text className="quote">{item.content}</Text>
@@ -115,10 +123,14 @@ function Service({ workspace }: { workspace: RuntimeWorkspace }) {
].filter((row) => row.title && row.detail); ].filter((row) => row.title && row.detail);
const steps = rows(process?.config.steps).filter((step) => step.title && step.detail); const steps = rows(process?.config.steps).filter((step) => step.title && step.detail);
return ( return (
<View className="food-service"> <View className="food-service" data-editor-target="acheng-campus-food.service.service">
<View className="page service-page"> <View className="page service-page">
{schedule && scheduleRows.length > 0 && ( {schedule && scheduleRows.length > 0 && (
<View className="service-card schedule-card"> <View
className="service-card schedule-card"
data-editor-target="trust:schedule"
data-editor-record-id={schedule.id}
>
<View className="card-head"> <View className="card-head">
<View className="head-title"> <View className="head-title">
<Image className="icon" src={asset("service/clock.png")} /> <Image className="icon" src={asset("service/clock.png")} />
@@ -151,7 +163,11 @@ function Service({ workspace }: { workspace: RuntimeWorkspace }) {
</View> </View>
)} )}
{c && text(c.config.pickupDetail) && text(c.config.deliveryDetail) && ( {c && text(c.config.pickupDetail) && text(c.config.deliveryDetail) && (
<View className="service-card coverage-card"> <View
className="service-card coverage-card"
data-editor-target="trust:coverage"
data-editor-record-id={c.id}
>
<View className="simple-title"> <View className="simple-title">
<Image className="icon" src={asset("service/bike.png")} /> <Image className="icon" src={asset("service/bike.png")} />
<Text>{c.title}</Text> <Text>{c.title}</Text>
@@ -175,7 +191,11 @@ function Service({ workspace }: { workspace: RuntimeWorkspace }) {
</View> </View>
)} )}
{process && steps.length > 0 && ( {process && steps.length > 0 && (
<View className="service-card process-card"> <View
className="service-card process-card"
data-editor-target="trust:process"
data-editor-record-id={process.id}
>
<View className="simple-title"> <View className="simple-title">
<Image className="icon" src={asset("service/list.png")} /> <Image className="icon" src={asset("service/list.png")} />
<Text>{process.title}</Text> <Text>{process.title}</Text>
@@ -220,7 +240,7 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
const p = presentation(workspace, "profile"); const p = presentation(workspace, "profile");
const credentials = workspace.trustItems.filter((item) => item.type === "credential"); const credentials = workspace.trustItems.filter((item) => item.type === "credential");
return ( return (
<View className="food-profile"> <View className="food-profile" data-editor-target="acheng-campus-food.profile.identity">
<View className="page"> <View className="page">
<View className="profile-card"> <View className="profile-card">
<View className="portrait"> <View className="portrait">
@@ -236,7 +256,12 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
{text(brand.description) && <Text className="bio">{text(brand.description)}</Text>} {text(brand.description) && <Text className="bio">{text(brand.description)}</Text>}
{credentials.map((item) => {credentials.map((item) =>
rows(item.config.standards).length ? ( rows(item.config.standards).length ? (
<View className="standards" key={item.id}> <View
className="standards"
key={item.id}
data-editor-target="trust:credential"
data-editor-record-id={item.id}
>
{rows(item.config.standards).map((standard, index) => ( {rows(item.config.standards).map((standard, index) => (
<View className="standard" key={index}> <View className="standard" key={index}>
<Image <Image
@@ -251,7 +276,12 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
))} ))}
</View> </View>
) : ( ) : (
<View className="credential-copy" key={item.id}> <View
className="credential-copy"
key={item.id}
data-editor-target="trust:credential"
data-editor-record-id={item.id}
>
<Text className="credential-title">{item.title}</Text> <Text className="credential-title">{item.title}</Text>
{item.summary && <Text className="bio">{item.summary}</Text>} {item.summary && <Text className="bio">{item.summary}</Text>}
<Text className="bio">{item.content}</Text> <Text className="bio">{item.content}</Text>
@@ -263,7 +293,12 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
{workspace.trustItems {workspace.trustItems
.filter((item) => item.type === "case") .filter((item) => item.type === "case")
.map((item) => ( .map((item) => (
<View className="case-card" key={item.id}> <View
className="case-card"
key={item.id}
data-editor-target="trust:case"
data-editor-record-id={item.id}
>
<View className="section-heading"> <View className="section-heading">
<Image className="heading-icon" src={asset("owner/handshake.png")} /> <Image className="heading-icon" src={asset("owner/handshake.png")} />
<Text>{item.title}</Text> <Text>{item.title}</Text>
@@ -290,7 +325,12 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
{workspace.trustItems {workspace.trustItems
.filter((item) => item.type === "promise") .filter((item) => item.type === "promise")
.map((item) => ( .map((item) => (
<View className="promise-card" key={item.id}> <View
className="promise-card"
key={item.id}
data-editor-target="trust:promise"
data-editor-record-id={item.id}
>
<View className="section-heading"> <View className="section-heading">
<Image className="promise-icon" src={asset("owner/clock.png")} /> <Image className="promise-icon" src={asset("owner/clock.png")} />
<Text>{item.title}</Text> <Text>{item.title}</Text>
@@ -340,13 +380,22 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
</View> </View>
); );
} }
const formTargets: Record<string, string> = {
inquiry: "acheng-campus-food.inquiry.booking",
success: "acheng-campus-food.success.successCopy",
records: "acheng-campus-food.records.recordsCopy",
};
export function TemplatePage({ workspace, page, children, offeringId }: TemplateProps) { export function TemplatePage({ workspace, page, children, offeringId }: TemplateProps) {
if (page === "home") return <Home workspace={workspace} />; if (page === "home") return <Home workspace={workspace} />;
if (page === "service") return <Service workspace={workspace} />; if (page === "service") return <Service workspace={workspace} />;
if (page === "profile") return <Profile workspace={workspace} />; if (page === "profile") return <Profile workspace={workspace} />;
if (page === "offerings") return <OfferingList workspace={workspace} />; if (page === "offerings") return <OfferingList workspace={workspace} />;
if (page === "detail") return <Detail workspace={workspace} id={offeringId} />; if (page === "detail") return <Detail workspace={workspace} id={offeringId} />;
return <View className="food-forms">{children}</View>; return (
<View className="food-forms" data-editor-target={formTargets[page]}>
{children}
</View>
);
} }
function OfferingList({ workspace }: { workspace: RuntimeWorkspace }) { function OfferingList({ workspace }: { workspace: RuntimeWorkspace }) {
const p = presentation(workspace, "offerings"); const p = presentation(workspace, "offerings");
@@ -363,7 +412,7 @@ function OfferingList({ workspace }: { workspace: RuntimeWorkspace }) {
.includes(query.trim().toLowerCase()), .includes(query.trim().toLowerCase()),
); );
return ( return (
<View className="food-list"> <View className="food-list" data-editor-target="acheng-campus-food.offerings.menu">
<View className="page"> <View className="page">
<View className="filters"> <View className="filters">
<Button <Button
@@ -399,6 +448,8 @@ function OfferingList({ workspace }: { workspace: RuntimeWorkspace }) {
<View <View
className="offering-card" className="offering-card"
key={item.id} key={item.id}
data-editor-target="acheng-campus-food.offerings.item"
data-editor-record-id={item.id}
onClick={() => navigate("detail", { id: item.id })} onClick={() => navigate("detail", { id: item.id })}
> >
<View className="dish-media"> <View className="dish-media">
@@ -437,7 +488,11 @@ function Detail({ workspace, id }: { workspace: RuntimeWorkspace; id?: string })
const item = offering(found); const item = offering(found);
const p = presentation(workspace, "detail"); const p = presentation(workspace, "detail");
return ( return (
<View className="food-detail"> <View
className="food-detail"
data-editor-target="acheng-campus-food.detail.dishDetail"
data-editor-record-id={item.id}
>
<View className="detail"> <View className="detail">
<View className="hero-wrap"> <View className="hero-wrap">
<Image <Image
@@ -454,7 +509,7 @@ function Detail({ workspace, id }: { workspace: RuntimeWorkspace; id?: string })
<Text>{item.series}</Text> <Text>{item.series}</Text>
</View> </View>
</View> </View>
<View className="content"> <View className="content" data-editor-target="acheng-campus-food.detail.detailCopy">
<View className="price-card"> <View className="price-card">
<View> <View>
<Text>{p.priceLabel || "参考价格"}</Text> <Text>{p.priceLabel || "参考价格"}</Text>
@@ -144,7 +144,8 @@
"label": "主理人姓名", "label": "主理人姓名",
"input": "text", "input": "text",
"required": true, "required": true,
"placeholder": "例如:阿成" "placeholder": "例如:阿成",
"previewTarget": "acheng-campus-food.profile.identity"
}, },
{ {
"key": "title", "key": "title",
@@ -152,33 +153,87 @@
"label": "你的身份", "label": "你的身份",
"help": "例如:校园餐饮主理人。", "help": "例如:校园餐饮主理人。",
"input": "text", "input": "text",
"required": true "required": true,
"previewTarget": "acheng-campus-food.profile.identity"
}, },
{ {
"key": "badge", "key": "badge",
"binding": "brand.config.visualPresentation.profile.badge", "binding": "brand.config.visualPresentation.profile.badge",
"label": "写真角标", "label": "写真角标",
"input": "text", "input": "text",
"help": "显示在主理人写真上,可填写经验或服务定位。" "help": "显示在主理人写真上,可填写经验或服务定位。",
"previewTarget": "acheng-campus-food.profile.identity"
}, },
{ {
"key": "storyLead", "key": "storyLead",
"binding": "brand.config.visualPresentation.profile.storyLead", "binding": "brand.config.visualPresentation.profile.storyLead",
"label": "故事引言", "label": "故事引言",
"input": "textarea", "input": "textarea",
"help": "故事开头的强调段落,下面的正文使用品牌简介。" "help": "故事开头的强调段落,下面的正文使用品牌简介。",
"previewTarget": "acheng-campus-food.profile.identity"
}, },
{ {
"key": "recordsTitle", "key": "recordsTitle",
"binding": "brand.config.visualPresentation.profile.recordsTitle", "binding": "brand.config.visualPresentation.profile.recordsTitle",
"label": "记录入口文案", "label": "记录入口文案",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.profile.identity"
}, },
{ {
"key": "recordsCountUnit", "key": "recordsCountUnit",
"binding": "brand.config.visualPresentation.profile.recordsCountUnit", "binding": "brand.config.visualPresentation.profile.recordsCountUnit",
"label": "记录数量单位", "label": "记录数量单位",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.profile.identity"
}
],
"previewTargets": [
{
"key": "acheng-campus-food.profile.identity",
"label": "摊位与主理人"
}
]
},
{
"key": "homeOffering",
"title": "首页业务卡片",
"description": "点选预览中的单条内容,修改对应业务记录。",
"page": "home",
"target": "offering",
"fields": [
{
"key": "name",
"binding": "offering.name",
"label": "名称",
"input": "text",
"previewTarget": "acheng-campus-food.home.offering"
},
{
"key": "summary",
"binding": "offering.summary",
"label": "简介",
"input": "textarea",
"previewTarget": "acheng-campus-food.home.offering"
},
{
"key": "priceText",
"binding": "offering.priceText",
"label": "价格说明",
"input": "text",
"previewTarget": "acheng-campus-food.home.offering"
},
{
"key": "coverUrl",
"binding": "offering.coverUrl",
"label": "封面图片",
"input": "image",
"previewTarget": "acheng-campus-food.home.offering"
}
],
"previewTargets": [
{
"key": "acheng-campus-food.home.offering",
"label": "首页业务卡片"
} }
] ]
}, },
@@ -189,12 +244,52 @@
"page": "home", "page": "home",
"target": "brand", "target": "brand",
"previewTargets": [ "previewTargets": [
{ "key": "food.home.location", "label": "服务地点" }, {
{ "key": "food.home.hero", "label": "出摊现场图片" }, "key": "food.home.brand-card",
{ "key": "food.home.offerings-heading", "label": "餐品区域标题" }, "label": "品牌信息区",
{ "key": "food.home.promise-heading", "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.hero",
"label": "出摊现场图片"
},
{
"key": "food.home.offerings-heading",
"label": "餐品区域标题"
},
{
"key": "food.home.actions",
"label": "首页操作按钮"
},
{
"key": "food.home.promise-heading",
"label": "出餐承诺标题"
}
], ],
"fields": [ "fields": [
{
"key": "founder",
"binding": "brand.config.founder",
"label": "主理人姓名",
"input": "text",
"previewTarget": "food.home.identity"
},
{
"key": "title",
"binding": "brand.config.title",
"label": "身份说明",
"input": "text",
"previewTarget": "food.home.identity"
},
{ {
"key": "stallTitle", "key": "stallTitle",
"previewTarget": "food.home.location", "previewTarget": "food.home.location",
@@ -234,6 +329,27 @@
"label": "招牌餐品标题", "label": "招牌餐品标题",
"input": "text" "input": "text"
}, },
{
"key": "moreAction",
"previewTarget": "food.home.offerings-heading",
"binding": "brand.config.visualPresentation.home.moreAction",
"label": "查看全部按钮",
"input": "text"
},
{
"key": "primaryAction",
"previewTarget": "food.home.actions",
"binding": "brand.config.visualPresentation.home.primaryAction",
"label": "咨询按钮",
"input": "text"
},
{
"key": "secondaryAction",
"previewTarget": "food.home.actions",
"binding": "brand.config.visualPresentation.home.secondaryAction",
"label": "餐品按钮",
"input": "text"
},
{ {
"key": "manifestoTitle", "key": "manifestoTitle",
"previewTarget": "food.home.promise-heading", "previewTarget": "food.home.promise-heading",
@@ -255,7 +371,57 @@
"binding": "brand.config.visualPresentation.service.processAction", "binding": "brand.config.visualPresentation.service.processAction",
"label": "流程咨询按钮", "label": "流程咨询按钮",
"input": "text", "input": "text",
"placeholder": "例如:立即预订" "placeholder": "例如:立即预订",
"previewTarget": "acheng-campus-food.service.service"
}
],
"previewTargets": [
{
"key": "acheng-campus-food.service.service",
"label": "出摊服务页说明"
}
]
},
{
"key": "offeringsOffering",
"title": "业务卡片",
"description": "点选预览中的单条内容,修改对应业务记录。",
"page": "offerings",
"target": "offering",
"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": "priceText",
"binding": "offering.priceText",
"label": "价格说明",
"input": "text",
"previewTarget": "acheng-campus-food.offerings.item"
},
{
"key": "coverUrl",
"binding": "offering.coverUrl",
"label": "封面图片",
"input": "image",
"previewTarget": "acheng-campus-food.offerings.item"
}
],
"previewTargets": [
{
"key": "acheng-campus-food.offerings.item",
"label": "业务卡片"
} }
] ]
}, },
@@ -270,21 +436,30 @@
"key": "title", "key": "title",
"binding": "brand.config.visualPresentation.offerings.title", "binding": "brand.config.visualPresentation.offerings.title",
"label": "菜单页标题", "label": "菜单页标题",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.offerings.menu"
}, },
{ {
"key": "subtitle", "key": "subtitle",
"binding": "brand.config.visualPresentation.offerings.subtitle", "binding": "brand.config.visualPresentation.offerings.subtitle",
"label": "菜单页说明", "label": "菜单页说明",
"input": "textarea", "input": "textarea",
"maxLength": 120 "maxLength": 120,
"previewTarget": "acheng-campus-food.offerings.menu"
}, },
{ {
"key": "menuTip", "key": "menuTip",
"binding": "brand.config.visualPresentation.offerings.menuTip", "binding": "brand.config.visualPresentation.offerings.menuTip",
"label": "菜单提示", "label": "菜单提示",
"help": "只填写当前实际提供的取餐、加菜或定制服务。", "help": "只填写当前实际提供的取餐、加菜或定制服务。",
"input": "textarea" "input": "textarea",
"previewTarget": "acheng-campus-food.offerings.menu"
}
],
"previewTargets": [
{
"key": "acheng-campus-food.offerings.menu",
"label": "菜单页说明"
} }
] ]
}, },
@@ -299,28 +474,38 @@
"key": "title", "key": "title",
"binding": "brand.config.visualPresentation.inquiry.title", "binding": "brand.config.visualPresentation.inquiry.title",
"label": "预订页面标题", "label": "预订页面标题",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.inquiry.booking"
}, },
{ {
"key": "subtitle", "key": "subtitle",
"binding": "brand.config.visualPresentation.inquiry.subtitle", "binding": "brand.config.visualPresentation.inquiry.subtitle",
"label": "预订说明", "label": "预订说明",
"input": "textarea", "input": "textarea",
"maxLength": 120 "maxLength": 120,
"previewTarget": "acheng-campus-food.inquiry.booking"
}, },
{ {
"key": "submitLabel", "key": "submitLabel",
"binding": "brand.config.visualPresentation.inquiry.submitLabel", "binding": "brand.config.visualPresentation.inquiry.submitLabel",
"label": "提交按钮文字", "label": "提交按钮文字",
"input": "text", "input": "text",
"placeholder": "例如:提交预订需求" "placeholder": "例如:提交预订需求",
"previewTarget": "acheng-campus-food.inquiry.booking"
}, },
{ {
"key": "promise", "key": "promise",
"binding": "brand.config.visualPresentation.inquiry.promise", "binding": "brand.config.visualPresentation.inquiry.promise",
"label": "真实服务承诺", "label": "真实服务承诺",
"help": "仅填写能兑现的回复时间、订金和联系规则;留空则不显示。", "help": "仅填写能兑现的回复时间、订金和联系规则;留空则不显示。",
"input": "textarea" "input": "textarea",
"previewTarget": "acheng-campus-food.inquiry.booking"
}
],
"previewTargets": [
{
"key": "acheng-campus-food.inquiry.booking",
"label": "预订与定制"
} }
] ]
}, },
@@ -335,43 +520,50 @@
"key": "categoryLabel", "key": "categoryLabel",
"binding": "offering.config.categoryLabel", "binding": "offering.config.categoryLabel",
"label": "餐品类别", "label": "餐品类别",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.detail.dishDetail"
}, },
{ {
"key": "detailHero", "key": "detailHero",
"binding": "offering.config.detailHero", "binding": "offering.config.detailHero",
"label": "详情主图", "label": "详情主图",
"input": "image" "input": "image",
"previewTarget": "acheng-campus-food.detail.dishDetail"
}, },
{ {
"key": "area", "key": "area",
"binding": "offering.config.area", "binding": "offering.config.area",
"label": "供应地点", "label": "供应地点",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.detail.dishDetail"
}, },
{ {
"key": "series", "key": "series",
"binding": "offering.config.series", "binding": "offering.config.series",
"label": "套餐或系列说明", "label": "套餐或系列说明",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.detail.dishDetail"
}, },
{ {
"key": "spaceType", "key": "spaceType",
"binding": "offering.config.spaceType", "binding": "offering.config.spaceType",
"label": "适合场景", "label": "适合场景",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.detail.dishDetail"
}, },
{ {
"key": "background", "key": "background",
"binding": "offering.config.details.background", "binding": "offering.config.details.background",
"label": "餐品介绍", "label": "餐品介绍",
"input": "textarea" "input": "textarea",
"previewTarget": "acheng-campus-food.detail.dishDetail"
}, },
{ {
"key": "designConcept", "key": "designConcept",
"binding": "offering.config.details.designConcept", "binding": "offering.config.details.designConcept",
"label": "口味与分量", "label": "口味与分量",
"input": "textarea" "input": "textarea",
"previewTarget": "acheng-campus-food.detail.dishDetail"
}, },
{ {
"key": "keywords", "key": "keywords",
@@ -384,7 +576,8 @@
"key": "value", "key": "value",
"label": "特色" "label": "特色"
} }
] ],
"previewTarget": "acheng-campus-food.detail.dishDetail"
}, },
{ {
"key": "crafts", "key": "crafts",
@@ -397,7 +590,8 @@
"key": "value", "key": "value",
"label": "制作说明" "label": "制作说明"
} }
] ],
"previewTarget": "acheng-campus-food.detail.dishDetail"
}, },
{ {
"key": "materialsList", "key": "materialsList",
@@ -413,7 +607,14 @@
"key": "spec", "key": "spec",
"label": "说明" "label": "说明"
} }
] ],
"previewTarget": "acheng-campus-food.detail.dishDetail"
}
],
"previewTargets": [
{
"key": "acheng-campus-food.detail.dishDetail",
"label": "餐品与服务详情"
} }
] ]
}, },
@@ -428,50 +629,64 @@
"key": "priceLabel", "key": "priceLabel",
"binding": "brand.config.visualPresentation.detail.priceLabel", "binding": "brand.config.visualPresentation.detail.priceLabel",
"label": "价格说明标题", "label": "价格说明标题",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.detail.detailCopy"
}, },
{ {
"key": "spaceLabel", "key": "spaceLabel",
"binding": "brand.config.visualPresentation.detail.spaceLabel", "binding": "brand.config.visualPresentation.detail.spaceLabel",
"label": "适合场景标题", "label": "适合场景标题",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.detail.detailCopy"
}, },
{ {
"key": "backgroundTitle", "key": "backgroundTitle",
"binding": "brand.config.visualPresentation.detail.backgroundTitle", "binding": "brand.config.visualPresentation.detail.backgroundTitle",
"label": "餐品介绍标题", "label": "餐品介绍标题",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.detail.detailCopy"
}, },
{ {
"key": "conceptTitle", "key": "conceptTitle",
"binding": "brand.config.visualPresentation.detail.conceptTitle", "binding": "brand.config.visualPresentation.detail.conceptTitle",
"label": "口味与分量标题", "label": "口味与分量标题",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.detail.detailCopy"
}, },
{ {
"key": "craftsTitle", "key": "craftsTitle",
"binding": "brand.config.visualPresentation.detail.craftsTitle", "binding": "brand.config.visualPresentation.detail.craftsTitle",
"label": "制作方式标题", "label": "制作方式标题",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.detail.detailCopy"
}, },
{ {
"key": "materialsTitle", "key": "materialsTitle",
"binding": "brand.config.visualPresentation.detail.materialsTitle", "binding": "brand.config.visualPresentation.detail.materialsTitle",
"label": "食材与搭配标题", "label": "食材与搭配标题",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.detail.detailCopy"
}, },
{ {
"key": "inquiryAction", "key": "inquiryAction",
"binding": "brand.config.visualPresentation.detail.inquiryAction", "binding": "brand.config.visualPresentation.detail.inquiryAction",
"label": "咨询按钮文字", "label": "咨询按钮文字",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.detail.detailCopy"
}, },
{ {
"key": "inquiryHint", "key": "inquiryHint",
"binding": "brand.config.visualPresentation.detail.inquiryHint", "binding": "brand.config.visualPresentation.detail.inquiryHint",
"label": "咨询后的处理说明", "label": "咨询后的处理说明",
"help": "只写能够兑现的联系和确认方式。", "help": "只写能够兑现的联系和确认方式。",
"input": "textarea" "input": "textarea",
"previewTarget": "acheng-campus-food.detail.detailCopy"
}
],
"previewTargets": [
{
"key": "acheng-campus-food.detail.detailCopy",
"label": "详情页说明"
} }
] ]
}, },
@@ -486,32 +701,43 @@
"key": "eyebrow", "key": "eyebrow",
"binding": "brand.config.visualPresentation.success.eyebrow", "binding": "brand.config.visualPresentation.success.eyebrow",
"label": "页面小标题", "label": "页面小标题",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.success.successCopy"
}, },
{ {
"key": "title", "key": "title",
"binding": "brand.config.visualPresentation.success.title", "binding": "brand.config.visualPresentation.success.title",
"label": "确认标题", "label": "确认标题",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.success.successCopy"
}, },
{ {
"key": "intro", "key": "intro",
"binding": "brand.config.visualPresentation.success.intro", "binding": "brand.config.visualPresentation.success.intro",
"label": "后续联系说明", "label": "后续联系说明",
"help": "若写回复时间,请确认日常能兑现。", "help": "若写回复时间,请确认日常能兑现。",
"input": "textarea" "input": "textarea",
"previewTarget": "acheng-campus-food.success.successCopy"
}, },
{ {
"key": "recordsAction", "key": "recordsAction",
"binding": "brand.config.visualPresentation.success.recordsAction", "binding": "brand.config.visualPresentation.success.recordsAction",
"label": "查看记录按钮", "label": "查看记录按钮",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.success.successCopy"
}, },
{ {
"key": "homeAction", "key": "homeAction",
"binding": "brand.config.visualPresentation.success.homeAction", "binding": "brand.config.visualPresentation.success.homeAction",
"label": "返回首页按钮", "label": "返回首页按钮",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.success.successCopy"
}
],
"previewTargets": [
{
"key": "acheng-campus-food.success.successCopy",
"label": "提交成功页"
} }
] ]
}, },
@@ -526,31 +752,42 @@
"key": "title", "key": "title",
"binding": "brand.config.visualPresentation.records.title", "binding": "brand.config.visualPresentation.records.title",
"label": "记录页标题", "label": "记录页标题",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.records.recordsCopy"
}, },
{ {
"key": "createAction", "key": "createAction",
"binding": "brand.config.visualPresentation.records.createAction", "binding": "brand.config.visualPresentation.records.createAction",
"label": "新增咨询按钮", "label": "新增咨询按钮",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.records.recordsCopy"
}, },
{ {
"key": "emptyTitle", "key": "emptyTitle",
"binding": "brand.config.visualPresentation.records.emptyTitle", "binding": "brand.config.visualPresentation.records.emptyTitle",
"label": "暂无记录标题", "label": "暂无记录标题",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.records.recordsCopy"
}, },
{ {
"key": "emptyDescription", "key": "emptyDescription",
"binding": "brand.config.visualPresentation.records.emptyDescription", "binding": "brand.config.visualPresentation.records.emptyDescription",
"label": "暂无记录说明", "label": "暂无记录说明",
"input": "textarea" "input": "textarea",
"previewTarget": "acheng-campus-food.records.recordsCopy"
}, },
{ {
"key": "emptyAction", "key": "emptyAction",
"binding": "brand.config.visualPresentation.records.emptyAction", "binding": "brand.config.visualPresentation.records.emptyAction",
"label": "空状态按钮", "label": "空状态按钮",
"input": "text" "input": "text",
"previewTarget": "acheng-campus-food.records.recordsCopy"
}
],
"previewTargets": [
{
"key": "acheng-campus-food.records.recordsCopy",
"label": "咨询记录页"
} }
] ]
} }
+7 -1
View File
@@ -86,7 +86,13 @@ export type TemplateAdminSection = {
page: TemplatePageKey; page: TemplatePageKey;
target: "brand" | "offering" | "trust" | "inquiry"; target: "brand" | "offering" | "trust" | "inquiry";
/** Visual regions rendered by this section's page. */ /** Visual regions rendered by this section's page. */
previewTargets?: Array<{ key: string; label: string }>; previewTargets?: Array<{
key: string;
label: string;
/** 组合区域只负责承载和导航,不重复声明可编辑字段。 */
composite?: boolean;
children?: string[];
}>;
fields: TemplateAdminField[]; fields: TemplateAdminField[];
}; };
@@ -27,17 +27,47 @@ for (const directory of templateDirectories) {
const keys = targets.map((target) => target.key); const keys = targets.map((target) => target.key);
assert.equal(new Set(keys).size, keys.length, "preview target keys must be unique"); assert.equal(new Set(keys).size, keys.length, "preview target keys must be unique");
for (const { section } of targets) { for (const section of sections) {
for (const field of section.fields) { for (const field of section.fields) {
if (field.previewTarget) 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( assert.ok(
section.previewTargets.some((target) => target.key === field.previewTarget), section.previewTargets?.some((target) => target.key === field.previewTarget),
`${section.key}.${field.key} references an undeclared previewTarget`, `${section.key}.${field.key} references an undeclared previewTarget`,
); );
} }
for (const target of section.previewTargets ?? []) {
if (target.composite) {
assert.ok(
Array.isArray(target.children) && target.children.length > 0,
`${target.key} composite target must declare child targets`,
);
for (const child of target.children)
assert.ok(
section.previewTargets?.some(
(candidate) => candidate.key === child && !candidate.composite,
),
`${target.key} references missing or composite child ${child}`,
);
assert.ok(
!section.fields.some((field) => field.previewTarget === target.key),
`${target.key} composite target must not duplicate editable fields`,
);
}
}
}
for (const field of manifest.templateFields ?? []) {
assert.ok(field.binding, `templateFields.${field.key} must have an editable binding`);
assert.ok(field.previewTarget, `templateFields.${field.key} must map to a visual region`);
assert.ok(
targets.some((target) => target.key === field.previewTarget),
`templateFields.${field.key} references an undeclared previewTarget`,
);
assert.ok(rendererPath && fs.existsSync(rendererPath));
} }
for (const target of targets) for (const target of targets)
if (!target.composite)
assert.ok( assert.ok(
target.section.fields.some((field) => field.previewTarget === target.key), target.section.fields.some((field) => field.previewTarget === target.key),
`${target.key} must map to at least one editable field`, `${target.key} must map to at least one editable field`,
@@ -48,8 +78,44 @@ for (const directory of templateDirectories) {
const renderer = fs.readFileSync(rendererPath, "utf8"); const renderer = fs.readFileSync(rendererPath, "utf8");
for (const target of targets) for (const target of targets)
assert.ok( assert.ok(
renderer.includes(`data-editor-target="${target.key}"`), renderer.includes(`data-editor-target="${target.key}"`) ||
renderer.includes(`data-editor-target={\`${target.key}`) ||
renderer.includes(`data-editor-target={formTargets[`),
`renderer is missing data-editor-target ${target.key}`, `renderer is missing data-editor-target ${target.key}`,
); );
assert.ok(renderer.includes("data-editor-target"), "renderer must expose editor targets");
const hasDynamicTrustTarget = /data-editor-target=\{`trust:\$\{item\.type\}`\}/.test(renderer);
const literalRendererTargets = new Set(
[...renderer.matchAll(/data-editor-target="([^"]+)"/g)]
.map((match) => match[1])
.filter((key) => !key.startsWith("trust:")),
);
for (const renderedKey of literalRendererTargets)
assert.ok(
keys.includes(renderedKey),
`renderer target ${renderedKey} is missing from manifest`,
);
const concreteTrustTypes = new Set(
[...literalRendererTargets]
.filter((key) => key.startsWith("trust:"))
.map((key) => key.slice("trust:".length)),
);
for (const type of concreteTrustTypes) {
const key = `trust:${type}`;
assert.ok(
(manifest.trustContentTypes ?? []).some((item) => item.type === type),
`renderer trust target ${key} has no trust type declaration`,
);
assert.ok(
targets.some((target) => target.key === key),
`renderer trust target ${key} is missing from Admin declarations`,
);
}
if (hasDynamicTrustTarget)
assert.ok(
manifest.trustContentTypes?.length,
"dynamic trust targets need trust type declarations",
);
}); });
} }
@@ -19,7 +19,7 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
const credential = slot(workspace, "credential"); const credential = slot(workspace, "credential");
const t = workspace.trustPresentation; const t = workspace.trustPresentation;
return ( return (
<View className="editorial-home"> <View className="editorial-home" data-editor-target="linjing-editorial.home.home">
<View className="page"> <View className="page">
<View className="founder-card" data-editor-target="editorial.home.identity"> <View className="founder-card" data-editor-target="editorial.home.identity">
{text(b.avatarUrl) && ( {text(b.avatarUrl) && (
@@ -53,7 +53,13 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
<View className="intro" data-editor-target="editorial.home.proof"> <View className="intro" data-editor-target="editorial.home.proof">
<Text className="eyebrow dark">{p.proofEyebrow}</Text> <Text className="eyebrow dark">{p.proofEyebrow}</Text>
<Text className="section-title">{p.proofTitle}</Text> <Text className="section-title">{p.proofTitle}</Text>
<Text className="body">{credential?.content}</Text> <Text
className="body"
data-editor-target="trust:credential"
data-editor-record-id={credential?.id}
>
{credential?.content}
</Text>
<View className="stats"> <View className="stats">
{t.stats?.map((item, index) => ( {t.stats?.map((item, index) => (
<View key={index}> <View key={index}>
@@ -88,6 +94,8 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
<View <View
className="work-card" className="work-card"
key={item.id} key={item.id}
data-editor-target="linjing-editorial.home.offering"
data-editor-record-id={item.id}
onClick={() => navigate("detail", { id: item.id })} onClick={() => navigate("detail", { id: item.id })}
> >
<Image src={item.image} mode="aspectFill" /> <Image src={item.image} mode="aspectFill" />
@@ -125,9 +133,12 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
const p = presentation(workspace, "profile"); const p = presentation(workspace, "profile");
const config = object(b.profilePresentation); const config = object(b.profilePresentation);
return ( return (
<View className="editorial-profile"> <View
className="editorial-profile"
data-editor-target="linjing-editorial.profile.profileDetails"
>
<View className="profile"> <View className="profile">
<View className="founder-card"> <View className="founder-card" data-editor-target="linjing-editorial.profile.identity">
<View className="identity"> <View className="identity">
{text(b.avatarUrl) && ( {text(b.avatarUrl) && (
<Image className="avatar" src={text(b.avatarUrl)} mode="aspectFill" /> <Image className="avatar" src={text(b.avatarUrl)} mode="aspectFill" />
@@ -202,7 +213,12 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
</View> </View>
)} )}
{workspace.trustItems.map((item) => ( {workspace.trustItems.map((item) => (
<View className="info-card trust-card" key={item.id}> <View
className="info-card trust-card"
key={item.id}
data-editor-target={`trust:${item.type}`}
data-editor-record-id={item.id}
>
<View className="card-title">{item.title}</View> <View className="card-title">{item.title}</View>
{item.summary && <Text className="trust-summary">{item.summary}</Text>} {item.summary && <Text className="trust-summary">{item.summary}</Text>}
<Text>{item.content}</Text> <Text>{item.content}</Text>
@@ -215,7 +231,7 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
function List({ workspace }: { workspace: RuntimeWorkspace }) { function List({ workspace }: { workspace: RuntimeWorkspace }) {
const p = presentation(workspace, "offerings"); const p = presentation(workspace, "offerings");
return ( return (
<View className="editorial-list"> <View className="editorial-list" data-editor-target="linjing-editorial.offerings.cases">
<View className="page"> <View className="page">
<Text className="eyebrow">{p.eyebrow}</Text> <Text className="eyebrow">{p.eyebrow}</Text>
<Text className="section-title">{p.title || "作品与服务"}</Text> <Text className="section-title">{p.title || "作品与服务"}</Text>
@@ -224,6 +240,8 @@ function List({ workspace }: { workspace: RuntimeWorkspace }) {
<View <View
className="work-card" className="work-card"
key={item.id} key={item.id}
data-editor-target="linjing-editorial.offerings.item"
data-editor-record-id={item.id}
onClick={() => navigate("detail", { id: item.id })} onClick={() => navigate("detail", { id: item.id })}
> >
<Image src={item.image} mode="aspectFill" /> <Image src={item.image} mode="aspectFill" />
@@ -255,7 +273,11 @@ function Detail({ workspace, id }: { workspace: RuntimeWorkspace; id?: string })
const item = offering(found); const item = offering(found);
const p = presentation(workspace, "detail"); const p = presentation(workspace, "detail");
return ( return (
<View className="editorial-detail"> <View
className="editorial-detail"
data-editor-target="linjing-editorial.detail.projectDetail"
data-editor-record-id={item.id}
>
<View className="detail"> <View className="detail">
<View className="hero-wrap"> <View className="hero-wrap">
<Image <Image
@@ -272,7 +294,7 @@ function Detail({ workspace, id }: { workspace: RuntimeWorkspace; id?: string })
<Text>{item.series}</Text> <Text>{item.series}</Text>
</View> </View>
</View> </View>
<View className="content"> <View className="content" data-editor-target="linjing-editorial.detail.detailCopy">
<View className="price-card"> <View className="price-card">
<View> <View>
<Text>{p.priceLabel}</Text> <Text>{p.priceLabel}</Text>
@@ -333,10 +355,19 @@ function Detail({ workspace, id }: { workspace: RuntimeWorkspace; id?: string })
</View> </View>
); );
} }
const formTargets: Record<string, string> = {
inquiry: "linjing-editorial.inquiry.consultation",
success: "linjing-editorial.success.successCopy",
records: "linjing-editorial.records.recordsCopy",
};
export function TemplatePage({ workspace, page, children, offeringId }: TemplateProps) { export function TemplatePage({ workspace, page, children, offeringId }: TemplateProps) {
if (page === "home") return <Home workspace={workspace} />; if (page === "home") return <Home workspace={workspace} />;
if (page === "offerings") return <List workspace={workspace} />; if (page === "offerings") return <List workspace={workspace} />;
if (page === "profile" || page === "service") return <Profile workspace={workspace} />; if (page === "profile" || page === "service") return <Profile workspace={workspace} />;
if (page === "detail") return <Detail workspace={workspace} id={offeringId} />; if (page === "detail") return <Detail workspace={workspace} id={offeringId} />;
return <View className="editorial-forms">{children}</View>; return (
<View className="editorial-forms" data-editor-target={formTargets[page]}>
{children}
</View>
);
} }
+464 -102
View File
@@ -86,6 +86,8 @@
{ {
"key": "designPhilosophy", "key": "designPhilosophy",
"page": "home", "page": "home",
"binding": "brand.config.templateData.designPhilosophy",
"previewTarget": "linjing-editorial.home.home",
"label": "设计理念", "label": "设计理念",
"help": "用一两句话说明你的设计方法。", "help": "用一两句话说明你的设计方法。",
"input": "textarea", "input": "textarea",
@@ -139,7 +141,8 @@
"binding": "brand.config.founder", "binding": "brand.config.founder",
"label": "主理人姓名", "label": "主理人姓名",
"input": "text", "input": "text",
"required": true "required": true,
"previewTarget": "linjing-editorial.profile.identity"
}, },
{ {
"key": "title", "key": "title",
@@ -147,7 +150,57 @@
"label": "身份或职位", "label": "身份或职位",
"input": "text", "input": "text",
"required": true, "required": true,
"placeholder": "例如:别墅门系统主理人" "placeholder": "例如:别墅门系统主理人",
"previewTarget": "linjing-editorial.profile.identity"
}
],
"previewTargets": [
{
"key": "linjing-editorial.profile.identity",
"label": "主理人与联系方式"
}
]
},
{
"key": "homeOffering",
"title": "首页业务卡片",
"description": "点选预览中的单条内容,修改对应业务记录。",
"page": "home",
"target": "offering",
"fields": [
{
"key": "name",
"binding": "offering.name",
"label": "名称",
"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"
}
],
"previewTargets": [
{
"key": "linjing-editorial.home.offering",
"label": "首页业务卡片"
} }
] ]
}, },
@@ -158,11 +211,30 @@
"page": "home", "page": "home",
"target": "brand", "target": "brand",
"previewTargets": [ "previewTargets": [
{ "key": "editorial.home.identity", "label": "主理人标签" }, {
{ "key": "editorial.home.hero", "label": "首页主视觉" }, "key": "editorial.home.identity",
{ "key": "editorial.home.proof", "label": "信任介绍" }, "label": "主理人标签"
{ "key": "editorial.home.manifesto", "label": "品牌主张" }, },
{ "key": "editorial.home.works", "label": "代表案例标题" } {
"key": "editorial.home.hero",
"label": "首页主视觉"
},
{
"key": "editorial.home.proof",
"label": "信任介绍"
},
{
"key": "editorial.home.manifesto",
"label": "品牌主张"
},
{
"key": "editorial.home.works",
"label": "代表案例标题"
},
{
"key": "linjing-editorial.home.home",
"label": "首页品牌表达"
}
], ],
"fields": [ "fields": [
{ {
@@ -228,43 +300,50 @@
"key": "worksAction", "key": "worksAction",
"binding": "brand.config.visualPresentation.home.worksAction", "binding": "brand.config.visualPresentation.home.worksAction",
"label": "查看案例入口", "label": "查看案例入口",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.home.home"
}, },
{ {
"key": "flowEyebrow", "key": "flowEyebrow",
"binding": "brand.config.visualPresentation.home.flowEyebrow", "binding": "brand.config.visualPresentation.home.flowEyebrow",
"label": "合作流程小标题", "label": "合作流程小标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.home.home"
}, },
{ {
"key": "flowTitle", "key": "flowTitle",
"binding": "brand.config.visualPresentation.home.flowTitle", "binding": "brand.config.visualPresentation.home.flowTitle",
"label": "项目流程标题", "label": "项目流程标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.home.home"
}, },
{ {
"key": "heroTitle", "key": "heroTitle",
"binding": "brand.config.homeHero.title", "binding": "brand.config.homeHero.title",
"label": "首页主标题", "label": "首页主标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.home.home"
}, },
{ {
"key": "heroEyebrow", "key": "heroEyebrow",
"binding": "brand.config.homeHero.eyebrow", "binding": "brand.config.homeHero.eyebrow",
"label": "主图项目标注", "label": "主图项目标注",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.home.home"
}, },
{ {
"key": "heroDescription", "key": "heroDescription",
"binding": "brand.config.homeHero.slogan", "binding": "brand.config.homeHero.slogan",
"label": "首页主图说明", "label": "首页主图说明",
"input": "textarea" "input": "textarea",
"previewTarget": "linjing-editorial.home.home"
}, },
{ {
"key": "heroAction", "key": "heroAction",
"binding": "brand.config.homeHero.cta", "binding": "brand.config.homeHero.cta",
"label": "主图行动文字", "label": "主图行动文字",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.home.home"
} }
] ]
}, },
@@ -281,9 +360,17 @@
"label": "服务区域", "label": "服务区域",
"input": "list", "input": "list",
"itemFields": [ "itemFields": [
{ "key": "title", "label": "区域名称" }, {
{ "key": "content", "label": "服务说明", "input": "textarea" } "key": "title",
] "label": "区域名称"
},
{
"key": "content",
"label": "服务说明",
"input": "textarea"
}
],
"previewTarget": "linjing-editorial.profile.profileDetails"
}, },
{ {
"key": "warranty", "key": "warranty",
@@ -291,67 +378,133 @@
"label": "履约与维护说明", "label": "履约与维护说明",
"input": "list", "input": "list",
"itemValueKey": "value", "itemValueKey": "value",
"itemFields": [{ "key": "value", "label": "承诺内容", "input": "textarea" }] "itemFields": [
{
"key": "value",
"label": "承诺内容",
"input": "textarea"
}
],
"previewTarget": "linjing-editorial.profile.profileDetails"
}, },
{ {
"key": "recordsTitle", "key": "recordsTitle",
"binding": "brand.config.visualPresentation.profile.recordsTitle", "binding": "brand.config.visualPresentation.profile.recordsTitle",
"label": "咨询记录入口标题", "label": "咨询记录入口标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
}, },
{ {
"key": "recordsSubtitle", "key": "recordsSubtitle",
"binding": "brand.config.visualPresentation.profile.recordsSubtitle", "binding": "brand.config.visualPresentation.profile.recordsSubtitle",
"label": "咨询记录入口说明", "label": "咨询记录入口说明",
"input": "textarea" "input": "textarea",
"previewTarget": "linjing-editorial.profile.profileDetails"
}, },
{ {
"key": "coverageTitle", "key": "coverageTitle",
"binding": "brand.config.visualPresentation.profile.coverageTitle", "binding": "brand.config.visualPresentation.profile.coverageTitle",
"label": "服务区域标题", "label": "服务区域标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
}, },
{ {
"key": "warrantyTitle", "key": "warrantyTitle",
"binding": "brand.config.visualPresentation.profile.warrantyTitle", "binding": "brand.config.visualPresentation.profile.warrantyTitle",
"label": "履约说明标题", "label": "履约说明标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
}, },
{ {
"key": "phoneLabel", "key": "phoneLabel",
"binding": "brand.config.visualPresentation.profile.phoneLabel", "binding": "brand.config.visualPresentation.profile.phoneLabel",
"label": "电话标签", "label": "电话标签",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
}, },
{ {
"key": "wechatLabel", "key": "wechatLabel",
"binding": "brand.config.visualPresentation.profile.wechatLabel", "binding": "brand.config.visualPresentation.profile.wechatLabel",
"label": "微信标签", "label": "微信标签",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
}, },
{ {
"key": "addressLabel", "key": "addressLabel",
"binding": "brand.config.visualPresentation.profile.addressLabel", "binding": "brand.config.visualPresentation.profile.addressLabel",
"label": "地址标签", "label": "地址标签",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
}, },
{ {
"key": "callAction", "key": "callAction",
"binding": "brand.config.visualPresentation.profile.callAction", "binding": "brand.config.visualPresentation.profile.callAction",
"label": "拨打电话按钮", "label": "拨打电话按钮",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
}, },
{ {
"key": "copyAction", "key": "copyAction",
"binding": "brand.config.visualPresentation.profile.copyAction", "binding": "brand.config.visualPresentation.profile.copyAction",
"label": "复制微信按钮", "label": "复制微信按钮",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
}, },
{ {
"key": "recordsCountUnit", "key": "recordsCountUnit",
"binding": "brand.config.visualPresentation.profile.recordsCountUnit", "binding": "brand.config.visualPresentation.profile.recordsCountUnit",
"label": "记录数量单位", "label": "记录数量单位",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.profile.profileDetails"
}
],
"previewTargets": [
{
"key": "linjing-editorial.profile.profileDetails",
"label": "服务区域与履约说明"
}
]
},
{
"key": "offeringsOffering",
"title": "业务卡片",
"description": "点选预览中的单条内容,修改对应业务记录。",
"page": "offerings",
"target": "offering",
"fields": [
{
"key": "name",
"binding": "offering.name",
"label": "名称",
"input": "text",
"previewTarget": "linjing-editorial.offerings.item"
},
{
"key": "summary",
"binding": "offering.summary",
"label": "简介",
"input": "textarea",
"previewTarget": "linjing-editorial.offerings.item"
},
{
"key": "priceText",
"binding": "offering.priceText",
"label": "价格说明",
"input": "text",
"previewTarget": "linjing-editorial.offerings.item"
},
{
"key": "coverUrl",
"binding": "offering.coverUrl",
"label": "封面图片",
"input": "image",
"previewTarget": "linjing-editorial.offerings.item"
}
],
"previewTargets": [
{
"key": "linjing-editorial.offerings.item",
"label": "业务卡片"
} }
] ]
}, },
@@ -366,32 +519,43 @@
"key": "worksEyebrow", "key": "worksEyebrow",
"binding": "brand.config.visualPresentation.offerings.worksEyebrow", "binding": "brand.config.visualPresentation.offerings.worksEyebrow",
"label": "案例页辅助标题", "label": "案例页辅助标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.offerings.cases"
}, },
{ {
"key": "worksTitle", "key": "worksTitle",
"binding": "brand.config.visualPresentation.offerings.worksTitle", "binding": "brand.config.visualPresentation.offerings.worksTitle",
"label": "案例页主标题", "label": "案例页主标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.offerings.cases"
}, },
{ {
"key": "subtitle", "key": "subtitle",
"binding": "brand.config.visualPresentation.offerings.subtitle", "binding": "brand.config.visualPresentation.offerings.subtitle",
"label": "案例页说明", "label": "案例页说明",
"input": "textarea", "input": "textarea",
"maxLength": 140 "maxLength": 140,
"previewTarget": "linjing-editorial.offerings.cases"
}, },
{ {
"key": "closingText", "key": "closingText",
"binding": "brand.config.visualPresentation.offerings.closingText", "binding": "brand.config.visualPresentation.offerings.closingText",
"label": "案例页结语", "label": "案例页结语",
"input": "textarea" "input": "textarea",
"previewTarget": "linjing-editorial.offerings.cases"
}, },
{ {
"key": "closingAction", "key": "closingAction",
"binding": "brand.config.visualPresentation.offerings.closingAction", "binding": "brand.config.visualPresentation.offerings.closingAction",
"label": "案例页咨询入口", "label": "案例页咨询入口",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.offerings.cases"
}
],
"previewTargets": [
{
"key": "linjing-editorial.offerings.cases",
"label": "案例与体系"
} }
] ]
}, },
@@ -406,32 +570,43 @@
"key": "title", "key": "title",
"binding": "brand.config.visualPresentation.inquiry.title", "binding": "brand.config.visualPresentation.inquiry.title",
"label": "咨询页面标题", "label": "咨询页面标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.inquiry.consultation"
}, },
{ {
"key": "subtitle", "key": "subtitle",
"binding": "brand.config.visualPresentation.inquiry.subtitle", "binding": "brand.config.visualPresentation.inquiry.subtitle",
"label": "咨询说明", "label": "咨询说明",
"input": "textarea", "input": "textarea",
"maxLength": 140 "maxLength": 140,
"previewTarget": "linjing-editorial.inquiry.consultation"
}, },
{ {
"key": "submitLabel", "key": "submitLabel",
"binding": "brand.config.visualPresentation.inquiry.submitLabel", "binding": "brand.config.visualPresentation.inquiry.submitLabel",
"label": "提交按钮文字", "label": "提交按钮文字",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.inquiry.consultation"
}, },
{ {
"key": "eyebrow", "key": "eyebrow",
"binding": "brand.config.visualPresentation.inquiry.eyebrow", "binding": "brand.config.visualPresentation.inquiry.eyebrow",
"label": "咨询页小标题", "label": "咨询页小标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.inquiry.consultation"
}, },
{ {
"key": "note", "key": "note",
"binding": "brand.config.visualPresentation.inquiry.note", "binding": "brand.config.visualPresentation.inquiry.note",
"label": "咨询前提示", "label": "咨询前提示",
"input": "textarea" "input": "textarea",
"previewTarget": "linjing-editorial.inquiry.consultation"
}
],
"previewTargets": [
{
"key": "linjing-editorial.inquiry.consultation",
"label": "咨询说明"
} }
] ]
}, },
@@ -446,43 +621,50 @@
"key": "categoryLabel", "key": "categoryLabel",
"binding": "offering.config.categoryLabel", "binding": "offering.config.categoryLabel",
"label": "案例类别", "label": "案例类别",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.detail.projectDetail"
}, },
{ {
"key": "detailHero", "key": "detailHero",
"binding": "offering.config.detailHero", "binding": "offering.config.detailHero",
"label": "详情主图", "label": "详情主图",
"input": "image" "input": "image",
"previewTarget": "linjing-editorial.detail.projectDetail"
}, },
{ {
"key": "area", "key": "area",
"binding": "offering.config.area", "binding": "offering.config.area",
"label": "项目地点", "label": "项目地点",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.detail.projectDetail"
}, },
{ {
"key": "series", "key": "series",
"binding": "offering.config.series", "binding": "offering.config.series",
"label": "产品系列", "label": "产品系列",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.detail.projectDetail"
}, },
{ {
"key": "spaceType", "key": "spaceType",
"binding": "offering.config.spaceType", "binding": "offering.config.spaceType",
"label": "适用空间", "label": "适用空间",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.detail.projectDetail"
}, },
{ {
"key": "background", "key": "background",
"binding": "offering.config.details.background", "binding": "offering.config.details.background",
"label": "项目背景", "label": "项目背景",
"input": "textarea" "input": "textarea",
"previewTarget": "linjing-editorial.detail.projectDetail"
}, },
{ {
"key": "designConcept", "key": "designConcept",
"binding": "offering.config.details.designConcept", "binding": "offering.config.details.designConcept",
"label": "设计理念", "label": "设计理念",
"input": "textarea" "input": "textarea",
"previewTarget": "linjing-editorial.detail.projectDetail"
}, },
{ {
"key": "keywords", "key": "keywords",
@@ -490,7 +672,13 @@
"label": "项目关键词", "label": "项目关键词",
"input": "list", "input": "list",
"itemValueKey": "value", "itemValueKey": "value",
"itemFields": [{ "key": "value", "label": "关键词" }] "itemFields": [
{
"key": "value",
"label": "关键词"
}
],
"previewTarget": "linjing-editorial.detail.projectDetail"
}, },
{ {
"key": "crafts", "key": "crafts",
@@ -498,7 +686,13 @@
"label": "工艺要点", "label": "工艺要点",
"input": "list", "input": "list",
"itemValueKey": "value", "itemValueKey": "value",
"itemFields": [{ "key": "value", "label": "工艺说明" }] "itemFields": [
{
"key": "value",
"label": "工艺说明"
}
],
"previewTarget": "linjing-editorial.detail.projectDetail"
}, },
{ {
"key": "materialsList", "key": "materialsList",
@@ -506,9 +700,22 @@
"label": "材料说明", "label": "材料说明",
"input": "list", "input": "list",
"itemFields": [ "itemFields": [
{ "key": "name", "label": "材料名称" }, {
{ "key": "spec", "label": "规格说明" } "key": "name",
] "label": "材料名称"
},
{
"key": "spec",
"label": "规格说明"
}
],
"previewTarget": "linjing-editorial.detail.projectDetail"
}
],
"previewTargets": [
{
"key": "linjing-editorial.detail.projectDetail",
"label": "案例详情"
} }
] ]
}, },
@@ -523,50 +730,64 @@
"key": "priceLabel", "key": "priceLabel",
"binding": "brand.config.visualPresentation.detail.priceLabel", "binding": "brand.config.visualPresentation.detail.priceLabel",
"label": "价格说明标题", "label": "价格说明标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.detail.detailCopy"
}, },
{ {
"key": "spaceLabel", "key": "spaceLabel",
"binding": "brand.config.visualPresentation.detail.spaceLabel", "binding": "brand.config.visualPresentation.detail.spaceLabel",
"label": "适用空间标题", "label": "适用空间标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.detail.detailCopy"
}, },
{ {
"key": "backgroundTitle", "key": "backgroundTitle",
"binding": "brand.config.visualPresentation.detail.backgroundTitle", "binding": "brand.config.visualPresentation.detail.backgroundTitle",
"label": "项目背景标题", "label": "项目背景标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.detail.detailCopy"
}, },
{ {
"key": "conceptTitle", "key": "conceptTitle",
"binding": "brand.config.visualPresentation.detail.conceptTitle", "binding": "brand.config.visualPresentation.detail.conceptTitle",
"label": "设计理念标题", "label": "设计理念标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.detail.detailCopy"
}, },
{ {
"key": "craftsTitle", "key": "craftsTitle",
"binding": "brand.config.visualPresentation.detail.craftsTitle", "binding": "brand.config.visualPresentation.detail.craftsTitle",
"label": "工艺要点标题", "label": "工艺要点标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.detail.detailCopy"
}, },
{ {
"key": "materialsTitle", "key": "materialsTitle",
"binding": "brand.config.visualPresentation.detail.materialsTitle", "binding": "brand.config.visualPresentation.detail.materialsTitle",
"label": "材料说明标题", "label": "材料说明标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.detail.detailCopy"
}, },
{ {
"key": "inquiryAction", "key": "inquiryAction",
"binding": "brand.config.visualPresentation.detail.inquiryAction", "binding": "brand.config.visualPresentation.detail.inquiryAction",
"label": "咨询按钮文字", "label": "咨询按钮文字",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.detail.detailCopy"
}, },
{ {
"key": "inquiryHint", "key": "inquiryHint",
"binding": "brand.config.visualPresentation.detail.inquiryHint", "binding": "brand.config.visualPresentation.detail.inquiryHint",
"label": "咨询后的处理说明", "label": "咨询后的处理说明",
"help": "只填写能兑现的服务安排。", "help": "只填写能兑现的服务安排。",
"input": "textarea" "input": "textarea",
"previewTarget": "linjing-editorial.detail.detailCopy"
}
],
"previewTargets": [
{
"key": "linjing-editorial.detail.detailCopy",
"label": "详情页说明"
} }
] ]
}, },
@@ -581,32 +802,43 @@
"key": "eyebrow", "key": "eyebrow",
"binding": "brand.config.visualPresentation.success.eyebrow", "binding": "brand.config.visualPresentation.success.eyebrow",
"label": "页面小标题", "label": "页面小标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.success.successCopy"
}, },
{ {
"key": "title", "key": "title",
"binding": "brand.config.visualPresentation.success.title", "binding": "brand.config.visualPresentation.success.title",
"label": "确认标题", "label": "确认标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.success.successCopy"
}, },
{ {
"key": "intro", "key": "intro",
"binding": "brand.config.visualPresentation.success.intro", "binding": "brand.config.visualPresentation.success.intro",
"label": "后续联系说明", "label": "后续联系说明",
"help": "回复时间必须与实际承诺一致。", "help": "回复时间必须与实际承诺一致。",
"input": "textarea" "input": "textarea",
"previewTarget": "linjing-editorial.success.successCopy"
}, },
{ {
"key": "recordsAction", "key": "recordsAction",
"binding": "brand.config.visualPresentation.success.recordsAction", "binding": "brand.config.visualPresentation.success.recordsAction",
"label": "查看记录按钮", "label": "查看记录按钮",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.success.successCopy"
}, },
{ {
"key": "homeAction", "key": "homeAction",
"binding": "brand.config.visualPresentation.success.homeAction", "binding": "brand.config.visualPresentation.success.homeAction",
"label": "返回首页按钮", "label": "返回首页按钮",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.success.successCopy"
}
],
"previewTargets": [
{
"key": "linjing-editorial.success.successCopy",
"label": "提交成功页"
} }
] ]
}, },
@@ -621,31 +853,42 @@
"key": "title", "key": "title",
"binding": "brand.config.visualPresentation.records.title", "binding": "brand.config.visualPresentation.records.title",
"label": "记录页标题", "label": "记录页标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.records.recordsCopy"
}, },
{ {
"key": "createAction", "key": "createAction",
"binding": "brand.config.visualPresentation.records.createAction", "binding": "brand.config.visualPresentation.records.createAction",
"label": "新增咨询按钮", "label": "新增咨询按钮",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.records.recordsCopy"
}, },
{ {
"key": "emptyTitle", "key": "emptyTitle",
"binding": "brand.config.visualPresentation.records.emptyTitle", "binding": "brand.config.visualPresentation.records.emptyTitle",
"label": "暂无记录标题", "label": "暂无记录标题",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.records.recordsCopy"
}, },
{ {
"key": "emptyDescription", "key": "emptyDescription",
"binding": "brand.config.visualPresentation.records.emptyDescription", "binding": "brand.config.visualPresentation.records.emptyDescription",
"label": "暂无记录说明", "label": "暂无记录说明",
"input": "textarea" "input": "textarea",
"previewTarget": "linjing-editorial.records.recordsCopy"
}, },
{ {
"key": "emptyAction", "key": "emptyAction",
"binding": "brand.config.visualPresentation.records.emptyAction", "binding": "brand.config.visualPresentation.records.emptyAction",
"label": "空状态按钮", "label": "空状态按钮",
"input": "text" "input": "text",
"previewTarget": "linjing-editorial.records.recordsCopy"
}
],
"previewTargets": [
{
"key": "linjing-editorial.records.recordsCopy",
"label": "咨询记录页"
} }
] ]
} }
@@ -655,21 +898,33 @@
{ {
"type": "schedule", "type": "schedule",
"label": "服务与合作安排", "label": "服务与合作安排",
"adminFields": { "title": "安排标题", "summary": "安排摘要", "content": "时间与排期详情" }, "adminFields": {
"title": "安排标题",
"summary": "安排摘要",
"content": "时间与排期详情"
},
"pages": ["profile"], "pages": ["profile"],
"help": "说明可预约时间、服务周期或项目排期。" "help": "说明可预约时间、服务周期或项目排期。"
}, },
{ {
"type": "coverage", "type": "coverage",
"label": "服务范围与适用对象", "label": "服务范围与适用对象",
"adminFields": { "title": "范围标题", "summary": "范围摘要", "content": "服务范围说明" }, "adminFields": {
"title": "范围标题",
"summary": "范围摘要",
"content": "服务范围说明"
},
"pages": ["profile"], "pages": ["profile"],
"help": "说明服务地区、项目类型或合作边界。" "help": "说明服务地区、项目类型或合作边界。"
}, },
{ {
"type": "process", "type": "process",
"label": "合作流程", "label": "合作流程",
"adminFields": { "title": "流程标题", "summary": "流程摘要", "content": "流程步骤" }, "adminFields": {
"title": "流程标题",
"summary": "流程摘要",
"content": "流程步骤"
},
"pages": ["profile"], "pages": ["profile"],
"help": "每行写一步,从初次沟通到交付完成。", "help": "每行写一步,从初次沟通到交付完成。",
"placeholder": "例如:需求沟通\n方案确认\n落地交付", "placeholder": "例如:需求沟通\n方案确认\n落地交付",
@@ -678,7 +933,11 @@
{ {
"type": "credential", "type": "credential",
"label": "专业资历与方法", "label": "专业资历与方法",
"adminFields": { "title": "证明标题", "summary": "专业摘要", "content": "资历与方法说明" }, "adminFields": {
"title": "证明标题",
"summary": "专业摘要",
"content": "资历与方法说明"
},
"pages": ["home", "profile"], "pages": ["home", "profile"],
"help": "填写经验、资质、专业标准或工作方法。", "help": "填写经验、资质、专业标准或工作方法。",
"configFields": [ "configFields": [
@@ -688,9 +947,19 @@
"label": "信任数据", "label": "信任数据",
"input": "list", "input": "list",
"itemFields": [ "itemFields": [
{ "key": "value", "label": "数字或成果" }, {
{ "key": "label", "label": "说明" }, "key": "value",
{ "key": "sub", "label": "补充说明", "required": false } "label": "数字或成果"
},
{
"key": "label",
"label": "说明"
},
{
"key": "sub",
"label": "补充说明",
"required": false
}
] ]
}, },
{ {
@@ -699,8 +968,14 @@
"label": "专业方法", "label": "专业方法",
"input": "list", "input": "list",
"itemFields": [ "itemFields": [
{ "key": "title", "label": "方法名称" }, {
{ "key": "desc", "label": "方法说明" } "key": "title",
"label": "方法名称"
},
{
"key": "desc",
"label": "方法说明"
}
] ]
}, },
{ {
@@ -709,9 +984,18 @@
"label": "合作流程", "label": "合作流程",
"input": "list", "input": "list",
"itemFields": [ "itemFields": [
{ "key": "step", "label": "步骤编号" }, {
{ "key": "name", "label": "步骤名称" }, "key": "step",
{ "key": "desc", "label": "步骤说明" } "label": "步骤编号"
},
{
"key": "name",
"label": "步骤名称"
},
{
"key": "desc",
"label": "步骤说明"
}
] ]
} }
], ],
@@ -731,7 +1015,11 @@
{ {
"type": "promise", "type": "promise",
"label": "合作预期与响应承诺", "label": "合作预期与响应承诺",
"adminFields": { "title": "承诺标题", "summary": "承诺摘要", "content": "合作与响应说明" }, "adminFields": {
"title": "承诺标题",
"summary": "承诺摘要",
"content": "合作与响应说明"
},
"pages": ["profile"], "pages": ["profile"],
"help": "说明回复时间、合作边界和后续跟进方式。" "help": "说明回复时间、合作边界和后续跟进方式。"
} }
@@ -777,7 +1065,11 @@
"title": "别墅门系统案例", "title": "别墅门系统案例",
"content": "示例内容,待品牌主理人完善。" "content": "示例内容,待品牌主理人完善。"
}, },
{ "type": "process", "title": "从测量到交付", "content": "示例内容,待品牌主理人完善。" }, {
"type": "process",
"title": "从测量到交付",
"content": "示例内容,待品牌主理人完善。"
},
{ {
"type": "credential", "type": "credential",
"title": "材料与工艺标准", "title": "材料与工艺标准",
@@ -791,11 +1083,26 @@
"type": "select", "type": "select",
"required": true, "required": true,
"options": [ "options": [
{ "label": "入户大门(防暴铸铜 / 实木)", "value": "入户大门(防暴铸铜 / 实木)" }, {
{ "label": "庭院围墙门(耐候格栅 / 对开)", "value": "庭院围墙门(耐候格栅 / 对开)" }, "label": "入户大门(防暴铸铜 / 实木)",
{ "label": "全屋室内门系统(通顶隐形)", "value": "全屋室内门系统(通顶隐形)" }, "value": "入户大门(防暴铸铜 / 实木)"
{ "label": "背景墙一体门 / 密室门", "value": "背景墙一体门 / 密室门" }, },
{ "label": "整栋别墅门系统全案一体化", "value": "整栋别墅门系统全案一体化" } {
"label": "庭院围墙门(耐候格栅 / 对开)",
"value": "庭院围墙门(耐候格栅 / 对开)"
},
{
"label": "全屋室内门系统(通顶隐形)",
"value": "全屋室内门系统(通顶隐形)"
},
{
"label": "背景墙一体门 / 密室门",
"value": "背景墙一体门 / 密室门"
},
{
"label": "整栋别墅门系统全案一体化",
"value": "整栋别墅门系统全案一体化"
}
] ]
}, },
{ {
@@ -810,10 +1117,22 @@
"type": "select", "type": "select",
"required": true, "required": true,
"options": [ "options": [
{ "label": "土建结构阶段(适合预埋加固)", "value": "土建结构阶段(适合预埋加固)" }, {
{ "label": "水电木工阶段(适合精确测距)", "value": "水电木工阶段(适合精确测距)" }, "label": "土建结构阶段(适合预埋加固)",
{ "label": "硬装收尾阶段", "value": "硬装收尾阶段" }, "value": "土建结构阶段(适合预埋加固)"
{ "label": "旧宅门体翻新改造", "value": "旧宅门体翻新改造" } },
{
"label": "水电木工阶段(适合精确测距)",
"value": "水电木工阶段(适合精确测距)"
},
{
"label": "硬装收尾阶段",
"value": "硬装收尾阶段"
},
{
"label": "旧宅门体翻新改造",
"value": "旧宅门体翻新改造"
}
] ]
}, },
{ {
@@ -822,10 +1141,22 @@
"type": "select", "type": "select",
"required": false, "required": false,
"options": [ "options": [
{ "label": "5 万 - 10 万", "value": "5 万 - 10 万" }, {
{ "label": "10 万 - 20 万", "value": "10 万 - 20 万" }, "label": "5 万 - 10 万",
{ "label": "20 万 - 50 万(全宅全案)", "value": "20 万 - 50 万(全宅全案)" }, "value": "5 万 - 10 万"
{ "label": "50 万以上(顶级孤品定制)", "value": "50 万以上(顶级孤品定制)" } },
{
"label": "10 万 - 20 万",
"value": "10 万 - 20 万"
},
{
"label": "20 万 - 50 万(全宅全案)",
"value": "20 万 - 50 万(全宅全案)"
},
{
"label": "50 万以上(顶级孤品定制)",
"value": "50 万以上(顶级孤品定制)"
}
] ]
}, },
{ {
@@ -834,14 +1165,22 @@
"type": "radio", "type": "radio",
"required": true, "required": true,
"options": [ "options": [
{ "label": "需要(预约排期现场勘测)", "value": "需要(预约排期现场勘测)" }, {
"label": "需要(预约排期现场勘测)",
"value": "需要(预约排期现场勘测)"
},
{ {
"label": "暂不需要(先发图纸在线深化评估)", "label": "暂不需要(先发图纸在线深化评估)",
"value": "暂不需要(先发图纸在线深化评估)" "value": "暂不需要(先发图纸在线深化评估)"
} }
] ]
}, },
{ "key": "contactName", "label": "贵姓称谓", "type": "text", "required": true }, {
"key": "contactName",
"label": "贵姓称谓",
"type": "text",
"required": true
},
{ {
"key": "contactPhone", "key": "contactPhone",
"label": "联系手机号(微信同号)", "label": "联系手机号(微信同号)",
@@ -875,13 +1214,36 @@
} }
], ],
"trustContent": [ "trustContent": [
{ "type": "credential", "title": "关于主理人", "content": "示例内容,待品牌主理人完善。" }, {
{ "type": "process", "title": "合作方法", "content": "示例内容,待品牌主理人完善。" } "type": "credential",
"title": "关于主理人",
"content": "示例内容,待品牌主理人完善。"
},
{
"type": "process",
"title": "合作方法",
"content": "示例内容,待品牌主理人完善。"
}
], ],
"fields": [ "fields": [
{ "key": "name", "label": "您的称呼", "type": "text", "required": true }, {
{ "key": "phone", "label": "联系方式", "type": "phone", "required": true }, "key": "name",
{ "key": "remark", "label": "合作需求", "type": "textarea", "required": true } "label": "您的称呼",
"type": "text",
"required": true
},
{
"key": "phone",
"label": "联系方式",
"type": "phone",
"required": true
},
{
"key": "remark",
"label": "合作需求",
"type": "textarea",
"required": true
}
], ],
"capabilityKey": "inquiry" "capabilityKey": "inquiry"
} }
+6
View File
@@ -1,6 +1,12 @@
import type { RuntimeWorkspace } from "./runtime-workspace.js"; import type { RuntimeWorkspace } from "./runtime-workspace.js";
export type EditorPreviewHostMessage = export type EditorPreviewHostMessage =
| {
protocol: "personal-brand-editor-preview";
version: 1;
type: "workspaceDraft";
workspace: RuntimeWorkspace;
}
| { | {
protocol: "personal-brand-editor-preview"; protocol: "personal-brand-editor-preview";
version: 1; version: 1;
@@ -62,6 +62,16 @@ export function runtimeContractForBinding(binding: string): RuntimeBindingContra
kind: "offering", kind: "offering",
}; };
} }
if (
binding.startsWith("offering.") &&
["name", "summary", "priceText", "coverUrl"].includes(binding.slice("offering.".length))
) {
return {
binding,
runtimePath: `workspace.offerings[].${binding.slice("offering.".length)}`,
kind: "offering",
};
}
if (binding === "trust.title" || binding === "trust.summary" || binding === "trust.content") { if (binding === "trust.title" || binding === "trust.summary" || binding === "trust.content") {
return { return {
binding, binding,
@@ -11,6 +11,10 @@ import {
} from "../src/runtime-content-contract.ts"; } from "../src/runtime-content-contract.ts";
test("runtime contract resolves canonical paths", () => { test("runtime contract resolves canonical paths", () => {
assert.equal(
runtimeContractForBinding("offering.name").runtimePath,
"workspace.offerings[].name",
);
assert.equal( assert.equal(
runtimeContractForBinding("offering.config.details.background").runtimePath, runtimeContractForBinding("offering.config.details.background").runtimePath,
"workspace.offerings[].presentation.details.background", "workspace.offerings[].presentation.details.background",
+14
View File
@@ -0,0 +1,14 @@
const fs = require("node:fs");
const path = require("node:path");
const root = path.resolve(__dirname, "..");
const source = path.join(root, "apps/taro/dist/template-preview/h5");
const destination = path.join(root, "apps/admin/public/template-preview");
if (!fs.existsSync(path.join(source, "index.html"))) {
throw new Error("Unified template preview build is missing; run build:preview first.");
}
fs.rmSync(destination, { recursive: true, force: true });
fs.mkdirSync(path.dirname(destination), { recursive: true });
fs.cpSync(source, destination, { recursive: true });