feat: 增加可视化模板页面编辑器

This commit is contained in:
que01 committed 2026-10-08 18:00:36 +08:00
1 parent 9d2038cc93
commit c5af790554
24 files changed
+773 -129

No files matched your search

+5
View File
@@ -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;
+56 -1
View File
@@ -1,14 +1,69 @@
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 } = 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 === "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]);
if (loading) return <View className="runtime-state">正在加载…</View>;
if (error || !workspace)
return (
+16 -3
View File
@@ -38,10 +38,23 @@ 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 =
process.env.TARO_ENV === "h5" &&
new URLSearchParams(window.location.search).get("editor") === "1";
if (!editorPreview && data.publication?.status !== "published") throw new Error("品牌尚未发布");
if (!editorPreview && data.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;
+20 -4
View File
@@ -1,22 +1,36 @@
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;
reload: () => void;
}>({ error: "", loading: true, reload() {} });
}>({ error: "", loading: true, setBrandDraft() {}, reload() {} });
export function WorkspaceProvider({ children }: PropsWithChildren) {
const [workspace, setWorkspace] = useState<RuntimeWorkspace>();
const [baseWorkspace, setBaseWorkspace] = useState<RuntimeWorkspace>();
const [brandDraft, setBrandDraft] = useState<Partial<RuntimeWorkspace["brand"]>>({});
const workspace = baseWorkspace
? {
...baseWorkspace,
brand: projectBrandAliases(
{ ...baseWorkspace.brand, ...brandDraft },
brandDraft.config && typeof brandDraft.config === "object"
? (brandDraft.config as Record<string, unknown>)
: ((baseWorkspace.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)
.then(setBaseWorkspace)
.catch((error: unknown) =>
setError(error instanceof Error ? error.message : "加载失败,请重试"),
)
@@ -24,7 +38,9 @@ export function WorkspaceProvider({ children }: PropsWithChildren) {
}, []);
useEffect(reload, [reload]);
return (
<Context.Provider value={{ workspace, error, loading, reload }}>{children}</Context.Provider>
<Context.Provider value={{ workspace, error, loading, setBrandDraft, reload }}>
{children}
</Context.Provider>
);
}
export const useWorkspace = () => useContext(Context);
+144
View File
@@ -0,0 +1,144 @@
import { test, expect } from "@playwright/test";
const adminOrigin = "http://localhost:3011";
const brand = {
id: "brand-fixture",
slug: "preview-fixture",
name: "预览品牌",
templateKey: "food",
tagline: "校园家常餐",
description: "认真做好每一餐",
avatarUrl: "",
coverUrl: "",
hours: "每日 17:00",
address: "东门附近",
deliveryNote: "提前预约",
contactPhone: "13800138000",
contactWechat: "food-example",
config: {
visualTemplateKey: "acheng-campus-food",
founder: "测试主理人",
title: "私房菜主理人",
heroImage: "",
visualPresentation: { home: { stallTitle: "原服务地点", worksTitle: "原餐品标题" } },
},
};
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: [],
inquiryForms: [],
trustItems: [],
trustPresentation: {},
capabilities: [],
theme: { colors: {} },
};
const templateContent = {
displayName: "餐饮模板",
navigation: [{ key: "home", page: "home", label: "首页" }],
assetSlots: [],
trustContentTypes: [],
admin: {
sections: [
{
key: "home",
title: "首页内容",
description: "首页可编辑项",
page: "home",
target: "brand",
previewTargets: [
{ key: "food.home.location", label: "服务地点" },
{ key: "food.home.offerings-heading", label: "餐品区域标题" },
],
fields: [
{
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",
},
],
},
],
},
};
test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ page }) => {
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")
return route.fulfill({
json: { brand, installations: [], fields: [], offerings: [], forms: [], templateContent },
});
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();
const frame = page.frameLocator('iframe[title="小程序页面预览"]');
await expect(frame.locator(".food-home .name")).toContainText("测试主理人");
await frame.locator('[data-editor-target="food.home.location"]').click();
await expect(page.getByText("出摊信息标题")).toBeVisible();
await expect(page.getByText("招牌餐品标题")).toHaveCount(0);
await page.getByLabel("出摊信息标题").fill("后台草稿地点");
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(
/editor-target-selected/,
);
});