feat: 建立组件化模板预览基线并规划可视化编辑

This commit is contained in:
que01 committed 2026-10-09 12:32:24 +08:00
1 parent c5af790554
commit 0b14b5a814
46 files changed
+1880 -427

No files matched your search

+25 -7
View File
@@ -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) },
},
+2
View File
@@ -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
View File
@@ -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,
})),
},
}
: {}),
});
+3 -2
View File
@@ -9,7 +9,7 @@ import { Inquiry } from "./Inquiry";
import { Records } from "./Records";
import { Success } from "./Success";
export function Page({ page }: { page: PageKey }) {
const { workspace, error, loading, reload, setBrandDraft } = useWorkspace();
const { workspace, error, loading, reload, setBrandDraft, setWorkspaceDraft } = useWorkspace();
const router = useRouter();
useEffect(() => {
if (process.env.TARO_ENV !== "h5" || window.parent === window) return;
@@ -27,6 +27,7 @@ export function Page({ page }: { page: PageKey }) {
if (event.source !== window.parent || event.origin !== parentOrigin) return;
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) => {
@@ -63,7 +64,7 @@ export function Page({ page }: { page: PageKey }) {
window.removeEventListener("message", onMessage);
document.removeEventListener("click", onClick, true);
};
}, [setBrandDraft]);
}, [setBrandDraft, setWorkspaceDraft]);
if (loading) return <View className="runtime-state">正在加载…</View>;
if (error || !workspace)
return (
+4
View File
@@ -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";
}
+11 -6
View File
@@ -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,9 +45,7 @@ export async function request<T>(
}
export async function loadWorkspace() {
const data = await request<RuntimeWorkspace>("/public/workspace");
const editorPreview =
process.env.TARO_ENV === "h5" &&
new URLSearchParams(window.location.search).get("editor") === "1";
const editorPreview = isEditorPreview();
if (!editorPreview && data.publication?.status !== "published") throw new Error("品牌尚未发布");
if (!editorPreview && data.brand.visualTemplateKey !== TEMPLATE_KEY)
throw new Error("该品牌使用其他模板,请选择匹配的模板预览地址");
@@ -0,0 +1,23 @@
import type { ComponentType } from "react";
import type { TemplateProps } from "./template";
type TemplateRenderer = ComponentType<TemplateProps>;
const renderers = import.meta.glob<{
TemplatePage: TemplateRenderer;
}>("../../../../packages/template-*/taro/index.tsx", { eager: true });
export function TemplatePage(props: TemplateProps) {
const config = props.workspace.brand.config;
const visualTemplateKey =
config && typeof config === "object" && !Array.isArray(config)
? (config as Record<string, unknown>).visualTemplateKey
: undefined;
const templateKey = typeof visualTemplateKey === "string" ? visualTemplateKey : TEMPLATE_KEY;
const suffix = `/template-${templateKey}/taro/index.tsx`;
const rendererModule = Object.entries(renderers).find(([path]) => path.endsWith(suffix))?.[1];
if (!rendererModule)
return <div className="runtime-state">当前模板没有可用的 H5 预览 renderer</div>;
const Renderer = rendererModule.TemplatePage;
return <Renderer {...props} />;
}
+31 -9
View File
@@ -8,19 +8,22 @@ const Context = createContext<{
error: string;
loading: boolean;
setBrandDraft: (brand: Partial<RuntimeWorkspace["brand"]>) => void;
setWorkspaceDraft: (workspace: RuntimeWorkspace) => void;
reload: () => void;
}>({ error: "", loading: true, setBrandDraft() {}, reload() {} });
}>({ error: "", loading: true, setBrandDraft() {}, setWorkspaceDraft() {}, reload() {} });
export function WorkspaceProvider({ children }: PropsWithChildren) {
const [baseWorkspace, setBaseWorkspace] = useState<RuntimeWorkspace>();
const [brandDraft, setBrandDraft] = useState<Partial<RuntimeWorkspace["brand"]>>({});
const workspace = baseWorkspace
const [workspaceDraft, setWorkspaceDraft] = useState<RuntimeWorkspace>();
const workspace = workspaceDraft ?? baseWorkspace;
const resolvedWorkspace = workspace
? {
...baseWorkspace,
...workspace,
brand: projectBrandAliases(
{ ...baseWorkspace.brand, ...brandDraft },
{ ...workspace.brand, ...brandDraft },
brandDraft.config && typeof brandDraft.config === "object"
? (brandDraft.config as Record<string, unknown>)
: ((baseWorkspace.brand.config as Record<string, unknown> | undefined) ?? {}),
: ((workspace.brand.config as Record<string, unknown> | undefined) ?? {}),
),
}
: undefined;
@@ -29,16 +32,35 @@ export function WorkspaceProvider({ children }: PropsWithChildren) {
const reload = useCallback(() => {
setLoading(true);
setError("");
void loadWorkspace()
.then(setBaseWorkspace)
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, setBrandDraft, reload }}>
<Context.Provider
value={{
workspace: resolvedWorkspace,
error,
loading:
process.env.TARO_ENV === "h5" &&
new URLSearchParams(window.location.search).get("editor") === "1"
? !workspace
: loading,
setBrandDraft,
setWorkspaceDraft,
reload,
}}
>
{children}
</Context.Provider>
);
+83 -9
View File
@@ -1,6 +1,6 @@
import { test, expect } from "@playwright/test";
const adminOrigin = "http://localhost:3011";
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
const brand = {
id: "brand-fixture",
slug: "preview-fixture",
@@ -8,7 +8,7 @@ const brand = {
templateKey: "food",
tagline: "校园家常餐",
description: "认真做好每一餐",
avatarUrl: "",
avatarUrl: "/assets/owner/portrait.jpg",
coverUrl: "",
hours: "每日 17:00",
address: "东门附近",
@@ -35,7 +35,16 @@ const runtimeWorkspace = {
},
templateData: {},
navigation: { tabs: [] },
offerings: [],
offerings: [
{
id: "menu-fixture",
name: "家庭聚餐定制",
summary: "为同学聚餐、家庭聚会提供常见的私房菜定制。",
priceText: "88.88",
coverUrl: brand.avatarUrl,
presentation: { categoryLabel: "业务提供项", keywords: [], details: [] },
},
],
inquiryForms: [],
trustItems: [],
trustPresentation: {},
@@ -44,7 +53,10 @@ const runtimeWorkspace = {
};
const templateContent = {
displayName: "餐饮模板",
navigation: [{ key: "home", page: "home", label: "首页" }],
navigation: [
{ key: "home", page: "home", label: "首页" },
{ key: "offerings", page: "offerings", label: "套餐餐品" },
],
assetSlots: [],
trustContentTypes: [],
admin: {
@@ -88,6 +100,7 @@ const templateContent = {
};
test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ page }) => {
await page.setViewportSize({ width: 1920, height: 1000 });
await page.route("http://localhost:3001/public/workspace**", (route) =>
route.fulfill({ json: runtimeWorkspace }),
);
@@ -116,6 +129,8 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
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: [] },
@@ -129,16 +144,75 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
await page.getByLabel("密码").fill("fixture-password");
await page.locator('button[type="submit"]').click();
await expect(page.getByText("小程序页面配置")).toBeVisible();
const frame = page.frameLocator('iframe[title="小程序页面预览"]');
await expect(frame.locator(".food-home .name")).toContainText("测试主理人");
await frame.locator('[data-editor-target="food.home.location"]').click();
const preview = page.locator(".component-template-preview");
await expect(preview.locator(".food-home .name")).toContainText("测试主理人");
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 preview.locator('[data-editor-target="food.home.location"]').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(frame.locator(".notice-title")).toContainText("后台草稿地点");
await expect(frame.locator('[data-editor-target="food.home.location"]')).toHaveClass(
await expect(preview.locator('[data-editor-target="food.home.location"]')).toHaveClass(
/editor-target-selected/,
);
await page.getByText("套餐餐品", { exact: true }).click();
await expect(preview.locator(".offering-card")).toHaveCount(1);
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",
});
}
});