Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fa6b492bce | ||
|
|
860d9266fe | ||
|
|
a2932b1134 | ||
|
|
849ae5df05 | ||
|
|
df2b1f6031 | ||
|
|
66dbba5748 | ||
|
|
c5db30f817 | ||
|
|
541304a763 | ||
|
|
fd2e970d8b | ||
|
|
5b85fe769f | ||
|
|
0b14b5a814 | ||
|
|
c5af790554 |
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、类型和构建通过
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -14,6 +14,7 @@ apps/miniapp/project.private.config.json
|
||||
|
||||
.worktrees/
|
||||
apps/taro/src/assets/
|
||||
apps/admin/public/template-preview/
|
||||
|
||||
apps/taro/test-results/
|
||||
apps/taro/playwright-report/
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
node_modules
|
||||
.turbo
|
||||
dist
|
||||
apps/admin/public/template-preview
|
||||
.next
|
||||
prototype
|
||||
pnpm-lock.yaml
|
||||
|
||||
@@ -2,3 +2,4 @@ VITE_APP_BASE_PATH=/admin/
|
||||
VITE_API_BASE_URL=/api
|
||||
VITE_DEV_API_TARGET=http://localhost:3001
|
||||
ADMIN_PORT=3000
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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 { useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import type { BrandProfile } from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||
import { MutationError, QueryState } from "../../components/QueryState.js";
|
||||
import { PresentationEditor } from "./PresentationEditor.js";
|
||||
import "./BrandPage.css";
|
||||
import { useEditorDraft } from "./use-editor-draft.js";
|
||||
|
||||
export function BrandPage() {
|
||||
const [panel, setPanel] = useState("pages");
|
||||
const [dirty, setDirty] = useState(false);
|
||||
useEditorDraft(dirty);
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
const [form] = Form.useForm<BrandProfile>();
|
||||
@@ -16,6 +36,10 @@ export function BrandPage() {
|
||||
queryKey: ["admin-workspace"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
const previewWorkspace = useQuery({
|
||||
queryKey: ["admin-preview-workspace"],
|
||||
queryFn: () => client.getAdminPreviewWorkspace(),
|
||||
});
|
||||
const template = useQuery({
|
||||
queryKey: ["template", brand.data?.templateKey],
|
||||
queryFn: () => client.getPublicTemplate(brand.data!.templateKey),
|
||||
@@ -24,8 +48,10 @@ export function BrandPage() {
|
||||
const save = useMutation({
|
||||
mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values),
|
||||
onSuccess: () => {
|
||||
setDirty(false);
|
||||
message.success("品牌表达已保存");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
|
||||
},
|
||||
});
|
||||
return (
|
||||
@@ -33,22 +59,50 @@ export function BrandPage() {
|
||||
{!brand.data ? null : (
|
||||
<>
|
||||
<AdminPageHeader
|
||||
title="品牌资料"
|
||||
description="先让访客理解你是谁、服务谁,以及为什么值得信任。"
|
||||
title="小程序工作台"
|
||||
description={
|
||||
template.data?.description
|
||||
? `先让访客理解你是谁、服务谁,以及为什么值得信任。${template.data.description}`
|
||||
: "先让访客理解你是谁、服务谁,以及为什么值得信任。"
|
||||
}
|
||||
extra={<Tag color="blue">{template.data?.name ?? "当前模板"}</Tag>}
|
||||
/>
|
||||
<Row gutter={[24, 24]} align="top">
|
||||
<Col xs={24} xl={15}>
|
||||
<div className="brand-page__toolbar">
|
||||
<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}
|
||||
layout="vertical"
|
||||
initialValues={brand.data}
|
||||
onValuesChange={() => setDirty(true)}
|
||||
onFinish={(values) => save.mutate(values)}
|
||||
>
|
||||
<Card
|
||||
title="我是谁"
|
||||
extra={<Typography.Text type="secondary">公开展示</Typography.Text>}
|
||||
>
|
||||
<section className="brand-settings-section" aria-labelledby="brand-identity-title">
|
||||
<div className="brand-settings-section__header">
|
||||
<div>
|
||||
<Typography.Title id="brand-identity-title" level={4}>
|
||||
我是谁
|
||||
</Typography.Title>
|
||||
<Typography.Text type="secondary">公开展示的品牌身份和定位。</Typography.Text>
|
||||
</div>
|
||||
<Tag>品牌基础信息</Tag>
|
||||
</div>
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="品牌名称"
|
||||
@@ -73,8 +127,18 @@ export function BrandPage() {
|
||||
placeholder="让第一次认识你的人快速建立基本信任。"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Card>
|
||||
<Card title="如何联系与合作" style={{ marginTop: 24 }}>
|
||||
</section>
|
||||
<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}>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name="hours" label="可联系时间">
|
||||
@@ -104,8 +168,18 @@ export function BrandPage() {
|
||||
>
|
||||
<Input.TextArea rows={3} placeholder="例如:收到咨询后 1 个工作日内回复。" />
|
||||
</Form.Item>
|
||||
</Card>
|
||||
<Card title="模板与品牌视觉" style={{ marginTop: 24 }}>
|
||||
</section>
|
||||
<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
|
||||
name="templateKey"
|
||||
label="业务表达模板"
|
||||
@@ -135,7 +209,7 @@ export function BrandPage() {
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
</section>
|
||||
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
|
||||
<MutationError error={save.error} />
|
||||
<Button type="primary" htmlType="submit" loading={save.isPending} size="large">
|
||||
@@ -143,43 +217,27 @@ export function BrandPage() {
|
||||
</Button>
|
||||
</Space>
|
||||
</Form>
|
||||
<PresentationEditor
|
||||
templateContent={workspace.data?.templateContent}
|
||||
config={brand.data.config}
|
||||
loading={workspace.isLoading}
|
||||
error={workspace.error}
|
||||
</div>
|
||||
{template.data ? (
|
||||
<Alert
|
||||
className="brand-page__template-note"
|
||||
type="info"
|
||||
showIcon
|
||||
message={`当前使用:${template.data.name}`}
|
||||
description={`适用场景:${template.data.serviceCategories.join("、") || "通用品牌展示"}`}
|
||||
/>
|
||||
</Col>
|
||||
<Col xs={24} xl={9}>
|
||||
<Card title="公开表达预览" style={{ position: "sticky", top: 24 }}>
|
||||
<Typography.Text type="secondary">
|
||||
这些资料会用于小程序首页和联系区域
|
||||
</Typography.Text>
|
||||
<Typography.Title level={3}>{brand.data.name || "品牌名称"}</Typography.Title>
|
||||
<Typography.Title level={5}>{brand.data.tagline || "一句话定位"}</Typography.Title>
|
||||
<Typography.Paragraph>
|
||||
{brand.data.description || "品牌简介将在这里展示。"}
|
||||
</Typography.Paragraph>
|
||||
<Typography.Text strong>合作方式</Typography.Text>
|
||||
<Typography.Paragraph type="secondary">
|
||||
{brand.data.deliveryNote || "补充你的响应时间和合作预期。"}
|
||||
</Typography.Paragraph>
|
||||
<Space wrap>
|
||||
{brand.data.contactPhone && <Tag>电话:{brand.data.contactPhone}</Tag>}
|
||||
{brand.data.contactWechat && <Tag>微信:{brand.data.contactWechat}</Tag>}
|
||||
{brand.data.hours && <Tag>时间:{brand.data.hours}</Tag>}
|
||||
</Space>
|
||||
</Card>
|
||||
{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>
|
||||
) : null}
|
||||
</div>
|
||||
<div hidden={panel !== "pages"}>
|
||||
<PresentationEditor
|
||||
templateContent={workspace.data?.templateContent}
|
||||
previewWorkspace={previewWorkspace.data}
|
||||
config={brand.data.config}
|
||||
brand={brand.data}
|
||||
loading={workspace.isLoading}
|
||||
error={workspace.error}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</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%;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,27 @@
|
||||
.template-preview {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: min(72vh, 760px);
|
||||
min-height: 560px;
|
||||
overflow: hidden;
|
||||
border: 1px solid #e8e8e8;
|
||||
background: #f3f4f6;
|
||||
}
|
||||
|
||||
.template-preview iframe {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
background: #fff;
|
||||
transition: opacity 120ms ease;
|
||||
}
|
||||
|
||||
.template-preview__loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: #fff;
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Alert, Spin } from "antd";
|
||||
import type {
|
||||
BrandProfile,
|
||||
EditorPreviewFrameMessage,
|
||||
EditorPreviewHostMessage,
|
||||
RuntimeWorkspace,
|
||||
} from "@personal-brand/api-client";
|
||||
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";
|
||||
|
||||
export function TemplatePreview({
|
||||
brand,
|
||||
workspace,
|
||||
page,
|
||||
offeringId,
|
||||
targetKey,
|
||||
selection,
|
||||
targets,
|
||||
onTargetSelected,
|
||||
}: {
|
||||
brand: BrandProfile;
|
||||
workspace?: RuntimeWorkspace;
|
||||
page: string;
|
||||
offeringId?: string;
|
||||
targetKey?: string;
|
||||
selection?: PreviewSelection;
|
||||
targets: PreviewTarget[];
|
||||
onTargetSelected: (selection?: PreviewSelection) => void;
|
||||
}) {
|
||||
const frame = useRef<HTMLIFrameElement>(null);
|
||||
const useComponent = Boolean(workspace && resolveTemplateRenderer(workspace));
|
||||
const [ready, setReady] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const url = useMemo(() => {
|
||||
const value = templatePreviewUrl(
|
||||
brand.slug,
|
||||
page,
|
||||
import.meta.env.VITE_TEMPLATE_PREVIEW_URL || "/template-preview/index.html",
|
||||
window.location.origin,
|
||||
`/pages/${encodeURIComponent(page)}/index`,
|
||||
);
|
||||
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 brandDraft = useMemo(
|
||||
() => ({
|
||||
name: brand.name,
|
||||
tagline: brand.tagline,
|
||||
description: brand.description,
|
||||
avatarUrl: brand.avatarUrl,
|
||||
coverUrl: brand.coverUrl,
|
||||
hours: brand.hours,
|
||||
address: brand.address,
|
||||
deliveryNote: brand.deliveryNote,
|
||||
contactPhone: brand.contactPhone,
|
||||
contactWechat: brand.contactWechat,
|
||||
config: brand.config,
|
||||
}),
|
||||
[brand],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setReady(false);
|
||||
setError("");
|
||||
}, [url]);
|
||||
|
||||
useEffect(() => {
|
||||
const onMessage = (event: MessageEvent<EditorPreviewFrameMessage>) => {
|
||||
if (event.source !== frame.current?.contentWindow || event.origin !== origin) return;
|
||||
const message = event.data;
|
||||
if (message?.protocol !== "personal-brand-editor-preview" || message.version !== 1) return;
|
||||
if (message.type === "ready") setReady(true);
|
||||
if (message.type === "targetSelected" && message.page === page)
|
||||
onTargetSelected({ targetKey: message.targetKey });
|
||||
};
|
||||
window.addEventListener("message", onMessage);
|
||||
return () => window.removeEventListener("message", onMessage);
|
||||
}, [onTargetSelected, origin, page]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready || !frame.current?.contentWindow || !origin) return;
|
||||
const send = (message: EditorPreviewHostMessage) =>
|
||||
frame.current?.contentWindow?.postMessage(message, origin);
|
||||
if (workspace) {
|
||||
send({
|
||||
protocol: "personal-brand-editor-preview",
|
||||
version: 1,
|
||||
type: "workspaceDraft",
|
||||
workspace,
|
||||
});
|
||||
} else {
|
||||
send({
|
||||
protocol: "personal-brand-editor-preview",
|
||||
version: 1,
|
||||
type: "brandDraft",
|
||||
brand: brandDraft,
|
||||
});
|
||||
}
|
||||
if (targetKey)
|
||||
send({
|
||||
protocol: "personal-brand-editor-preview",
|
||||
version: 1,
|
||||
type: "focusTarget",
|
||||
targetKey,
|
||||
});
|
||||
}, [brandDraft, origin, ready, targetKey, workspace]);
|
||||
|
||||
useEffect(() => {
|
||||
const refresh = () => setReloadKey((value) => value + 1);
|
||||
window.addEventListener("template-preview-refresh", refresh);
|
||||
return () => window.removeEventListener("template-preview-refresh", refresh);
|
||||
}, []);
|
||||
|
||||
if (!useComponent && !url)
|
||||
return (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
message="页面预览暂不可用"
|
||||
description="请确认模板预览资源已构建并发布,或本地预览服务正在运行。"
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<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 ? (
|
||||
<div className="template-preview__loading">
|
||||
<Spin tip="正在加载页面预览" />
|
||||
</div>
|
||||
) : null}
|
||||
{error ? (
|
||||
<Alert type="error" showIcon message="页面预览加载失败" description={error} />
|
||||
) : null}
|
||||
<iframe
|
||||
key={url}
|
||||
ref={frame}
|
||||
title="小程序页面预览"
|
||||
src={url}
|
||||
referrerPolicy="origin"
|
||||
onError={() => setError("请检查预览服务地址和网络连接。")}
|
||||
style={{ opacity: ready ? 1 : 0 }}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -12,6 +12,18 @@ export type PresentationSection = {
|
||||
|
||||
export type PresentationValues = Record<string, unknown>;
|
||||
|
||||
export function filterSectionsForPreviewTarget<
|
||||
T extends { fields: Array<{ previewTarget?: string }> },
|
||||
>(sections: T[], targetKey?: string): T[] {
|
||||
if (!targetKey) return sections;
|
||||
return sections
|
||||
.map((section) => ({
|
||||
...section,
|
||||
fields: section.fields.filter((field) => field.previewTarget === targetKey),
|
||||
}))
|
||||
.filter((section) => section.fields.length > 0);
|
||||
}
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
@@ -19,11 +31,14 @@ function asObject(value: unknown): Record<string, unknown> {
|
||||
}
|
||||
|
||||
function safePath(binding: string): string[] | null {
|
||||
const prefix = ["brand.config.", "offering.config.", "trust.config."].find((candidate) =>
|
||||
binding.startsWith(candidate),
|
||||
);
|
||||
if (!prefix) return null;
|
||||
const path = binding.slice(prefix.length).split(".");
|
||||
const prefixes = ["brand.config.", "offering.config.", "trust.config."];
|
||||
const prefix = prefixes.find((candidate) => binding.startsWith(candidate));
|
||||
const standardField =
|
||||
/^(brand\.(avatarUrl|description|contactPhone|contactWechat|address|hours|deliveryNote)|offering\.(name|summary|description|coverUrl|priceText)|trust\.(title|summary|content|coverUrl))$/.test(
|
||||
binding,
|
||||
);
|
||||
if (!prefix && !standardField) return null;
|
||||
const path = prefix ? binding.slice(prefix.length).split(".") : [binding.split(".")[1] ?? ""];
|
||||
if (path.some((part) => !part || ["__proto__", "prototype", "constructor"].includes(part)))
|
||||
return null;
|
||||
return path;
|
||||
@@ -37,10 +52,15 @@ export function readPresentationValue(
|
||||
config: Record<string, unknown> | null | undefined,
|
||||
binding: string,
|
||||
field?: PresentationField,
|
||||
brand?: Record<string, unknown>,
|
||||
): unknown {
|
||||
const path = safePath(binding);
|
||||
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];
|
||||
if (field?.input === "list") {
|
||||
if (!Array.isArray(value)) return [];
|
||||
@@ -76,6 +96,7 @@ export function applyPresentationValues(
|
||||
let nextConfig = { ...asObject(config) };
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
if (!field.binding.includes(".config.")) continue;
|
||||
const path = safePath(field.binding);
|
||||
if (!path) continue;
|
||||
const raw = values[presentationFieldName(section.key, field.key)];
|
||||
@@ -92,3 +113,51 @@ export function applyPresentationValues(
|
||||
}
|
||||
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,
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export function templatePreviewUrl(
|
||||
brandSlug: string | undefined,
|
||||
page: string,
|
||||
configured: string | undefined,
|
||||
parentOrigin?: string,
|
||||
route?: string,
|
||||
): string | undefined {
|
||||
const raw = configured || "http://localhost:3002";
|
||||
try {
|
||||
const url = new URL(raw, parentOrigin);
|
||||
url.searchParams.set("editor", "1");
|
||||
if (parentOrigin) url.searchParams.set("parentOrigin", parentOrigin);
|
||||
if (brandSlug) url.searchParams.set("brand", brandSlug);
|
||||
url.hash = route || `/pages/${encodeURIComponent(page)}/index`;
|
||||
return url.toString();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
Vendored
+3
@@ -1,6 +1,9 @@
|
||||
interface ImportMetaEnv {
|
||||
readonly DEV: boolean;
|
||||
readonly PROD: boolean;
|
||||
readonly VITE_API_BASE_URL?: string;
|
||||
readonly VITE_APP_BASE_PATH?: string;
|
||||
readonly VITE_TEMPLATE_PREVIEW_URL?: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
|
||||
@@ -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,9 +1,13 @@
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
applyPresentationValues,
|
||||
applyBrandPreviewValues,
|
||||
applyStandardEntityValues,
|
||||
filterSectionsForPreviewTarget,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
} from "../src/features/brand/presentation-bindings.ts";
|
||||
import { resolvePreviewSelection } from "../src/features/brand/preview-selection.ts";
|
||||
|
||||
const config = {
|
||||
founder: "阿成",
|
||||
@@ -37,6 +41,21 @@ assert.equal(next.visualPresentation.inquiry.subtitle, "原说明");
|
||||
assert.equal(next.unrelatedSetting, true);
|
||||
assert.equal(config.founder, "阿成");
|
||||
|
||||
const previewSections = [
|
||||
{
|
||||
key: "home",
|
||||
fields: [
|
||||
{ key: "location", previewTarget: "home.location" },
|
||||
{ key: "hero", previewTarget: "home.hero" },
|
||||
],
|
||||
},
|
||||
{ key: "profile", fields: [{ key: "bio", previewTarget: "profile.bio" }] },
|
||||
];
|
||||
assert.deepEqual(filterSectionsForPreviewTarget(previewSections, "home.hero"), [
|
||||
{ key: "home", fields: [{ key: "hero", previewTarget: "home.hero" }] },
|
||||
]);
|
||||
assert.equal(filterSectionsForPreviewTarget(previewSections).length, 2);
|
||||
|
||||
const unsafe = applyPresentationValues(
|
||||
{ founder: "原主理人" },
|
||||
[
|
||||
@@ -108,3 +127,63 @@ const offering = applyPresentationValues(
|
||||
{ [presentationFieldName("offering", "background")]: "新背景" },
|
||||
);
|
||||
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);
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { templatePreviewUrl } from "../src/lib/template-preview.ts";
|
||||
|
||||
test("template preview URL is resolved from one shared deployment address", () => {
|
||||
const url = templatePreviewUrl(
|
||||
"brand-a",
|
||||
"profile",
|
||||
"https://preview.example.test/app/",
|
||||
"https://admin.example.test",
|
||||
"/pages/profile/index",
|
||||
);
|
||||
assert.equal(
|
||||
url,
|
||||
"https://preview.example.test/app/?editor=1&parentOrigin=https%3A%2F%2Fadmin.example.test&brand=brand-a#/pages/profile/index",
|
||||
);
|
||||
});
|
||||
|
||||
test("the shared same-origin preview address is the default", () => {
|
||||
assert.equal(
|
||||
templatePreviewUrl("brand-a", "home", 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",
|
||||
);
|
||||
});
|
||||
@@ -1,9 +1,23 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { templatePreviewCss } from "./template-preview-css.mjs";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
css: { postcss: { plugins: [templatePreviewCss()] } },
|
||||
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: {
|
||||
host: "0.0.0.0",
|
||||
port: Number(process.env.ADMIN_PORT ?? 3000),
|
||||
|
||||
@@ -36,12 +36,14 @@ import {
|
||||
} from "@personal-brand/config";
|
||||
import { TemplateWorkspaceService } from "./template-workspace.service.js";
|
||||
import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation";
|
||||
import { PublicWorkspaceService } from "./modules/public/public-workspace.controller.js";
|
||||
|
||||
@Controller("admin/workspace")
|
||||
class AdminWorkspaceController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
private readonly publicWorkspace: PublicWorkspaceService,
|
||||
) {}
|
||||
private brandId(): string {
|
||||
return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
|
||||
@@ -194,6 +196,11 @@ class AdminWorkspaceController {
|
||||
: 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> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
|
||||
@@ -7,7 +7,10 @@ import { BookingService } from "./booking.service.js";
|
||||
import { AdminAuthService } from "./admin-auth.service.js";
|
||||
import { ApiExceptionFilter, RequestIdMiddleware } from "./http.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 { AdminConfigController } from "./modules/admin/admin-config.controller.js";
|
||||
import { PublicOfferingController } from "./modules/public/public-offering.controller.js";
|
||||
@@ -70,6 +73,7 @@ export class HealthController {
|
||||
BrandReleaseService,
|
||||
BrandReleaseApiService,
|
||||
PublicBrandContextService,
|
||||
PublicWorkspaceService,
|
||||
],
|
||||
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 { PrismaService } from "../../prisma.service.js";
|
||||
import { PublicBrandContextService } from "./public-brand-context.service.js";
|
||||
@@ -26,15 +26,11 @@ import {
|
||||
projectTrustPresentation,
|
||||
} from "@personal-brand/types";
|
||||
|
||||
@Controller("public/workspace")
|
||||
export class PublicWorkspaceController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly brandContext: PublicBrandContextService,
|
||||
) {}
|
||||
@Get()
|
||||
async get(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
|
||||
const brandId = await this.brandContext.resolveId(brandSlug);
|
||||
@Injectable()
|
||||
export class PublicWorkspaceService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getForBrandId(brandId: string): Promise<unknown> {
|
||||
const release = await this.prisma.brandRelease.findFirst({
|
||||
where: { brandId, status: "published" },
|
||||
orderBy: { version: "desc" },
|
||||
@@ -370,3 +366,17 @@ export class PublicWorkspaceController {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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 () => {
|
||||
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
|
||||
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
|
||||
|
||||
@@ -4,6 +4,7 @@ import fs from "node:fs";
|
||||
|
||||
const root = path.resolve(__dirname, "../../..");
|
||||
const key = process.env.TEMPLATE_KEY || "acheng-campus-food";
|
||||
const previewAllTemplates = process.env.PREVIEW_ALL_TEMPLATES === "true";
|
||||
const templates = fs
|
||||
.readdirSync(path.join(root, "packages"))
|
||||
.filter(
|
||||
@@ -30,20 +31,33 @@ export default defineConfig({
|
||||
designWidth: 750,
|
||||
deviceRatio: { 750: 1 },
|
||||
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",
|
||||
compiler: { type: "vite" },
|
||||
plugins: [],
|
||||
alias: { "@template": path.join(template, "taro") },
|
||||
alias: {
|
||||
"@template": previewAllTemplates
|
||||
? path.resolve(__dirname, "../src/runtime/template-preview-entry.tsx")
|
||||
: path.join(template, "taro"),
|
||||
},
|
||||
defineConstants: {
|
||||
TEMPLATE_KEY: JSON.stringify(key),
|
||||
BRAND_SLUG: JSON.stringify(brand),
|
||||
API_BASE_URL: JSON.stringify(process.env.API_BASE_URL || "http://localhost:3001"),
|
||||
TEMPLATE_MANIFEST: JSON.stringify(manifest),
|
||||
PREVIEW_ALL_TEMPLATES: JSON.stringify(previewAllTemplates),
|
||||
},
|
||||
copy: {
|
||||
options: {},
|
||||
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"
|
||||
? [
|
||||
{
|
||||
@@ -52,15 +66,19 @@ export default defineConfig({
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
from: path.join(template, "miniapp/assets"),
|
||||
to: `dist/${key}/${process.env.TARO_ENV || "weapp"}/assets`,
|
||||
},
|
||||
...(!previewAllTemplates
|
||||
? [
|
||||
{
|
||||
from: path.join(template, "miniapp/assets"),
|
||||
to: `dist/${key}/${process.env.TARO_ENV || "weapp"}/assets`,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
mini: {},
|
||||
h5: {
|
||||
publicPath: "/",
|
||||
publicPath: process.env.PREVIEW_PUBLIC_PATH || "/",
|
||||
router: { mode: "hash" },
|
||||
devServer: { host: "0.0.0.0", port: Number(process.env.PREVIEW_PORT || 3002) },
|
||||
},
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"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:preview": "PREVIEW_ALL_TEMPLATES=true taro build --type h5",
|
||||
"build:weapp": "taro build --type weapp",
|
||||
"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",
|
||||
|
||||
+15
-11
@@ -21,15 +21,19 @@ export default defineAppConfig({
|
||||
navigationBarBackgroundColor: "#ffffff",
|
||||
navigationBarTextStyle: "black",
|
||||
},
|
||||
tabBar: {
|
||||
color: "#8b8178",
|
||||
selectedColor: "#3b2118",
|
||||
backgroundColor: "#ffffff",
|
||||
list: TEMPLATE_MANIFEST.navigation.map((tab) => ({
|
||||
pagePath: routes[tab.page],
|
||||
text: tab.label,
|
||||
iconPath: tab.iconPath,
|
||||
selectedIconPath: tab.selectedIconPath,
|
||||
})),
|
||||
},
|
||||
...(!PREVIEW_ALL_TEMPLATES
|
||||
? {
|
||||
tabBar: {
|
||||
color: "#8b8178",
|
||||
selectedColor: "#3b2118",
|
||||
backgroundColor: "#ffffff",
|
||||
list: TEMPLATE_MANIFEST.navigation.map((tab) => ({
|
||||
pagePath: routes[tab.page],
|
||||
text: tab.label,
|
||||
iconPath: tab.iconPath,
|
||||
selectedIconPath: tab.selectedIconPath,
|
||||
})),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
@@ -28,6 +28,11 @@ button::after {
|
||||
image {
|
||||
display: block;
|
||||
}
|
||||
.editor-target-selected {
|
||||
outline: 3px solid #1677ff;
|
||||
outline-offset: -3px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.runtime-state {
|
||||
min-height: 70vh;
|
||||
padding: 80px 32px;
|
||||
|
||||
@@ -17,7 +17,13 @@ import type { Values } from "../runtime/content";
|
||||
import { ensureSession, request, brandSlug } from "../runtime/api";
|
||||
import { takeQuery, navigate } from "../runtime/navigation";
|
||||
import "./forms.css";
|
||||
export function Inquiry({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
export function Inquiry({
|
||||
workspace,
|
||||
preview = false,
|
||||
}: {
|
||||
workspace: RuntimeWorkspace;
|
||||
preview?: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [offeringId, setOfferingId] = useState(router.params.offeringId || "");
|
||||
const form: RuntimeInquiryForm | undefined =
|
||||
@@ -28,7 +34,7 @@ export function Inquiry({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
const [sending, setSending] = useState(false);
|
||||
const busy = useRef(false);
|
||||
const p = presentation(workspace, "inquiry");
|
||||
const food = TEMPLATE_KEY === "acheng-campus-food";
|
||||
const food = workspace.brand.visualTemplateKey === "acheng-campus-food";
|
||||
useDidShow(() => {
|
||||
const query = takeQuery("inquiry");
|
||||
if (query.offeringId) setOfferingId(query.offeringId);
|
||||
@@ -40,6 +46,7 @@ export function Inquiry({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
const setValue = (key: string, value: string | string[]) =>
|
||||
setValues((current) => ({ ...current, [key]: value }));
|
||||
async function submit() {
|
||||
if (preview) return;
|
||||
if (busy.current) return;
|
||||
if (!form) {
|
||||
setError("咨询表单暂不可用,请稍后重试");
|
||||
@@ -96,6 +103,7 @@ export function Inquiry({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
<View
|
||||
className={`form-field ${food && ["people", "date", "budget", "delivery"].includes(field.key) ? "half-field" : ""}`}
|
||||
key={field.key}
|
||||
data-editor-target={preview ? `inquiry-field:${field.key}` : undefined}
|
||||
>
|
||||
<Text className="field-label">
|
||||
{field.label}
|
||||
|
||||
@@ -1,14 +1,70 @@
|
||||
import { View, Button } from "@tarojs/components";
|
||||
import { useRouter } from "@tarojs/taro";
|
||||
import { useEffect } from "react";
|
||||
import { TemplatePage } from "@template";
|
||||
import { useWorkspace } from "../runtime/workspace";
|
||||
import type { EditorPreviewFrameMessage, EditorPreviewHostMessage } from "@personal-brand/types";
|
||||
import type { PageKey } from "../runtime/navigation";
|
||||
import { Inquiry } from "./Inquiry";
|
||||
import { Records } from "./Records";
|
||||
import { Success } from "./Success";
|
||||
export function Page({ page }: { page: PageKey }) {
|
||||
const { workspace, error, loading, reload } = useWorkspace();
|
||||
const { workspace, error, loading, reload, setBrandDraft, setWorkspaceDraft } = useWorkspace();
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
if (process.env.TARO_ENV !== "h5" || window.parent === window) return;
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (params.get("editor") !== "1") return;
|
||||
const parentOrigin = params.get("parentOrigin") || "";
|
||||
try {
|
||||
if (!parentOrigin || new URL(parentOrigin).origin !== parentOrigin) return;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const send = (message: EditorPreviewFrameMessage) =>
|
||||
window.parent.postMessage(message, parentOrigin);
|
||||
const onMessage = (event: MessageEvent<EditorPreviewHostMessage>) => {
|
||||
if (event.source !== window.parent || event.origin !== parentOrigin) return;
|
||||
const message = event.data;
|
||||
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 === "focusTarget") {
|
||||
document.querySelectorAll<HTMLElement>("[data-editor-target]").forEach((element) => {
|
||||
element.classList.toggle(
|
||||
"editor-target-selected",
|
||||
element.dataset.editorTarget === message.targetKey,
|
||||
);
|
||||
});
|
||||
}
|
||||
};
|
||||
const onClick = (event: MouseEvent) => {
|
||||
const target =
|
||||
event.target instanceof Element
|
||||
? event.target.closest<HTMLElement>("[data-editor-target]")
|
||||
: null;
|
||||
if (!target?.dataset.editorTarget) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
document.querySelectorAll<HTMLElement>("[data-editor-target]").forEach((element) => {
|
||||
element.classList.toggle("editor-target-selected", element === target);
|
||||
});
|
||||
send({
|
||||
protocol: "personal-brand-editor-preview",
|
||||
version: 1,
|
||||
type: "targetSelected",
|
||||
targetKey: target.dataset.editorTarget,
|
||||
page: window.location.hash.match(/pages\/([^/]+)/)?.[1] || "home",
|
||||
});
|
||||
};
|
||||
window.addEventListener("message", onMessage);
|
||||
document.addEventListener("click", onClick, true);
|
||||
send({ protocol: "personal-brand-editor-preview", version: 1, type: "ready" });
|
||||
return () => {
|
||||
window.removeEventListener("message", onMessage);
|
||||
document.removeEventListener("click", onClick, true);
|
||||
};
|
||||
}, [setBrandDraft, setWorkspaceDraft]);
|
||||
if (loading) return <View className="runtime-state">正在加载…</View>;
|
||||
if (error || !workspace)
|
||||
return (
|
||||
|
||||
@@ -25,13 +25,20 @@ const labels: Record<string, string> = {
|
||||
converted: "已转化",
|
||||
closed: "已关闭",
|
||||
};
|
||||
export function Records({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
export function Records({
|
||||
workspace,
|
||||
preview = false,
|
||||
}: {
|
||||
workspace: RuntimeWorkspace;
|
||||
preview?: boolean;
|
||||
}) {
|
||||
const [records, setRecords] = useState<RecordItem[]>([]);
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [authenticated, setAuthenticated] = useState(hasSession());
|
||||
const [authenticated, setAuthenticated] = useState(preview ? false : hasSession());
|
||||
const p = presentation(workspace, "records");
|
||||
const load = useCallback(() => {
|
||||
if (preview) return;
|
||||
if (!hasSession()) {
|
||||
setAuthenticated(false);
|
||||
setRecords([]);
|
||||
@@ -46,7 +53,7 @@ export function Records({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
setAuthenticated(hasSession());
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
}, [preview]);
|
||||
useDidShow(load);
|
||||
return (
|
||||
<View className="records-page">
|
||||
|
||||
@@ -4,10 +4,18 @@ import type { RuntimeWorkspace } from "@personal-brand/types";
|
||||
import { presentation, object, text } from "../runtime/content";
|
||||
import { brandSlug } from "../runtime/api";
|
||||
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 result = object(Taro.getStorageSync<unknown>(`latestInquiry:${brandSlug()}`));
|
||||
if (!text(result.id))
|
||||
const submitted =
|
||||
preview ||
|
||||
Boolean(text(object(Taro.getStorageSync<unknown>(`latestInquiry:${brandSlug()}`)).id));
|
||||
if (!submitted)
|
||||
return (
|
||||
<View className="runtime-state">
|
||||
尚未提交咨询<Button onClick={() => navigate("inquiry")}>填写需求</Button>
|
||||
|
||||
Vendored
+4
@@ -12,7 +12,11 @@ declare const TEMPLATE_MANIFEST: {
|
||||
selectedIconPath: string;
|
||||
}[];
|
||||
};
|
||||
declare const PREVIEW_ALL_TEMPLATES: boolean;
|
||||
declare module "*.css";
|
||||
interface ImportMeta {
|
||||
glob<T = unknown>(pattern: string, options?: { eager?: boolean }): Record<string, T>;
|
||||
}
|
||||
declare module "@template" {
|
||||
export { TemplatePage } from "../../../packages/template-acheng-campus-food/taro";
|
||||
}
|
||||
@@ -7,6 +7,12 @@ export function brandSlug() {
|
||||
}
|
||||
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 function hasSession() {
|
||||
return Boolean(Taro.getStorageSync<string>(tokenKey()));
|
||||
@@ -16,9 +22,10 @@ export async function request<T>(
|
||||
options: { method?: "GET" | "POST"; data?: unknown; customer?: boolean } = {},
|
||||
): Promise<T> {
|
||||
const context = path.startsWith("/public/") || path.startsWith("/customer/session/wechat");
|
||||
const query = context
|
||||
? `${path.includes("?") ? "&" : "?"}brandSlug=${encodeURIComponent(brandSlug())}`
|
||||
: "";
|
||||
const query =
|
||||
context && !(isEditorPreview() && path === "/public/workspace")
|
||||
? `${path.includes("?") ? "&" : "?"}brandSlug=${encodeURIComponent(brandSlug())}`
|
||||
: "";
|
||||
const response = await Taro.request<T & { error?: { message?: string; requestId?: string } }>({
|
||||
url: API_BASE_URL.replace(/\/$/, "") + path + query,
|
||||
method: options.method || "GET",
|
||||
@@ -38,10 +45,21 @@ export async function request<T>(
|
||||
}
|
||||
export async function loadWorkspace() {
|
||||
const data = await request<RuntimeWorkspace>("/public/workspace");
|
||||
if (data.publication?.status !== "published") throw new Error("品牌尚未发布");
|
||||
if (data.brand.visualTemplateKey !== TEMPLATE_KEY)
|
||||
const editorPreview = isEditorPreview();
|
||||
if (!editorPreview && data.publication?.status !== "published") throw new Error("品牌尚未发布");
|
||||
if (!editorPreview && data.brand.visualTemplateKey !== TEMPLATE_KEY)
|
||||
throw new Error("该品牌使用其他模板,请选择匹配的模板预览地址");
|
||||
return data;
|
||||
return {
|
||||
...data,
|
||||
brand: data.brand ?? {},
|
||||
templateData: data.templateData ?? {},
|
||||
offerings: data.offerings ?? [],
|
||||
inquiryForms: data.inquiryForms ?? [],
|
||||
trustItems: data.trustItems ?? [],
|
||||
trustPresentation: data.trustPresentation ?? {},
|
||||
capabilities: data.capabilities ?? [],
|
||||
theme: data.theme ?? { colors: {} },
|
||||
};
|
||||
}
|
||||
export async function ensureSession() {
|
||||
if (hasSession()) return;
|
||||
|
||||
@@ -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} />;
|
||||
}
|
||||
@@ -1,30 +1,68 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useState } from "react";
|
||||
import type { PropsWithChildren } from "react";
|
||||
import type { RuntimeWorkspace } from "@personal-brand/types";
|
||||
import { projectBrandAliases } from "@personal-brand/types";
|
||||
import { loadWorkspace } from "./api";
|
||||
const Context = createContext<{
|
||||
workspace?: RuntimeWorkspace;
|
||||
error: string;
|
||||
loading: boolean;
|
||||
setBrandDraft: (brand: Partial<RuntimeWorkspace["brand"]>) => void;
|
||||
setWorkspaceDraft: (workspace: RuntimeWorkspace) => void;
|
||||
reload: () => void;
|
||||
}>({ error: "", loading: true, reload() {} });
|
||||
}>({ error: "", loading: true, setBrandDraft() {}, setWorkspaceDraft() {}, reload() {} });
|
||||
export function WorkspaceProvider({ children }: PropsWithChildren) {
|
||||
const [workspace, setWorkspace] = useState<RuntimeWorkspace>();
|
||||
const [baseWorkspace, setBaseWorkspace] = useState<RuntimeWorkspace>();
|
||||
const [brandDraft, setBrandDraft] = useState<Partial<RuntimeWorkspace["brand"]>>({});
|
||||
const [workspaceDraft, setWorkspaceDraft] = useState<RuntimeWorkspace>();
|
||||
const workspace = workspaceDraft ?? baseWorkspace;
|
||||
const resolvedWorkspace = workspace
|
||||
? {
|
||||
...workspace,
|
||||
brand: projectBrandAliases(
|
||||
{ ...workspace.brand, ...brandDraft },
|
||||
brandDraft.config && typeof brandDraft.config === "object"
|
||||
? (brandDraft.config as Record<string, unknown>)
|
||||
: ((workspace.brand.config as Record<string, unknown> | undefined) ?? {}),
|
||||
),
|
||||
}
|
||||
: undefined;
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const reload = useCallback(() => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
void loadWorkspace()
|
||||
.then(setWorkspace)
|
||||
const editorPreview =
|
||||
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) =>
|
||||
setError(error instanceof Error ? error.message : "加载失败,请重试"),
|
||||
)
|
||||
.finally(() => setLoading(false));
|
||||
.finally(() => setLoading(!editorPreview));
|
||||
}, []);
|
||||
useEffect(reload, [reload]);
|
||||
return (
|
||||
<Context.Provider value={{ workspace, error, loading, reload }}>{children}</Context.Provider>
|
||||
<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}
|
||||
</Context.Provider>
|
||||
);
|
||||
}
|
||||
export const useWorkspace = () => useContext(Context);
|
||||
@@ -0,0 +1,672 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
|
||||
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
|
||||
const brand = {
|
||||
id: "brand-fixture",
|
||||
slug: "preview-fixture",
|
||||
name: "预览品牌",
|
||||
templateKey: "food",
|
||||
tagline: "校园家常餐",
|
||||
description: "认真做好每一餐",
|
||||
avatarUrl: "/assets/owner/portrait.jpg",
|
||||
coverUrl: "",
|
||||
hours: "每日 17:00",
|
||||
address: "东门附近",
|
||||
deliveryNote: "提前预约",
|
||||
contactPhone: "13800138000",
|
||||
contactWechat: "food-example",
|
||||
config: {
|
||||
visualTemplateKey: "acheng-campus-food",
|
||||
founder: "测试主理人",
|
||||
title: "私房菜主理人",
|
||||
heroImage: "",
|
||||
visualPresentation: { home: { stallTitle: "原服务地点", worksTitle: "原餐品标题" } },
|
||||
},
|
||||
};
|
||||
const adminOffering = {
|
||||
id: "menu-fixture",
|
||||
kind: "service",
|
||||
name: "家庭聚餐定制",
|
||||
summary: "为同学聚餐、家庭聚会提供常见的私房菜定制。",
|
||||
description: "餐品详情",
|
||||
priceText: "88.88",
|
||||
coverUrl: brand.avatarUrl,
|
||||
isEnabled: true,
|
||||
sortOrder: 0,
|
||||
config: { categoryLabel: "业务提供项" },
|
||||
};
|
||||
const adminTrust = {
|
||||
id: "schedule-fixture",
|
||||
type: "schedule",
|
||||
title: "出摊安排",
|
||||
summary: "工作日安排",
|
||||
content: "周末安排",
|
||||
sortOrder: 0,
|
||||
isPublished: true,
|
||||
config: {
|
||||
weekdayLabel: "周一至周五",
|
||||
weekdayDetail: "东门附近",
|
||||
weekendLabel: "周六至周日",
|
||||
weekendDetail: "周末晚间出摊",
|
||||
},
|
||||
};
|
||||
const runtimeWorkspace = {
|
||||
schemaVersion: "1.0.0",
|
||||
publication: { status: "published", version: 1 },
|
||||
brand: {
|
||||
...brand,
|
||||
founder: "测试主理人",
|
||||
title: "私房菜主理人",
|
||||
visualPresentation: brand.config.visualPresentation,
|
||||
visualTemplateKey: "acheng-campus-food",
|
||||
},
|
||||
templateData: {},
|
||||
navigation: { tabs: [] },
|
||||
offerings: [
|
||||
{
|
||||
id: adminOffering.id,
|
||||
name: adminOffering.name,
|
||||
summary: adminOffering.summary,
|
||||
priceText: adminOffering.priceText,
|
||||
coverUrl: adminOffering.coverUrl,
|
||||
presentation: {
|
||||
categoryLabel: "业务提供项",
|
||||
keywords: [],
|
||||
details: { background: "餐品详情", designConcept: "", crafts: [], materialsList: [] },
|
||||
},
|
||||
},
|
||||
],
|
||||
inquiryForms: [
|
||||
{
|
||||
key: "brand-inquiry",
|
||||
version: "1",
|
||||
purpose: "inquiry",
|
||||
target: "brand",
|
||||
submissionAction: "create-inquiry",
|
||||
fields: [
|
||||
{ key: "name", label: "称呼", type: "text", required: true },
|
||||
{ key: "message", label: "需求说明", type: "textarea", required: true },
|
||||
],
|
||||
},
|
||||
],
|
||||
trustItems: [{ ...adminTrust }],
|
||||
trustPresentation: {},
|
||||
capabilities: [],
|
||||
theme: { colors: {} },
|
||||
};
|
||||
const templateContent = {
|
||||
displayName: "餐饮模板",
|
||||
navigation: [
|
||||
{ key: "home", page: "home", label: "首页" },
|
||||
{ key: "offerings", page: "offerings", label: "套餐餐品" },
|
||||
{ key: "service", page: "service", label: "出摊服务" },
|
||||
{ key: "detail", page: "detail", label: "详情页" },
|
||||
{ key: "inquiry", page: "inquiry", label: "定制/咨询" },
|
||||
{ key: "success", page: "success", label: "提交成功页" },
|
||||
{ key: "records", page: "records", label: "记录页" },
|
||||
],
|
||||
assetSlots: [],
|
||||
trustContentTypes: [
|
||||
{
|
||||
type: "schedule",
|
||||
label: "每周出摊安排",
|
||||
adminFields: { title: "安排标题", summary: "安排摘要", content: "安排正文" },
|
||||
hideStandardFields: ["summary", "content"],
|
||||
pages: ["service"],
|
||||
configFields: [
|
||||
{
|
||||
key: "weekdayLabel",
|
||||
binding: "trust.config.weekdayLabel",
|
||||
label: "工作日标题",
|
||||
input: "text",
|
||||
},
|
||||
{
|
||||
key: "weekdayDetail",
|
||||
binding: "trust.config.weekdayDetail",
|
||||
label: "工作日地点",
|
||||
input: "text",
|
||||
},
|
||||
{
|
||||
key: "weekendLabel",
|
||||
binding: "trust.config.weekendLabel",
|
||||
label: "周末标题",
|
||||
input: "text",
|
||||
},
|
||||
{
|
||||
key: "weekendDetail",
|
||||
binding: "trust.config.weekendDetail",
|
||||
label: "周末地点",
|
||||
input: "text",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
admin: {
|
||||
sections: [
|
||||
{
|
||||
key: "detailCopy",
|
||||
title: "餐品说明",
|
||||
description: "编辑详情页说明",
|
||||
page: "detail",
|
||||
target: "brand",
|
||||
previewTargets: [{ key: "acheng-campus-food.detail.detailCopy", label: "餐品说明" }],
|
||||
fields: [
|
||||
{
|
||||
key: "priceLabel",
|
||||
binding: "brand.config.visualPresentation.detail.priceLabel",
|
||||
label: "价格标题",
|
||||
input: "text",
|
||||
previewTarget: "acheng-campus-food.detail.detailCopy",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "offering-card",
|
||||
title: "餐品卡片",
|
||||
description: "编辑单条餐品",
|
||||
page: "offerings",
|
||||
target: "offering",
|
||||
previewTargets: [{ key: "acheng-campus-food.offerings.item", label: "餐品卡片" }],
|
||||
fields: [
|
||||
{
|
||||
key: "name",
|
||||
binding: "offering.name",
|
||||
label: "餐品名称",
|
||||
input: "text",
|
||||
previewTarget: "acheng-campus-food.offerings.item",
|
||||
},
|
||||
{
|
||||
key: "summary",
|
||||
binding: "offering.summary",
|
||||
label: "餐品简介",
|
||||
input: "textarea",
|
||||
previewTarget: "acheng-campus-food.offerings.item",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "home",
|
||||
title: "首页内容",
|
||||
description: "首页可编辑项",
|
||||
page: "home",
|
||||
target: "brand",
|
||||
previewTargets: [
|
||||
{
|
||||
key: "food.home.brand-card",
|
||||
label: "品牌信息区",
|
||||
composite: true,
|
||||
children: ["food.home.identity", "food.home.location", "food.home.actions"],
|
||||
},
|
||||
{ key: "food.home.identity", label: "主理人身份" },
|
||||
{ key: "food.home.location", label: "服务地点" },
|
||||
{ key: "food.home.offerings-heading", label: "餐品区域标题" },
|
||||
{ key: "food.home.actions", label: "首页操作按钮" },
|
||||
],
|
||||
fields: [
|
||||
{
|
||||
key: "identity",
|
||||
binding: "brand.config.founder",
|
||||
previewTarget: "food.home.identity",
|
||||
label: "主理人姓名",
|
||||
input: "text",
|
||||
},
|
||||
{
|
||||
key: "stallTitle",
|
||||
binding: "brand.config.visualPresentation.home.stallTitle",
|
||||
previewTarget: "food.home.location",
|
||||
label: "出摊信息标题",
|
||||
input: "text",
|
||||
},
|
||||
{
|
||||
key: "stallTime",
|
||||
binding: "brand.config.visualPresentation.home.stallTime",
|
||||
previewTarget: "food.home.location",
|
||||
label: "营业时间说明",
|
||||
input: "text",
|
||||
},
|
||||
{
|
||||
key: "worksTitle",
|
||||
binding: "brand.config.visualPresentation.home.worksTitle",
|
||||
previewTarget: "food.home.offerings-heading",
|
||||
label: "招牌餐品标题",
|
||||
input: "text",
|
||||
},
|
||||
{
|
||||
key: "primaryAction",
|
||||
binding: "brand.config.visualPresentation.home.primaryAction",
|
||||
previewTarget: "food.home.actions",
|
||||
label: "咨询按钮",
|
||||
input: "text",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ page }) => {
|
||||
let rejectOfferingSave = false;
|
||||
await page.setViewportSize({ width: 1920, height: 1000 });
|
||||
await page.route("http://localhost:3001/public/workspace**", (route) =>
|
||||
route.fulfill({ json: runtimeWorkspace }),
|
||||
);
|
||||
await page.route("**/api/**", async (route) => {
|
||||
const request = route.request();
|
||||
const url = new URL(request.url());
|
||||
url.pathname = url.pathname.replace(/^\/api/, "");
|
||||
if (url.pathname === "/admin/session/login")
|
||||
return route.fulfill({
|
||||
json: {
|
||||
token: "fixture-token",
|
||||
displayName: "测试管理员",
|
||||
role: "owner",
|
||||
mustChangePassword: false,
|
||||
},
|
||||
});
|
||||
if (url.pathname === "/admin/brands")
|
||||
return route.fulfill({ json: [{ id: brand.id, role: "owner", brand }] });
|
||||
if (url.pathname === "/admin/config/brand" && request.method() === "PATCH") {
|
||||
Object.assign(brand, request.postDataJSON());
|
||||
Object.assign(runtimeWorkspace.brand, brand);
|
||||
return route.fulfill({ json: brand });
|
||||
}
|
||||
if (url.pathname === "/admin/config/brand") return route.fulfill({ json: brand });
|
||||
if (url.pathname === "/admin/workspace/offerings")
|
||||
return route.fulfill({ json: [adminOffering] });
|
||||
if (url.pathname === "/admin/workspace/forms")
|
||||
return route.fulfill({
|
||||
json: [
|
||||
{
|
||||
id: "brand-inquiry",
|
||||
name: "品牌咨询",
|
||||
version: 1,
|
||||
isEnabled: true,
|
||||
purpose: "inquiry",
|
||||
targetType: "brand",
|
||||
submissionAction: "create-inquiry",
|
||||
fieldsSnapshot: runtimeWorkspace.inquiryForms[0].fields,
|
||||
},
|
||||
],
|
||||
});
|
||||
if (
|
||||
url.pathname === `/admin/workspace/offerings/${adminOffering.id}` &&
|
||||
request.method() === "PATCH"
|
||||
) {
|
||||
if (rejectOfferingSave) {
|
||||
rejectOfferingSave = false;
|
||||
return route.fulfill({
|
||||
status: 500,
|
||||
json: {
|
||||
error: { message: "保存暂时失败,请重试", code: "TEST_FAILURE", requestId: "fixture" },
|
||||
},
|
||||
});
|
||||
}
|
||||
Object.assign(adminOffering, request.postDataJSON());
|
||||
Object.assign(runtimeWorkspace.offerings[0], {
|
||||
name: adminOffering.name,
|
||||
summary: adminOffering.summary,
|
||||
});
|
||||
return route.fulfill({ json: adminOffering });
|
||||
}
|
||||
if (url.pathname === "/admin/config/trust-content")
|
||||
return route.fulfill({ json: [adminTrust] });
|
||||
if (
|
||||
url.pathname === `/admin/config/trust-content/${adminTrust.id}` &&
|
||||
request.method() === "PATCH"
|
||||
) {
|
||||
Object.assign(adminTrust, request.postDataJSON());
|
||||
Object.assign(runtimeWorkspace.trustItems[0], {
|
||||
title: adminTrust.title,
|
||||
config: adminTrust.config,
|
||||
});
|
||||
return route.fulfill({ json: adminTrust });
|
||||
}
|
||||
if (url.pathname === "/admin/workspace")
|
||||
return route.fulfill({
|
||||
json: { brand, installations: [], fields: [], offerings: [], forms: [], templateContent },
|
||||
});
|
||||
if (url.pathname === "/admin/workspace/preview")
|
||||
return route.fulfill({ json: runtimeWorkspace });
|
||||
if (url.pathname === "/public/templates/food")
|
||||
return route.fulfill({
|
||||
json: { name: "餐饮模板", description: "fixture", serviceCategories: [] },
|
||||
});
|
||||
if (url.pathname === "/public/workspace") return route.fulfill({ json: runtimeWorkspace });
|
||||
return route.fulfill({ json: {} });
|
||||
});
|
||||
|
||||
await page.goto(`${adminOrigin}/admin/brand`);
|
||||
await page.getByLabel("账号").fill("admin");
|
||||
await page.getByLabel("密码").fill("fixture-password");
|
||||
await page.locator('button[type="submit"]').click();
|
||||
await expect(page.getByText("小程序页面配置")).toBeVisible();
|
||||
await expect(page.getByLabel("品牌名称", { exact: true })).toBeHidden();
|
||||
await page.getByText("品牌资料", { exact: true }).last().click();
|
||||
await expect(page.getByLabel("品牌名称", { exact: true })).toBeVisible();
|
||||
await page.getByText("页面编辑", { exact: true }).click();
|
||||
const preview = page.locator(".component-template-preview");
|
||||
await expect(preview.locator(".food-home .name")).toContainText("测试主理人");
|
||||
await expect(page.getByText("选择要编辑的区域", { exact: true })).toBeVisible();
|
||||
for (const width of [1920, 1280, 1024, 768, 390]) {
|
||||
await page.setViewportSize({ width, height: 1000 });
|
||||
const editor = page.locator(".presentation-editor");
|
||||
await editor.scrollIntoViewIfNeeded();
|
||||
await expect
|
||||
.poll(() => editor.evaluate((element) => element.scrollWidth - element.clientWidth))
|
||||
.toBeLessThanOrEqual(1);
|
||||
await editor.screenshot({
|
||||
path: "../../.codex-tasks/admin-editor-workspace/raw/editor-" + width + ".png",
|
||||
});
|
||||
}
|
||||
await page.setViewportSize({ width: 1920, height: 1000 });
|
||||
|
||||
await page.getByRole("button", { name: "选择品牌信息区" }).click();
|
||||
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
|
||||
"data-selected-target",
|
||||
"food.home.brand-card",
|
||||
);
|
||||
await expect(page.getByRole("button", { name: "编辑主理人身份" })).toBeVisible();
|
||||
await page.getByRole("button", { name: "编辑服务地点" }).click();
|
||||
await expect(page.getByLabel("出摊信息标题")).toBeVisible();
|
||||
await page.getByRole("button", { name: "选择品牌信息区" }).click();
|
||||
await page.getByRole("button", { name: "编辑主理人身份" }).click();
|
||||
await expect(page.getByLabel("主理人姓名")).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
const dimensions = await preview.evaluate((element) => {
|
||||
const canvas = element.querySelector(".component-template-preview__canvas")!;
|
||||
const name = element.querySelector(".name")!;
|
||||
const avatar = element.querySelector(".identity img")!;
|
||||
return {
|
||||
width: canvas.getBoundingClientRect().width,
|
||||
font: parseFloat(getComputedStyle(name).fontSize),
|
||||
avatar: avatar.getBoundingClientRect().width,
|
||||
transform: getComputedStyle(canvas.firstElementChild!).transform,
|
||||
};
|
||||
});
|
||||
expect(dimensions.font / dimensions.width).toBeCloseTo(32 / 750, 3);
|
||||
expect(dimensions.avatar / dimensions.width).toBeCloseTo(128 / 750, 3);
|
||||
expect(dimensions.transform).toBe("none");
|
||||
await expect
|
||||
.poll(() =>
|
||||
preview.locator(".identity img").evaluate((image: HTMLImageElement) => image.naturalWidth),
|
||||
)
|
||||
.toBeGreaterThan(0);
|
||||
await preview.screenshot({ path: "../../.codex-tasks/preview-proportion/home.png" });
|
||||
const actionButtons = preview.locator(".food-home .actions button");
|
||||
await expect(actionButtons).toHaveCount(2);
|
||||
const previewBox = await preview.locator(".component-template-preview__canvas").boundingBox();
|
||||
const firstActionBox = await actionButtons.nth(0).boundingBox();
|
||||
const secondActionBox = await actionButtons.nth(1).boundingBox();
|
||||
expect(previewBox && firstActionBox && secondActionBox).toBeTruthy();
|
||||
expect(firstActionBox!.x).toBeGreaterThanOrEqual(previewBox!.x);
|
||||
expect(secondActionBox!.x + secondActionBox!.width).toBeLessThanOrEqual(
|
||||
previewBox!.x + previewBox!.width,
|
||||
);
|
||||
await expect(actionButtons.nth(0)).toContainText("咨询 / 预订");
|
||||
await expect(actionButtons.nth(1)).toContainText("查看餐品");
|
||||
await page.getByRole("button", { name: "选择品牌信息区" }).click();
|
||||
await page.getByRole("button", { name: "编辑首页操作按钮" }).click();
|
||||
await expect(page.getByLabel("咨询按钮")).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await page.getByRole("button", { name: "选择品牌信息区" }).click();
|
||||
await page.getByRole("button", { name: "编辑服务地点" }).click();
|
||||
await expect(page.getByText("出摊信息标题")).toBeVisible();
|
||||
await expect(page.getByText("招牌餐品标题")).toHaveCount(0);
|
||||
await page.getByLabel("出摊信息标题").fill("后台草稿地点");
|
||||
await expect(preview.locator(".notice-title")).toContainText("后台草稿地点");
|
||||
await page.getByRole("button", { name: "保存页面内容" }).click();
|
||||
await expect(page.getByText("页面内容已保存为草稿,发布后小程序才会更新")).toBeVisible();
|
||||
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
|
||||
"data-selected-target",
|
||||
"food.home.location",
|
||||
);
|
||||
await page.getByRole("button", { name: "浏览页面" }).click();
|
||||
await preview.locator(".food-home .actions button").nth(1).click();
|
||||
await expect(page.getByText("招牌餐品标题")).toHaveCount(0);
|
||||
await page.getByRole("button", { name: "点选编辑" }).click();
|
||||
await page.getByRole("button", { name: "选择品牌信息区" }).click();
|
||||
await page.getByRole("button", { name: "编辑服务地点" }).click();
|
||||
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
|
||||
"data-selected-target",
|
||||
"food.home.location",
|
||||
);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveCount(0);
|
||||
await page.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("修改后的主理人");
|
||||
});
|
||||
@@ -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 纳入正式部署流水线。
|
||||
@@ -0,0 +1,29 @@
|
||||
# 0021 Admin 品牌配置与页面编辑工作区
|
||||
|
||||
## 背景
|
||||
|
||||
品牌基础资料、模板说明和可视化编辑被多个 Card 包裹,预览仅占页面的一部分。用户难以理解编辑入口与实际展示之间的关系。
|
||||
|
||||
## 决策
|
||||
|
||||
工作台默认进入页面编辑,通过顶部视图切换访问品牌资料。编辑器采用左侧区域导航、中间预览、右侧属性编辑三栏布局,窄屏堆叠。组合区域的子区域在导航中缩进,并与画布选区同步。视图切换保持组件挂载,避免丢弃未保存输入。发布操作通过顶部入口进入已有发布流程。
|
||||
|
||||
品牌基础资料使用连续的身份、联系合作和视觉分组。模板说明作为基础配置的辅助信息。页面编辑工作区使用完整页面宽度,页面导航位于顶部,预览与选区面板并列,窄屏上下排列。未选择区域时提供明确的点选引导,避免展示整页字段。
|
||||
|
||||
详情页只提供业务记录选择和动态预览,隐藏区域列表和点选工具;业务记录在业务提供项中维护。模板 manifest 的字段声明继续供业务内容编辑器和模板校验使用。
|
||||
|
||||
## 替代方案
|
||||
|
||||
继续嵌套 Card 会保留视觉层级混乱。单独建立第二套预览页面会造成 renderer 与模板实际展示分离。采用现有 renderer 和表单机制可以复用既有契约。
|
||||
|
||||
## 后果
|
||||
|
||||
配置与预览的空间更明确,区域编辑仍由模板声明驱动。基础品牌信息与模板区域保存仍分别执行,保存后的内容是草稿,需要发布才能公开展示。没有可编辑区域的页面不显示点选工具。
|
||||
|
||||
## 迁移计划
|
||||
|
||||
仅调整 Admin 布局与详情页编辑入口,不迁移数据库。使用已有字段绑定和 API,并通过多宽度截图、真实鼠标交互、类型检查、lint 和生产构建验收。
|
||||
|
||||
## 已知后续项
|
||||
|
||||
Admin 生产构建的共享 api chunk 超过 500 kB。由 Admin 前端后续打包优化任务负责拆分,当前构建成功。
|
||||
+13
-2
@@ -21,10 +21,21 @@ location /api/ {
|
||||
}
|
||||
```
|
||||
|
||||
构建管理后台时使用:
|
||||
生产构建会先把所有已接入模板的 H5 renderer 编译进一个静态预览应用,再将其放到 Admin 的 `/template-preview/` 下。线上无需启动 Vite,也无需为每个模板运行单独服务。构建管理后台与预览应用时使用:
|
||||
|
||||
```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`。
|
||||
@@ -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,必要结构调整先制定兼容迁移。
|
||||
@@ -12,6 +12,7 @@ export default tseslint.config(
|
||||
"apps/api/test/**/*.test.js",
|
||||
"apps/api/test/**/*.cjs",
|
||||
"apps/admin/test/**/*.test.mjs",
|
||||
"apps/admin/public/**",
|
||||
"packages/types/test/**/*.test.mjs",
|
||||
"apps/taro/test/**/*.test.mjs",
|
||||
"apps/taro/src/assets/**",
|
||||
@@ -53,4 +54,8 @@ export default tseslint.config(
|
||||
"@typescript-eslint/require-await": "off",
|
||||
},
|
||||
},
|
||||
{
|
||||
...tseslint.configs.disableTypeChecked,
|
||||
files: ["apps/admin/template-preview-css.mjs"],
|
||||
},
|
||||
);
|
||||
@@ -26,6 +26,8 @@
|
||||
"clean": "turbo run clean && rimraf node_modules .turbo",
|
||||
"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:templates": "pnpm --filter @personal-brand/taro dev:preview",
|
||||
"build:admin:preview": "PREVIEW_ALL_TEMPLATES=true API_BASE_URL=/api PREVIEW_PUBLIC_PATH=/template-preview/ pnpm --filter @personal-brand/taro build:preview && node scripts/package-template-preview.cjs && VITE_APP_BASE_PATH=/admin/ VITE_API_BASE_URL=/api pnpm --filter @personal-brand/admin build",
|
||||
"build:taro:food": "pnpm --filter @personal-brand/taro build:h5 && pnpm --filter @personal-brand/taro build:weapp",
|
||||
"build:taro:linjing": "TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:h5 && TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:weapp"
|
||||
},
|
||||
|
||||
@@ -11,9 +11,15 @@ import type {
|
||||
RuntimeTrustItem,
|
||||
ThemeManifest,
|
||||
} from "@personal-brand/types";
|
||||
export { projectBrandAliases, projectTrustPresentation } from "@personal-brand/types";
|
||||
export type { PublicOffering } from "@personal-brand/types";
|
||||
export type { BookingStatus } from "@personal-brand/types";
|
||||
export type { BrandTemplateKey } from "@personal-brand/types";
|
||||
export type {
|
||||
EditorPreviewFrameMessage,
|
||||
EditorPreviewHostMessage,
|
||||
RuntimeWorkspace,
|
||||
} from "@personal-brand/types";
|
||||
|
||||
export interface BrandProfile {
|
||||
id: string;
|
||||
@@ -92,6 +98,7 @@ export interface TemplateAdminField {
|
||||
maxLength?: number;
|
||||
placeholder?: string;
|
||||
options?: Array<{ value: string; label: string }>;
|
||||
previewTarget?: string;
|
||||
}
|
||||
|
||||
export interface TemplateAdminSection {
|
||||
@@ -100,6 +107,12 @@ export interface TemplateAdminSection {
|
||||
description: string;
|
||||
page: string;
|
||||
target: "brand" | "offering" | "trust" | "inquiry";
|
||||
previewTargets?: Array<{
|
||||
key: string;
|
||||
label: string;
|
||||
composite?: boolean;
|
||||
children?: string[];
|
||||
}>;
|
||||
fields: TemplateAdminField[];
|
||||
}
|
||||
|
||||
@@ -685,6 +698,9 @@ export class ApiClient {
|
||||
}> {
|
||||
return this.request("/admin/workspace");
|
||||
}
|
||||
getAdminPreviewWorkspace(): Promise<import("@personal-brand/types").RuntimeWorkspace> {
|
||||
return this.request("/admin/workspace/preview");
|
||||
}
|
||||
listAdminReleases(): Promise<BrandReleaseSummary[]> {
|
||||
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 type { RuntimeWorkspace } from "@personal-brand/types";
|
||||
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 }) {
|
||||
const brand = workspace.brand;
|
||||
const p = presentation(workspace, "home");
|
||||
@@ -14,8 +15,8 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
return (
|
||||
<View className="food-home">
|
||||
<View className="page">
|
||||
<View className="brand-card">
|
||||
<View className="identity">
|
||||
<View className="brand-card" data-editor-target="food.home.brand-card">
|
||||
<View className="identity" data-editor-target="food.home.identity">
|
||||
{text(brand.avatarUrl) && <Image src={text(brand.avatarUrl)} mode="aspectFill" />}
|
||||
<View>
|
||||
<Text className="name">{text(brand.founder)}</Text>
|
||||
@@ -23,21 +24,21 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
<Text className="slogan">“{text(brand.description)}”</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View className="notice">
|
||||
<View className="notice" data-editor-target="food.home.location">
|
||||
<Text className="notice-title">{p.stallTitle || "服务地点"}</Text>
|
||||
<Text>{text(brand.address)}</Text>
|
||||
{p.stallTime && <Text className="notice-time">{p.stallTime}</Text>}
|
||||
</View>
|
||||
<View className="actions">
|
||||
<View className="actions" data-editor-target="food.home.actions">
|
||||
<Button className="home-action" onClick={() => navigate("inquiry")}>
|
||||
咨询 / 预订
|
||||
{p.primaryAction || "咨询 / 预订"}
|
||||
</Button>
|
||||
<Button className="home-action muted" onClick={() => navigate("offerings")}>
|
||||
查看餐品
|
||||
{p.secondaryAction || "查看餐品"}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
<View className="scene-wrap">
|
||||
<View className="scene-wrap" data-editor-target="food.home.hero">
|
||||
<View className="section-head">
|
||||
<Text className="eyebrow">{text(brand.name)}</Text>
|
||||
</View>
|
||||
@@ -50,13 +51,13 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
<View className="section-head">
|
||||
<View className="section-head" data-editor-target="food.home.offerings-heading">
|
||||
<View>
|
||||
<Text className="eyebrow">{p.worksEyebrow || "餐品与服务"}</Text>
|
||||
<Text className="heading">{p.worksTitle || "可选餐品"}</Text>
|
||||
</View>
|
||||
<Text className="more" onClick={() => navigate("offerings")}>
|
||||
查看全部 ›
|
||||
{p.moreAction || "查看全部"} ›
|
||||
</Text>
|
||||
</View>
|
||||
<View className="dish-grid">
|
||||
@@ -64,6 +65,8 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
<View
|
||||
className="dish"
|
||||
key={item.id}
|
||||
data-editor-target="acheng-campus-food.home.offering"
|
||||
data-editor-record-id={item.id}
|
||||
onClick={() => navigate("detail", { id: item.id })}
|
||||
>
|
||||
<Image src={item.image} mode="aspectFill" />
|
||||
@@ -75,11 +78,18 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
<Text className="heading manifesto-heading">{p.manifestoTitle}</Text>
|
||||
<View data-editor-target="food.home.promise-heading">
|
||||
<Text className="heading manifesto-heading">{p.manifestoTitle}</Text>
|
||||
</View>
|
||||
{workspace.trustItems
|
||||
.filter((item) => ["promise", "case"].includes(item.type))
|
||||
.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>
|
||||
{item.summary && <Text className="promise-title">{item.summary}</Text>}
|
||||
<Text className="quote">{item.content}</Text>
|
||||
@@ -113,10 +123,14 @@ function Service({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
].filter((row) => row.title && row.detail);
|
||||
const steps = rows(process?.config.steps).filter((step) => step.title && step.detail);
|
||||
return (
|
||||
<View className="food-service">
|
||||
<View className="food-service" data-editor-target="acheng-campus-food.service.service">
|
||||
<View className="page service-page">
|
||||
{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="head-title">
|
||||
<Image className="icon" src={asset("service/clock.png")} />
|
||||
@@ -149,7 +163,11 @@ function Service({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
</View>
|
||||
)}
|
||||
{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">
|
||||
<Image className="icon" src={asset("service/bike.png")} />
|
||||
<Text>{c.title}</Text>
|
||||
@@ -173,7 +191,11 @@ function Service({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
</View>
|
||||
)}
|
||||
{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">
|
||||
<Image className="icon" src={asset("service/list.png")} />
|
||||
<Text>{process.title}</Text>
|
||||
@@ -218,7 +240,7 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
const p = presentation(workspace, "profile");
|
||||
const credentials = workspace.trustItems.filter((item) => item.type === "credential");
|
||||
return (
|
||||
<View className="food-profile">
|
||||
<View className="food-profile" data-editor-target="acheng-campus-food.profile.identity">
|
||||
<View className="page">
|
||||
<View className="profile-card">
|
||||
<View className="portrait">
|
||||
@@ -234,7 +256,12 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
{text(brand.description) && <Text className="bio">{text(brand.description)}</Text>}
|
||||
{credentials.map((item) =>
|
||||
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) => (
|
||||
<View className="standard" key={index}>
|
||||
<Image
|
||||
@@ -249,7 +276,12 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
))}
|
||||
</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>
|
||||
{item.summary && <Text className="bio">{item.summary}</Text>}
|
||||
<Text className="bio">{item.content}</Text>
|
||||
@@ -261,7 +293,12 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
{workspace.trustItems
|
||||
.filter((item) => item.type === "case")
|
||||
.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">
|
||||
<Image className="heading-icon" src={asset("owner/handshake.png")} />
|
||||
<Text>{item.title}</Text>
|
||||
@@ -288,7 +325,12 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
{workspace.trustItems
|
||||
.filter((item) => item.type === "promise")
|
||||
.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">
|
||||
<Image className="promise-icon" src={asset("owner/clock.png")} />
|
||||
<Text>{item.title}</Text>
|
||||
@@ -338,13 +380,22 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
</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) {
|
||||
if (page === "home") return <Home workspace={workspace} />;
|
||||
if (page === "service") return <Service workspace={workspace} />;
|
||||
if (page === "profile") return <Profile workspace={workspace} />;
|
||||
if (page === "offerings") return <OfferingList workspace={workspace} />;
|
||||
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 }) {
|
||||
const p = presentation(workspace, "offerings");
|
||||
@@ -361,7 +412,7 @@ function OfferingList({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
.includes(query.trim().toLowerCase()),
|
||||
);
|
||||
return (
|
||||
<View className="food-list">
|
||||
<View className="food-list" data-editor-target="acheng-campus-food.offerings.menu">
|
||||
<View className="page">
|
||||
<View className="filters">
|
||||
<Button
|
||||
@@ -397,6 +448,8 @@ function OfferingList({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
<View
|
||||
className="offering-card"
|
||||
key={item.id}
|
||||
data-editor-target="acheng-campus-food.offerings.item"
|
||||
data-editor-record-id={item.id}
|
||||
onClick={() => navigate("detail", { id: item.id })}
|
||||
>
|
||||
<View className="dish-media">
|
||||
@@ -435,7 +488,11 @@ function Detail({ workspace, id }: { workspace: RuntimeWorkspace; id?: string })
|
||||
const item = offering(found);
|
||||
const p = presentation(workspace, "detail");
|
||||
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="hero-wrap">
|
||||
<Image
|
||||
@@ -452,7 +509,7 @@ function Detail({ workspace, id }: { workspace: RuntimeWorkspace; id?: string })
|
||||
<Text>{item.series}</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View className="content">
|
||||
<View className="content" data-editor-target="acheng-campus-food.detail.detailCopy">
|
||||
<View className="price-card">
|
||||
<View>
|
||||
<Text>{p.priceLabel || "参考价格"}</Text>
|
||||
|
||||
@@ -144,7 +144,8 @@
|
||||
"label": "主理人姓名",
|
||||
"input": "text",
|
||||
"required": true,
|
||||
"placeholder": "例如:阿成"
|
||||
"placeholder": "例如:阿成",
|
||||
"previewTarget": "acheng-campus-food.profile.identity"
|
||||
},
|
||||
{
|
||||
"key": "title",
|
||||
@@ -152,33 +153,87 @@
|
||||
"label": "你的身份",
|
||||
"help": "例如:校园餐饮主理人。",
|
||||
"input": "text",
|
||||
"required": true
|
||||
"required": true,
|
||||
"previewTarget": "acheng-campus-food.profile.identity"
|
||||
},
|
||||
{
|
||||
"key": "badge",
|
||||
"binding": "brand.config.visualPresentation.profile.badge",
|
||||
"label": "写真角标",
|
||||
"input": "text",
|
||||
"help": "显示在主理人写真上,可填写经验或服务定位。"
|
||||
"help": "显示在主理人写真上,可填写经验或服务定位。",
|
||||
"previewTarget": "acheng-campus-food.profile.identity"
|
||||
},
|
||||
{
|
||||
"key": "storyLead",
|
||||
"binding": "brand.config.visualPresentation.profile.storyLead",
|
||||
"label": "故事引言",
|
||||
"input": "textarea",
|
||||
"help": "故事开头的强调段落,下面的正文使用品牌简介。"
|
||||
"help": "故事开头的强调段落,下面的正文使用品牌简介。",
|
||||
"previewTarget": "acheng-campus-food.profile.identity"
|
||||
},
|
||||
{
|
||||
"key": "recordsTitle",
|
||||
"binding": "brand.config.visualPresentation.profile.recordsTitle",
|
||||
"label": "记录入口文案",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.profile.identity"
|
||||
},
|
||||
{
|
||||
"key": "recordsCountUnit",
|
||||
"binding": "brand.config.visualPresentation.profile.recordsCountUnit",
|
||||
"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": "首页业务卡片"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -188,9 +243,56 @@
|
||||
"description": "说明今天在哪里、何时营业,以及餐品有什么特点。",
|
||||
"page": "home",
|
||||
"target": "brand",
|
||||
"previewTargets": [
|
||||
{
|
||||
"key": "food.home.brand-card",
|
||||
"label": "品牌信息区",
|
||||
"composite": true,
|
||||
"children": ["food.home.identity", "food.home.location", "food.home.actions"]
|
||||
},
|
||||
{
|
||||
"key": "food.home.identity",
|
||||
"label": "主理人身份"
|
||||
},
|
||||
{
|
||||
"key": "food.home.location",
|
||||
"label": "服务地点"
|
||||
},
|
||||
{
|
||||
"key": "food.home.hero",
|
||||
"label": "出摊现场图片"
|
||||
},
|
||||
{
|
||||
"key": "food.home.offerings-heading",
|
||||
"label": "餐品区域标题"
|
||||
},
|
||||
{
|
||||
"key": "food.home.actions",
|
||||
"label": "首页操作按钮"
|
||||
},
|
||||
{
|
||||
"key": "food.home.promise-heading",
|
||||
"label": "出餐承诺标题"
|
||||
}
|
||||
],
|
||||
"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",
|
||||
"previewTarget": "food.home.location",
|
||||
"binding": "brand.config.visualPresentation.home.stallTitle",
|
||||
"label": "出摊信息标题",
|
||||
"input": "text",
|
||||
@@ -198,6 +300,7 @@
|
||||
},
|
||||
{
|
||||
"key": "heroImage",
|
||||
"previewTarget": "food.home.hero",
|
||||
"binding": "brand.config.heroImage",
|
||||
"label": "出摊现场主图",
|
||||
"help": "展示真实摊位、餐品或取餐场景,建议使用横向图片。",
|
||||
@@ -206,6 +309,7 @@
|
||||
},
|
||||
{
|
||||
"key": "stallTime",
|
||||
"previewTarget": "food.home.location",
|
||||
"binding": "brand.config.visualPresentation.home.stallTime",
|
||||
"label": "营业时间说明",
|
||||
"input": "text",
|
||||
@@ -213,18 +317,42 @@
|
||||
},
|
||||
{
|
||||
"key": "worksEyebrow",
|
||||
"previewTarget": "food.home.offerings-heading",
|
||||
"binding": "brand.config.visualPresentation.home.worksEyebrow",
|
||||
"label": "餐品区域小标题",
|
||||
"input": "text"
|
||||
},
|
||||
{
|
||||
"key": "worksTitle",
|
||||
"previewTarget": "food.home.offerings-heading",
|
||||
"binding": "brand.config.visualPresentation.home.worksTitle",
|
||||
"label": "招牌餐品标题",
|
||||
"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",
|
||||
"previewTarget": "food.home.promise-heading",
|
||||
"binding": "brand.config.visualPresentation.home.manifestoTitle",
|
||||
"label": "出餐承诺标题",
|
||||
"input": "text"
|
||||
@@ -243,7 +371,57 @@
|
||||
"binding": "brand.config.visualPresentation.service.processAction",
|
||||
"label": "流程咨询按钮",
|
||||
"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": "业务卡片"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -258,21 +436,30 @@
|
||||
"key": "title",
|
||||
"binding": "brand.config.visualPresentation.offerings.title",
|
||||
"label": "菜单页标题",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.offerings.menu"
|
||||
},
|
||||
{
|
||||
"key": "subtitle",
|
||||
"binding": "brand.config.visualPresentation.offerings.subtitle",
|
||||
"label": "菜单页说明",
|
||||
"input": "textarea",
|
||||
"maxLength": 120
|
||||
"maxLength": 120,
|
||||
"previewTarget": "acheng-campus-food.offerings.menu"
|
||||
},
|
||||
{
|
||||
"key": "menuTip",
|
||||
"binding": "brand.config.visualPresentation.offerings.menuTip",
|
||||
"label": "菜单提示",
|
||||
"help": "只填写当前实际提供的取餐、加菜或定制服务。",
|
||||
"input": "textarea"
|
||||
"input": "textarea",
|
||||
"previewTarget": "acheng-campus-food.offerings.menu"
|
||||
}
|
||||
],
|
||||
"previewTargets": [
|
||||
{
|
||||
"key": "acheng-campus-food.offerings.menu",
|
||||
"label": "菜单页说明"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -287,28 +474,38 @@
|
||||
"key": "title",
|
||||
"binding": "brand.config.visualPresentation.inquiry.title",
|
||||
"label": "预订页面标题",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.inquiry.booking"
|
||||
},
|
||||
{
|
||||
"key": "subtitle",
|
||||
"binding": "brand.config.visualPresentation.inquiry.subtitle",
|
||||
"label": "预订说明",
|
||||
"input": "textarea",
|
||||
"maxLength": 120
|
||||
"maxLength": 120,
|
||||
"previewTarget": "acheng-campus-food.inquiry.booking"
|
||||
},
|
||||
{
|
||||
"key": "submitLabel",
|
||||
"binding": "brand.config.visualPresentation.inquiry.submitLabel",
|
||||
"label": "提交按钮文字",
|
||||
"input": "text",
|
||||
"placeholder": "例如:提交预订需求"
|
||||
"placeholder": "例如:提交预订需求",
|
||||
"previewTarget": "acheng-campus-food.inquiry.booking"
|
||||
},
|
||||
{
|
||||
"key": "promise",
|
||||
"binding": "brand.config.visualPresentation.inquiry.promise",
|
||||
"label": "真实服务承诺",
|
||||
"help": "仅填写能兑现的回复时间、订金和联系规则;留空则不显示。",
|
||||
"input": "textarea"
|
||||
"input": "textarea",
|
||||
"previewTarget": "acheng-campus-food.inquiry.booking"
|
||||
}
|
||||
],
|
||||
"previewTargets": [
|
||||
{
|
||||
"key": "acheng-campus-food.inquiry.booking",
|
||||
"label": "预订与定制"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -323,43 +520,50 @@
|
||||
"key": "categoryLabel",
|
||||
"binding": "offering.config.categoryLabel",
|
||||
"label": "餐品类别",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.detail.dishDetail"
|
||||
},
|
||||
{
|
||||
"key": "detailHero",
|
||||
"binding": "offering.config.detailHero",
|
||||
"label": "详情主图",
|
||||
"input": "image"
|
||||
"input": "image",
|
||||
"previewTarget": "acheng-campus-food.detail.dishDetail"
|
||||
},
|
||||
{
|
||||
"key": "area",
|
||||
"binding": "offering.config.area",
|
||||
"label": "供应地点",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.detail.dishDetail"
|
||||
},
|
||||
{
|
||||
"key": "series",
|
||||
"binding": "offering.config.series",
|
||||
"label": "套餐或系列说明",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.detail.dishDetail"
|
||||
},
|
||||
{
|
||||
"key": "spaceType",
|
||||
"binding": "offering.config.spaceType",
|
||||
"label": "适合场景",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.detail.dishDetail"
|
||||
},
|
||||
{
|
||||
"key": "background",
|
||||
"binding": "offering.config.details.background",
|
||||
"label": "餐品介绍",
|
||||
"input": "textarea"
|
||||
"input": "textarea",
|
||||
"previewTarget": "acheng-campus-food.detail.dishDetail"
|
||||
},
|
||||
{
|
||||
"key": "designConcept",
|
||||
"binding": "offering.config.details.designConcept",
|
||||
"label": "口味与分量",
|
||||
"input": "textarea"
|
||||
"input": "textarea",
|
||||
"previewTarget": "acheng-campus-food.detail.dishDetail"
|
||||
},
|
||||
{
|
||||
"key": "keywords",
|
||||
@@ -372,7 +576,8 @@
|
||||
"key": "value",
|
||||
"label": "特色"
|
||||
}
|
||||
]
|
||||
],
|
||||
"previewTarget": "acheng-campus-food.detail.dishDetail"
|
||||
},
|
||||
{
|
||||
"key": "crafts",
|
||||
@@ -385,7 +590,8 @@
|
||||
"key": "value",
|
||||
"label": "制作说明"
|
||||
}
|
||||
]
|
||||
],
|
||||
"previewTarget": "acheng-campus-food.detail.dishDetail"
|
||||
},
|
||||
{
|
||||
"key": "materialsList",
|
||||
@@ -401,7 +607,14 @@
|
||||
"key": "spec",
|
||||
"label": "说明"
|
||||
}
|
||||
]
|
||||
],
|
||||
"previewTarget": "acheng-campus-food.detail.dishDetail"
|
||||
}
|
||||
],
|
||||
"previewTargets": [
|
||||
{
|
||||
"key": "acheng-campus-food.detail.dishDetail",
|
||||
"label": "餐品与服务详情"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -416,50 +629,64 @@
|
||||
"key": "priceLabel",
|
||||
"binding": "brand.config.visualPresentation.detail.priceLabel",
|
||||
"label": "价格说明标题",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.detail.detailCopy"
|
||||
},
|
||||
{
|
||||
"key": "spaceLabel",
|
||||
"binding": "brand.config.visualPresentation.detail.spaceLabel",
|
||||
"label": "适合场景标题",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.detail.detailCopy"
|
||||
},
|
||||
{
|
||||
"key": "backgroundTitle",
|
||||
"binding": "brand.config.visualPresentation.detail.backgroundTitle",
|
||||
"label": "餐品介绍标题",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.detail.detailCopy"
|
||||
},
|
||||
{
|
||||
"key": "conceptTitle",
|
||||
"binding": "brand.config.visualPresentation.detail.conceptTitle",
|
||||
"label": "口味与分量标题",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.detail.detailCopy"
|
||||
},
|
||||
{
|
||||
"key": "craftsTitle",
|
||||
"binding": "brand.config.visualPresentation.detail.craftsTitle",
|
||||
"label": "制作方式标题",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.detail.detailCopy"
|
||||
},
|
||||
{
|
||||
"key": "materialsTitle",
|
||||
"binding": "brand.config.visualPresentation.detail.materialsTitle",
|
||||
"label": "食材与搭配标题",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.detail.detailCopy"
|
||||
},
|
||||
{
|
||||
"key": "inquiryAction",
|
||||
"binding": "brand.config.visualPresentation.detail.inquiryAction",
|
||||
"label": "咨询按钮文字",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.detail.detailCopy"
|
||||
},
|
||||
{
|
||||
"key": "inquiryHint",
|
||||
"binding": "brand.config.visualPresentation.detail.inquiryHint",
|
||||
"label": "咨询后的处理说明",
|
||||
"help": "只写能够兑现的联系和确认方式。",
|
||||
"input": "textarea"
|
||||
"input": "textarea",
|
||||
"previewTarget": "acheng-campus-food.detail.detailCopy"
|
||||
}
|
||||
],
|
||||
"previewTargets": [
|
||||
{
|
||||
"key": "acheng-campus-food.detail.detailCopy",
|
||||
"label": "详情页说明"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -474,32 +701,43 @@
|
||||
"key": "eyebrow",
|
||||
"binding": "brand.config.visualPresentation.success.eyebrow",
|
||||
"label": "页面小标题",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.success.successCopy"
|
||||
},
|
||||
{
|
||||
"key": "title",
|
||||
"binding": "brand.config.visualPresentation.success.title",
|
||||
"label": "确认标题",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.success.successCopy"
|
||||
},
|
||||
{
|
||||
"key": "intro",
|
||||
"binding": "brand.config.visualPresentation.success.intro",
|
||||
"label": "后续联系说明",
|
||||
"help": "若写回复时间,请确认日常能兑现。",
|
||||
"input": "textarea"
|
||||
"input": "textarea",
|
||||
"previewTarget": "acheng-campus-food.success.successCopy"
|
||||
},
|
||||
{
|
||||
"key": "recordsAction",
|
||||
"binding": "brand.config.visualPresentation.success.recordsAction",
|
||||
"label": "查看记录按钮",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.success.successCopy"
|
||||
},
|
||||
{
|
||||
"key": "homeAction",
|
||||
"binding": "brand.config.visualPresentation.success.homeAction",
|
||||
"label": "返回首页按钮",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.success.successCopy"
|
||||
}
|
||||
],
|
||||
"previewTargets": [
|
||||
{
|
||||
"key": "acheng-campus-food.success.successCopy",
|
||||
"label": "提交成功页"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -514,31 +752,42 @@
|
||||
"key": "title",
|
||||
"binding": "brand.config.visualPresentation.records.title",
|
||||
"label": "记录页标题",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.records.recordsCopy"
|
||||
},
|
||||
{
|
||||
"key": "createAction",
|
||||
"binding": "brand.config.visualPresentation.records.createAction",
|
||||
"label": "新增咨询按钮",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.records.recordsCopy"
|
||||
},
|
||||
{
|
||||
"key": "emptyTitle",
|
||||
"binding": "brand.config.visualPresentation.records.emptyTitle",
|
||||
"label": "暂无记录标题",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.records.recordsCopy"
|
||||
},
|
||||
{
|
||||
"key": "emptyDescription",
|
||||
"binding": "brand.config.visualPresentation.records.emptyDescription",
|
||||
"label": "暂无记录说明",
|
||||
"input": "textarea"
|
||||
"input": "textarea",
|
||||
"previewTarget": "acheng-campus-food.records.recordsCopy"
|
||||
},
|
||||
{
|
||||
"key": "emptyAction",
|
||||
"binding": "brand.config.visualPresentation.records.emptyAction",
|
||||
"label": "空状态按钮",
|
||||
"input": "text"
|
||||
"input": "text",
|
||||
"previewTarget": "acheng-campus-food.records.recordsCopy"
|
||||
}
|
||||
],
|
||||
"previewTargets": [
|
||||
{
|
||||
"key": "acheng-campus-food.records.recordsCopy",
|
||||
"label": "咨询记录页"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -66,6 +66,8 @@ export type TemplateAdminField = {
|
||||
maxLength?: number;
|
||||
placeholder?: string;
|
||||
options?: Array<{ value: string; label: string }>;
|
||||
/** Stable visual-region identifier declared by the owning Admin section. */
|
||||
previewTarget?: string;
|
||||
};
|
||||
|
||||
/** 模板自己的浅层品牌字段,值存于 BrandProfile.config.templateData。 */
|
||||
@@ -83,6 +85,14 @@ export type TemplateAdminSection = {
|
||||
/** Exact Mini Program page that displays this section's content. */
|
||||
page: TemplatePageKey;
|
||||
target: "brand" | "offering" | "trust" | "inquiry";
|
||||
/** Visual regions rendered by this section's page. */
|
||||
previewTargets?: Array<{
|
||||
key: string;
|
||||
label: string;
|
||||
/** 组合区域只负责承载和导航,不重复声明可编辑字段。 */
|
||||
composite?: boolean;
|
||||
children?: string[];
|
||||
}>;
|
||||
fields: TemplateAdminField[];
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
const templateDirectories = fs
|
||||
.readdirSync(path.join(root, "packages"))
|
||||
.filter(
|
||||
(directory) =>
|
||||
directory.startsWith("template-") &&
|
||||
fs.existsSync(path.join(root, "packages", directory, "template.json")),
|
||||
);
|
||||
|
||||
for (const directory of templateDirectories) {
|
||||
const manifest = JSON.parse(
|
||||
fs.readFileSync(path.join(root, "packages", directory, "template.json"), "utf8"),
|
||||
);
|
||||
const rendererPath = path.join(root, "packages", directory, "taro/index.tsx");
|
||||
|
||||
test(`${manifest.packageKey} preview targets match manifest and renderer`, () => {
|
||||
const sections = manifest.admin.sections;
|
||||
const targets = sections.flatMap((section) =>
|
||||
(section.previewTargets ?? []).map((target) => ({ ...target, page: section.page, section })),
|
||||
);
|
||||
const keys = targets.map((target) => target.key);
|
||||
assert.equal(new Set(keys).size, keys.length, "preview target keys must be unique");
|
||||
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
assert.ok(field.binding, `${section.key}.${field.key} must have an editable binding`);
|
||||
assert.ok(field.previewTarget, `${section.key}.${field.key} must map to a visual region`);
|
||||
assert.ok(
|
||||
section.previewTargets?.some((target) => target.key === field.previewTarget),
|
||||
`${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)
|
||||
if (!target.composite)
|
||||
assert.ok(
|
||||
target.section.fields.some((field) => field.previewTarget === target.key),
|
||||
`${target.key} must map to at least one editable field`,
|
||||
);
|
||||
|
||||
if (!targets.length) return;
|
||||
assert.ok(fs.existsSync(rendererPath), "templates with preview targets need a Taro renderer");
|
||||
const renderer = fs.readFileSync(rendererPath, "utf8");
|
||||
for (const target of targets)
|
||||
assert.ok(
|
||||
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}`,
|
||||
);
|
||||
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,9 +19,9 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
const credential = slot(workspace, "credential");
|
||||
const t = workspace.trustPresentation;
|
||||
return (
|
||||
<View className="editorial-home">
|
||||
<View className="editorial-home" data-editor-target="linjing-editorial.home.home">
|
||||
<View className="page">
|
||||
<View className="founder-card">
|
||||
<View className="founder-card" data-editor-target="editorial.home.identity">
|
||||
{text(b.avatarUrl) && (
|
||||
<Image className="avatar" src={text(b.avatarUrl)} mode="aspectFill" />
|
||||
)}
|
||||
@@ -32,7 +32,11 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
</View>
|
||||
{p.founderBadge && <Text className="badge">{p.founderBadge}</Text>}
|
||||
</View>
|
||||
<View className="hero" onClick={() => navigate("offerings")}>
|
||||
<View
|
||||
className="hero"
|
||||
data-editor-target="editorial.home.hero"
|
||||
onClick={() => navigate("offerings")}
|
||||
>
|
||||
<Image className="hero-image" src={text(b.heroImage)} mode="aspectFill" />
|
||||
<View className="hero-shade" />
|
||||
<View className="hero-copy">
|
||||
@@ -46,10 +50,16 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
<Text className="hero-button">{text(hero.cta) || "查看作品"}</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View className="intro">
|
||||
<View className="intro" data-editor-target="editorial.home.proof">
|
||||
<Text className="eyebrow dark">{p.proofEyebrow}</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">
|
||||
{t.stats?.map((item, index) => (
|
||||
<View key={index}>
|
||||
@@ -60,7 +70,7 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
<View className="trust">
|
||||
<View className="trust" data-editor-target="editorial.home.manifesto">
|
||||
<Text className="eyebrow">{p.manifestoEyebrow}</Text>
|
||||
<Text className="section-title light">{p.manifestoTitle}</Text>
|
||||
{t.pillars?.map((item, index) => (
|
||||
@@ -71,7 +81,7 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
))}
|
||||
</View>
|
||||
<View className="section">
|
||||
<View className="section-head">
|
||||
<View className="section-head" data-editor-target="editorial.home.works">
|
||||
<View>
|
||||
<Text className="eyebrow dark">{p.worksEyebrow}</Text>
|
||||
<Text className="section-title">{p.worksTitle}</Text>
|
||||
@@ -84,6 +94,8 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
<View
|
||||
className="work-card"
|
||||
key={item.id}
|
||||
data-editor-target="linjing-editorial.home.offering"
|
||||
data-editor-record-id={item.id}
|
||||
onClick={() => navigate("detail", { id: item.id })}
|
||||
>
|
||||
<Image src={item.image} mode="aspectFill" />
|
||||
@@ -121,9 +133,12 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
const p = presentation(workspace, "profile");
|
||||
const config = object(b.profilePresentation);
|
||||
return (
|
||||
<View className="editorial-profile">
|
||||
<View
|
||||
className="editorial-profile"
|
||||
data-editor-target="linjing-editorial.profile.profileDetails"
|
||||
>
|
||||
<View className="profile">
|
||||
<View className="founder-card">
|
||||
<View className="founder-card" data-editor-target="linjing-editorial.profile.identity">
|
||||
<View className="identity">
|
||||
{text(b.avatarUrl) && (
|
||||
<Image className="avatar" src={text(b.avatarUrl)} mode="aspectFill" />
|
||||
@@ -198,7 +213,12 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
</View>
|
||||
)}
|
||||
{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>
|
||||
{item.summary && <Text className="trust-summary">{item.summary}</Text>}
|
||||
<Text>{item.content}</Text>
|
||||
@@ -211,7 +231,7 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
function List({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
const p = presentation(workspace, "offerings");
|
||||
return (
|
||||
<View className="editorial-list">
|
||||
<View className="editorial-list" data-editor-target="linjing-editorial.offerings.cases">
|
||||
<View className="page">
|
||||
<Text className="eyebrow">{p.eyebrow}</Text>
|
||||
<Text className="section-title">{p.title || "作品与服务"}</Text>
|
||||
@@ -220,6 +240,8 @@ function List({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
<View
|
||||
className="work-card"
|
||||
key={item.id}
|
||||
data-editor-target="linjing-editorial.offerings.item"
|
||||
data-editor-record-id={item.id}
|
||||
onClick={() => navigate("detail", { id: item.id })}
|
||||
>
|
||||
<Image src={item.image} mode="aspectFill" />
|
||||
@@ -251,7 +273,11 @@ function Detail({ workspace, id }: { workspace: RuntimeWorkspace; id?: string })
|
||||
const item = offering(found);
|
||||
const p = presentation(workspace, "detail");
|
||||
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="hero-wrap">
|
||||
<Image
|
||||
@@ -268,7 +294,7 @@ function Detail({ workspace, id }: { workspace: RuntimeWorkspace; id?: string })
|
||||
<Text>{item.series}</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View className="content">
|
||||
<View className="content" data-editor-target="linjing-editorial.detail.detailCopy">
|
||||
<View className="price-card">
|
||||
<View>
|
||||
<Text>{p.priceLabel}</Text>
|
||||
@@ -329,10 +355,19 @@ function Detail({ workspace, id }: { workspace: RuntimeWorkspace; id?: string })
|
||||
</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) {
|
||||
if (page === "home") return <Home workspace={workspace} />;
|
||||
if (page === "offerings") return <List workspace={workspace} />;
|
||||
if (page === "profile" || page === "service") return <Profile workspace={workspace} />;
|
||||
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>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,35 @@
|
||||
import type { RuntimeWorkspace } from "./runtime-workspace.js";
|
||||
|
||||
export type EditorPreviewHostMessage =
|
||||
| {
|
||||
protocol: "personal-brand-editor-preview";
|
||||
version: 1;
|
||||
type: "workspaceDraft";
|
||||
workspace: RuntimeWorkspace;
|
||||
}
|
||||
| {
|
||||
protocol: "personal-brand-editor-preview";
|
||||
version: 1;
|
||||
type: "brandDraft";
|
||||
brand: Partial<RuntimeWorkspace["brand"]>;
|
||||
}
|
||||
| {
|
||||
protocol: "personal-brand-editor-preview";
|
||||
version: 1;
|
||||
type: "focusTarget";
|
||||
targetKey: string;
|
||||
};
|
||||
|
||||
export type EditorPreviewFrameMessage =
|
||||
| {
|
||||
protocol: "personal-brand-editor-preview";
|
||||
version: 1;
|
||||
type: "ready";
|
||||
}
|
||||
| {
|
||||
protocol: "personal-brand-editor-preview";
|
||||
version: 1;
|
||||
type: "targetSelected";
|
||||
targetKey: string;
|
||||
page: string;
|
||||
};
|
||||
@@ -41,4 +41,5 @@ export interface PublicOffering {
|
||||
}
|
||||
|
||||
export * from "./runtime-workspace.js";
|
||||
export * from "./editor-preview.js";
|
||||
export * from "./runtime-content-contract.js";
|
||||
@@ -62,6 +62,16 @@ export function runtimeContractForBinding(binding: string): RuntimeBindingContra
|
||||
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") {
|
||||
return {
|
||||
binding,
|
||||
|
||||
@@ -11,6 +11,10 @@ import {
|
||||
} from "../src/runtime-content-contract.ts";
|
||||
|
||||
test("runtime contract resolves canonical paths", () => {
|
||||
assert.equal(
|
||||
runtimeContractForBinding("offering.name").runtimePath,
|
||||
"workspace.offerings[].name",
|
||||
);
|
||||
assert.equal(
|
||||
runtimeContractForBinding("offering.config.details.background").runtimePath,
|
||||
"workspace.offerings[].presentation.details.background",
|
||||
|
||||
@@ -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 });
|
||||
Reference in new issue
Block a user