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

+1
View File
@@ -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_URLS={"acheng-campus-food":"http://localhost:3002","linjing-editorial":"http://localhost:3003"}
+3 -21
View File
@@ -38,7 +38,7 @@ export function BrandPage() {
extra={<Tag color="blue">{template.data?.name ?? "当前模板"}</Tag>}
/>
<Row gutter={[24, 24]} align="top">
<Col xs={24} xl={15}>
<Col xs={24} xl={16}>
<Form
form={form}
layout="vertical"
@@ -146,30 +146,12 @@ export function BrandPage() {
<PresentationEditor
templateContent={workspace.data?.templateContent}
config={brand.data.config}
brand={brand.data}
loading={workspace.isLoading}
error={workspace.error}
/>
</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>
<Col xs={24} xl={8}>
{template.data && (
<Card title="模板说明" style={{ marginTop: 24 }}>
<Typography.Paragraph>{template.data.description}</Typography.Paragraph>
@@ -17,15 +17,18 @@ import {
message,
} from "antd";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import type { AdminTemplateContent, TemplateAdminField } from "@personal-brand/api-client";
import type { BrandProfile } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { ImageUrlField } from "../../components/ImageUrlField.js";
import { TemplateListField } from "../../components/TemplateListField.js";
import { MutationError } from "../../components/QueryState.js";
import { TemplatePreview } from "./TemplatePreview.js";
import {
applyPresentationValues,
filterSectionsForPreviewTarget,
presentationFieldName,
readPresentationValue,
type PresentationValues,
@@ -34,6 +37,7 @@ import {
interface PresentationEditorProps {
templateContent: AdminTemplateContent | null | undefined;
config: Record<string, unknown> | null | undefined;
brand: BrandProfile;
loading?: boolean;
error?: unknown;
}
@@ -80,6 +84,7 @@ function renderField(field: TemplateAdminField) {
export function PresentationEditor({
templateContent,
config,
brand,
loading,
error,
}: PresentationEditorProps) {
@@ -88,6 +93,7 @@ export function PresentationEditor({
const navigate = useNavigate();
const breakpoints = Grid.useBreakpoint();
const [activePage, setActivePage] = useState<string>();
const [activeTarget, setActiveTarget] = useState<string>();
const sections = useMemo(() => {
const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({
...field,
@@ -138,6 +144,12 @@ export function PresentationEditor({
? activePage
: pageOptions[0]?.value;
const visibleSections = sections.filter((section) => section.page === selectedPage);
const visibleTargets = visibleSections.flatMap((section) =>
(section.previewTargets ?? []).map((target) => ({ ...target, page: section.page })),
);
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
const editableSections = filterSectionsForPreviewTarget(visibleSections, selectedTarget?.key);
const handleTargetSelected = useCallback((key: string) => setActiveTarget(key), []);
const relatedTargets = [
...(templateContent?.admin.sections ?? [])
.filter((section) => section.page === selectedPage && section.target !== "brand")
@@ -189,6 +201,7 @@ export function PresentationEditor({
},
onSuccess: () => {
message.success("页面内容已保存为草稿,发布后小程序才会更新");
window.dispatchEvent(new Event("template-preview-refresh"));
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
@@ -204,6 +217,7 @@ export function PresentationEditor({
if (!pageOptions.some((item) => item.value === activePage))
setActivePage(pageOptions[0]?.value);
}, [activePage, pageOptions]);
useEffect(() => setActiveTarget(undefined), [selectedPage]);
return (
<Card
@@ -241,97 +255,133 @@ export function PresentationEditor({
/>
)}
</Space>
<Form
form={form}
layout="vertical"
initialValues={initialValues}
onFinish={(values) => save.mutate(values)}
style={{ minHeight: 540, display: "flex", flexDirection: "column" }}
>
<div style={{ flex: 1 }}>
{visibleSections.map((section, index) => (
<section key={section.key} aria-labelledby={`section-${section.key}`}>
{index > 0 ? <Divider /> : null}
<Typography.Title id={`section-${section.key}`} level={5}>
{section.title}
</Typography.Title>
<Typography.Paragraph type="secondary">
{section.description}
</Typography.Paragraph>
<Row gutter={16}>
{section.fields.map((field) => (
<Col
key={field.key}
xs={24}
md={field.input === "textarea" || field.input === "list" ? 24 : 12}
>
{field.input === "list" ? (
<TemplateListField
field={field}
name={presentationFieldName(section.key, field.key)}
/>
) : (
<Form.Item
name={presentationFieldName(section.key, field.key)}
label={field.label}
{...(field.help ? { help: field.help } : {})}
{...(field.required
? { rules: [{ required: true, message: `请填写${field.label}` }] }
: {})}
<Row gutter={[24, 24]} align="top">
<Col xs={24} xl={12}>
<Typography.Title level={5}>页面预览</Typography.Title>
<TemplatePreview
brand={brand}
page={selectedPage ?? "home"}
route={`/pages/${encodeURIComponent(selectedPage ?? "home")}/index`}
{...(activeTarget ? { targetKey: activeTarget } : {})}
onTargetSelected={handleTargetSelected}
/>
{visibleTargets.length ? (
<Space wrap style={{ marginTop: 16 }}>
{visibleTargets.map((target) => (
<Button
key={target.key}
type={activeTarget === target.key ? "primary" : "default"}
onClick={() => setActiveTarget(target.key)}
>
{target.label}
</Button>
))}
</Space>
) : null}
</Col>
<Col xs={24} xl={12}>
<Typography.Title level={5}>
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
</Typography.Title>
<Form
form={form}
layout="vertical"
initialValues={initialValues}
onFinish={(values) => save.mutate(values)}
style={{ minHeight: 540, display: "flex", flexDirection: "column" }}
>
<div style={{ flex: 1 }}>
{editableSections.map((section, index) => (
<section key={section.key} aria-labelledby={`section-${section.key}`}>
{selectedTarget && index > 0 ? <Divider /> : null}
<Typography.Title id={`section-${section.key}`} level={5}>
{selectedTarget
? fieldTargetTitle(section, selectedTarget.label)
: section.title}
</Typography.Title>
{!selectedTarget ? (
<Typography.Paragraph type="secondary">
{section.description}
</Typography.Paragraph>
) : null}
<Row gutter={16}>
{section.fields.map((field) => (
<Col
key={field.key}
xs={24}
md={field.input === "textarea" || field.input === "list" ? 24 : 12}
>
{renderField(field)}
</Form.Item>
)}
</Col>
))}
</Row>
</section>
))}
{pageLinks.length ? (
<Alert
type="info"
showIcon
style={{ marginBottom: 24 }}
message="这个页面还有关联内容"
description={
<Space wrap>
{pageLinks.map((item) => (
<Button
key={item.target}
type="link"
onClick={() => {
if (item.target.startsWith("trust:")) {
void navigate(
`/admin/trust?type=${encodeURIComponent(item.target.slice(6))}`,
);
return;
}
void navigate(
item.target === "offering" ? "/admin/services" : "/admin/workspace",
);
}}
style={{ padding: 0 }}
>
{item.label}
</Button>
))}
</Space>
}
/>
) : null}
{!visibleSections.length && !pageLinks.length ? (
<Typography.Paragraph type="secondary">
这个页面没有单独的品牌文案配置。
</Typography.Paragraph>
) : null}
</div>
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
<MutationError error={save.error} />
<Button type="primary" htmlType="submit" loading={save.isPending}>
保存页面内容
</Button>
</Space>
</Form>
{field.input === "list" ? (
<TemplateListField
field={field}
name={presentationFieldName(section.key, field.key)}
/>
) : (
<Form.Item
name={presentationFieldName(section.key, field.key)}
label={field.label}
{...(field.help ? { help: field.help } : {})}
{...(field.required
? { rules: [{ required: true, message: `请填写${field.label}` }] }
: {})}
>
{renderField(field)}
</Form.Item>
)}
</Col>
))}
</Row>
</section>
))}
{pageLinks.length ? (
<Alert
type="info"
showIcon
style={{ marginBottom: 24 }}
message="这个页面还有关联内容"
description={
<Space wrap>
{pageLinks.map((item) => (
<Button
key={item.target}
type="link"
onClick={() => {
if (item.target.startsWith("trust:")) {
void navigate(
`/admin/trust?type=${encodeURIComponent(item.target.slice(6))}`,
);
return;
}
void navigate(
item.target === "offering"
? "/admin/services"
: "/admin/workspace",
);
}}
style={{ padding: 0 }}
>
{item.label}
</Button>
))}
</Space>
}
/>
) : null}
{!editableSections.length && !pageLinks.length ? (
<Typography.Paragraph type="secondary">
这个页面没有单独的品牌文案配置。
</Typography.Paragraph>
) : null}
</div>
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
<MutationError error={save.error} />
<Button type="primary" htmlType="submit" loading={save.isPending}>
保存页面内容
</Button>
</Space>
</Form>
</Col>
</Row>
</>
) : null}
</Card>
@@ -354,3 +404,7 @@ function pageTitle(page: string): string {
)[page] ?? page
);
}
function fieldTargetTitle(section: { title: string }, targetLabel: string): string {
return section.title === targetLabel ? targetLabel : `${targetLabel} · ${section.title}`;
}
@@ -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,135 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { Alert, Spin } from "antd";
import type {
BrandProfile,
EditorPreviewFrameMessage,
EditorPreviewHostMessage,
} from "@personal-brand/api-client";
import { templatePreviewUrl } from "../../lib/template-preview.js";
import "./TemplatePreview.css";
export function TemplatePreview({
brand,
page,
targetKey,
route,
onTargetSelected,
}: {
brand: BrandProfile;
page: string;
targetKey?: string;
route: string;
onTargetSelected: (key: string) => void;
}) {
const frame = useRef<HTMLIFrameElement>(null);
const [ready, setReady] = useState(false);
const [error, setError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
const config = brand.config ?? {};
const templateKey =
typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : brand.templateKey;
const url = useMemo(
() =>
templatePreviewUrl(
templateKey,
brand.slug,
page,
import.meta.env.VITE_TEMPLATE_PREVIEW_URLS,
window.location.origin,
route,
),
[brand.slug, page, reloadKey, route, templateKey],
);
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(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);
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]);
useEffect(() => {
const refresh = () => setReloadKey((value) => value + 1);
window.addEventListener("template-preview-refresh", refresh);
return () => window.removeEventListener("template-preview-refresh", refresh);
}, []);
if (!url)
return (
<Alert
type="warning"
showIcon
message="尚未配置模板预览服务"
description="请在 Admin 环境变量 VITE_TEMPLATE_PREVIEW_URLS 中为模板配置 H5 预览地址。"
/>
);
return (
<div className="template-preview">
{!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 }}
/>
</div>
);
}
@@ -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>)
+31
View File
@@ -0,0 +1,31 @@
export function templatePreviewUrl(
templateKey: string,
brandSlug: string | undefined,
page: string,
configured: string | undefined,
parentOrigin?: string,
route?: string,
): string | undefined {
let urls: Record<string, unknown>;
try {
const parsed: unknown = configured ? JSON.parse(configured) : {};
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
return undefined;
}
urls = parsed as Record<string, unknown>;
} catch {
return undefined;
}
const raw = urls[templateKey];
if (typeof raw !== "string" || !raw) return undefined;
try {
const url = new URL(raw);
url.searchParams.set("editor", "1");
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;
}
}
+1
View File
@@ -1,6 +1,7 @@
interface ImportMetaEnv {
readonly VITE_API_BASE_URL?: string;
readonly VITE_APP_BASE_PATH?: string;
readonly VITE_TEMPLATE_PREVIEW_URLS?: string;
}
interface ImportMeta {
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import {
applyPresentationValues,
filterSectionsForPreviewTarget,
presentationFieldName,
readPresentationValue,
} from "../src/features/brand/presentation-bindings.ts";
@@ -37,6 +38,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: "原主理人" },
[
+27
View File
@@ -0,0 +1,27 @@
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 generic deployment configuration", () => {
const url = templatePreviewUrl(
"new-template",
"brand-a",
"profile",
JSON.stringify({ "new-template": "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("missing, malformed or invalid template preview configuration fails closed", () => {
assert.equal(templatePreviewUrl("missing", "brand-a", "home", undefined), undefined);
assert.equal(templatePreviewUrl("missing", "brand-a", "home", "{"), undefined);
assert.equal(
templatePreviewUrl("broken", "brand-a", "home", JSON.stringify({ broken: "not a URL" })),
undefined,
);
});
+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/,
);
});
+3
View File
@@ -14,6 +14,7 @@ import type {
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 } from "@personal-brand/types";
export interface BrandProfile {
id: string;
@@ -92,6 +93,7 @@ export interface TemplateAdminField {
maxLength?: number;
placeholder?: string;
options?: Array<{ value: string; label: string }>;
previewTarget?: string;
}
export interface TemplateAdminSection {
@@ -100,6 +102,7 @@ export interface TemplateAdminSection {
description: string;
page: string;
target: "brand" | "offering" | "trust" | "inquiry";
previewTargets?: Array<{ key: string; label: string }>;
fields: TemplateAdminField[];
}
@@ -23,7 +23,7 @@ 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>}
@@ -37,7 +37,7 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
</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,7 +50,7 @@ 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>
@@ -75,7 +75,9 @@ 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) => (
@@ -188,9 +188,16 @@
"description": "说明今天在哪里、何时营业,以及餐品有什么特点。",
"page": "home",
"target": "brand",
"previewTargets": [
{ "key": "food.home.location", "label": "服务地点" },
{ "key": "food.home.hero", "label": "出摊现场图片" },
{ "key": "food.home.offerings-heading", "label": "餐品区域标题" },
{ "key": "food.home.promise-heading", "label": "出餐承诺标题" }
],
"fields": [
{
"key": "stallTitle",
"previewTarget": "food.home.location",
"binding": "brand.config.visualPresentation.home.stallTitle",
"label": "出摊信息标题",
"input": "text",
@@ -198,6 +205,7 @@
},
{
"key": "heroImage",
"previewTarget": "food.home.hero",
"binding": "brand.config.heroImage",
"label": "出摊现场主图",
"help": "展示真实摊位、餐品或取餐场景,建议使用横向图片。",
@@ -206,6 +214,7 @@
},
{
"key": "stallTime",
"previewTarget": "food.home.location",
"binding": "brand.config.visualPresentation.home.stallTime",
"label": "营业时间说明",
"input": "text",
@@ -213,18 +222,21 @@
},
{
"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": "manifestoTitle",
"previewTarget": "food.home.promise-heading",
"binding": "brand.config.visualPresentation.home.manifestoTitle",
"label": "出餐承诺标题",
"input": "text"
+4
View File
@@ -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,8 @@ 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 }>;
fields: TemplateAdminField[];
};
@@ -0,0 +1,55 @@
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 targets) {
for (const field of section.fields) {
if (field.previewTarget)
assert.ok(
section.previewTargets.some((target) => target.key === field.previewTarget),
`${section.key}.${field.key} references an undeclared previewTarget`,
);
}
}
for (const target of targets)
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 is missing data-editor-target ${target.key}`,
);
});
}
@@ -21,7 +21,7 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
return (
<View className="editorial-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,7 +50,7 @@ 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>
@@ -60,7 +64,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 +75,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>
@@ -157,9 +157,17 @@
"description": "用简洁的语言解释你的项目方法、代表作品和合作流程。",
"page": "home",
"target": "brand",
"previewTargets": [
{ "key": "editorial.home.identity", "label": "主理人标签" },
{ "key": "editorial.home.hero", "label": "首页主视觉" },
{ "key": "editorial.home.proof", "label": "信任介绍" },
{ "key": "editorial.home.manifesto", "label": "品牌主张" },
{ "key": "editorial.home.works", "label": "代表案例标题" }
],
"fields": [
{
"key": "founderBadge",
"previewTarget": "editorial.home.identity",
"binding": "brand.config.visualPresentation.home.founderBadge",
"label": "主理人标签",
"input": "text",
@@ -167,6 +175,7 @@
},
{
"key": "heroImage",
"previewTarget": "editorial.home.hero",
"binding": "brand.config.heroImage",
"label": "首页项目主图",
"help": "展示真实别墅、入户门或空间细节,体现项目能力。",
@@ -175,36 +184,42 @@
},
{
"key": "proofTitle",
"previewTarget": "editorial.home.proof",
"binding": "brand.config.visualPresentation.home.proofTitle",
"label": "信任介绍标题",
"input": "text"
},
{
"key": "proofEyebrow",
"previewTarget": "editorial.home.proof",
"binding": "brand.config.visualPresentation.home.proofEyebrow",
"label": "信任介绍小标题",
"input": "text"
},
{
"key": "manifestoEyebrow",
"previewTarget": "editorial.home.manifesto",
"binding": "brand.config.visualPresentation.home.manifestoEyebrow",
"label": "品牌主张小标题",
"input": "text"
},
{
"key": "manifestoTitle",
"previewTarget": "editorial.home.manifesto",
"binding": "brand.config.visualPresentation.home.manifestoTitle",
"label": "品牌主张",
"input": "text"
},
{
"key": "worksEyebrow",
"previewTarget": "editorial.home.works",
"binding": "brand.config.visualPresentation.home.worksEyebrow",
"label": "代表案例小标题",
"input": "text"
},
{
"key": "worksTitle",
"previewTarget": "editorial.home.works",
"binding": "brand.config.visualPresentation.home.worksTitle",
"label": "代表案例标题",
"input": "text"
+29
View File
@@ -0,0 +1,29 @@
import type { RuntimeWorkspace } from "./runtime-workspace.js";
export type EditorPreviewHostMessage =
| {
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;
};
+1
View File
@@ -41,4 +41,5 @@ export interface PublicOffering {
}
export * from "./runtime-workspace.js";
export * from "./editor-preview.js";
export * from "./runtime-content-contract.js";