feat: 完善后台可视化模板编辑与区域绑定

This commit is contained in:
que01 committed 2026-10-09 14:26:05 +08:00
1 parent 0b14b5a814
commit 5b85fe769f
18 files changed
+1620 -239

No files matched your search

@@ -1,12 +1,36 @@
.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: min(76vh, 820px);
min-height: 620px;
height: calc(100% - 49px);
min-height: 510px;
padding: 24px 16px;
overflow-x: hidden;
overflow-y: auto;
border: 1px solid #e8e8e8;
background: #f3f4f6;
}
@@ -61,42 +85,36 @@
object-fit: cover;
}
.component-template-preview [data-editor-target] {
position: relative;
.component-template-preview[data-editor-mode="edit"] [data-editor-target] {
cursor: pointer;
outline: 2px solid transparent;
outline-offset: 3px;
transition:
outline-color 120ms ease,
background-color 120ms ease,
box-shadow 120ms ease;
}
.component-template-preview [data-editor-target]:hover {
outline-color: #91caff;
background-color: rgba(22, 119, 255, 0.04);
}
.component-template-preview [data-editor-target].editor-target-selected {
z-index: 2;
outline: 2px solid #1677ff;
outline-offset: 4px;
background-color: rgba(22, 119, 255, 0.1);
box-shadow: 0 0 0 5px rgba(22, 119, 255, 0.14);
}
.component-template-preview [data-editor-target].editor-target-selected::before {
.component-template-preview__outline {
position: absolute;
top: -10px;
left: -2px;
z-index: 3;
padding: 2px 7px;
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__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;
content: attr(data-editor-target);
font-size: 11px;
line-height: 16px;
pointer-events: none;
font-size: 12px;
line-height: 18px;
text-overflow: ellipsis;
white-space: nowrap;
}
@@ -1,6 +1,8 @@
import { useEffect, useRef } from "react";
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";
@@ -9,54 +11,177 @@ type PreviewProps = {
workspace: RuntimeWorkspace;
page: string;
offeringId?: string;
targetKey?: string;
onTargetSelected: (targetKey: string) => void;
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,
targetKey,
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 targetFor = useCallback(
(element: Element | null): HTMLElement | null => {
let candidate = element?.closest<HTMLElement>("[data-editor-target]");
while (candidate && root.current?.contains(candidate)) {
if (targets.some((target) => target.key === candidate?.dataset.editorTarget))
return candidate;
candidate = candidate.parentElement?.closest<HTMLElement>("[data-editor-target]") ?? null;
}
return null;
},
[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));
});
};
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(() => {
root.current?.querySelectorAll<HTMLElement>("[data-editor-target]").forEach((element) => {
element.classList.toggle(
"editor-target-selected",
element.dataset.editorTarget === targetKey,
);
});
const selected = targetKey
? root.current?.querySelector<HTMLElement>(`[data-editor-target="${CSS.escape(targetKey)}"]`)
: null;
selected?.scrollIntoView({ block: "nearest", behavior: "smooth" });
}, [targetKey, workspace, page]);
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
ref={root}
className="component-template-preview"
data-active-target={targetKey || undefined}
onClickCapture={(event) => {
const element =
event.target instanceof Element
? event.target.closest<HTMLElement>("[data-editor-target]")
: null;
const key = element?.dataset.editorTarget;
if (!key) return;
event.preventDefault();
event.stopPropagation();
onTargetSelected(key);
}}
>
<div className="component-template-preview__canvas">
<Renderer workspace={workspace} page={page} {...(offeringId ? { offeringId } : {})} />
<div className="component-template-preview-shell">
<div className="component-template-preview__tools" aria-label="预览操作模式">
<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") return;
const next = targetFor(event.target instanceof Element ? event.target : null);
if (next !== hovered) setHovered(next);
}}
onPointerLeave={() => setHovered(null)}
onClickCapture={(event) => {
if (mode !== "edit") return;
const element = targetFor(event.target instanceof Element ? event.target : 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" && 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>
{targetKey ? (
<div className="component-template-preview__selection" data-selected-target={targetKey} />
) : null}
</div>
);
}
@@ -16,24 +16,29 @@ import {
Typography,
message,
} from "antd";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import type {
AdminTemplateContent,
RuntimeWorkspace,
TemplateAdminField,
TemplateAdminSection,
Offering,
TrustContent,
} from "@personal-brand/api-client";
import type { BrandProfile } from "@personal-brand/api-client";
import { projectBrandAliases } from "@personal-brand/api-client";
import { projectBrandAliases, projectTrustPresentation } 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 { resolvePreviewSelection, type PreviewSelection } from "./preview-selection.js";
import {
applyBrandPreviewValues,
applyStandardBrandValues,
applyStandardEntityValues,
applyPresentationValues,
filterSectionsForPreviewTarget,
presentationFieldName,
@@ -50,6 +55,47 @@ interface PresentationEditorProps {
error?: unknown;
}
function trustSection(
declaration: NonNullable<AdminTemplateContent["trustContentTypes"]>[number],
page: string,
): TemplateAdminSection {
const key = `trust:${declaration.type}`;
return {
key,
title: declaration.label,
description: declaration.help ?? "编辑当前展示内容。",
page,
target: "trust",
previewTargets: [{ key, label: declaration.label }],
fields: [
{
key: "title",
binding: "trust.title",
label: declaration.adminFields.title,
input: "text" as const,
required: true,
},
...(["summary", "content"] as const)
.filter((field) => !declaration.hideStandardFields?.includes(field))
.map((field) => ({
key: field,
binding: `trust.${field}`,
label: declaration.adminFields[field],
input: "textarea" as const,
previewTarget: `trust:${declaration.type}`,
...(field === "summary" && declaration.adminFields.summaryHelp
? { help: declaration.adminFields.summaryHelp }
: {}),
...(field === "content" && declaration.required ? { required: true } : {}),
})),
...(declaration.configFields ?? []).map((field) => ({
...field,
previewTarget: `trust:${declaration.type}`,
})),
].map((field) => ({ ...field, previewTarget: `trust:${declaration.type}` })),
};
}
function renderField(field: TemplateAdminField) {
if (field.input === "textarea")
return (
@@ -102,7 +148,13 @@ export function PresentationEditor({
const navigate = useNavigate();
const breakpoints = Grid.useBreakpoint();
const [activePage, setActivePage] = useState<string>();
const [activeTarget, setActiveTarget] = useState<string>();
const [selection, setSelection] = useState<PreviewSelection>();
const [detailOfferingId, setDetailOfferingId] = useState<string>();
const [recordDraft, setRecordDraft] = useState<{
source: "offering" | "trust";
id: string;
values: PresentationValues;
}>();
const [previewConfig, setPreviewConfig] = useState(config ?? {});
const [previewBrandValues, setPreviewBrandValues] = useState<Record<string, unknown>>({});
const sections = useMemo(() => {
@@ -153,24 +205,83 @@ export function PresentationEditor({
? activePage
: pageOptions[0]?.value;
const visibleSections = sections.filter((section) => section.page === selectedPage);
const visibleTargets = (templateContent?.admin.sections ?? [])
.filter((section) => section.page === selectedPage)
.flatMap((section) =>
(section.previewTargets ?? []).map((target) => ({
...target,
page: section.page,
source: section.target,
})),
);
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
const selectedSection = (templateContent?.admin.sections ?? []).find((section) =>
section.previewTargets?.some((target) => target.key === selectedTarget?.key),
const recordSections = useMemo(
() =>
(templateContent?.trustContentTypes ?? [])
.filter((item) => item.pages?.includes(selectedPage ?? ""))
.map((item) => trustSection(item, selectedPage ?? "home")),
[templateContent, selectedPage],
);
const visibleTargets = useMemo(
() =>
[...(templateContent?.admin.sections ?? []), ...recordSections]
.filter((section) => section.page === selectedPage)
.flatMap((section) =>
(section.previewTargets ?? []).map((target) => ({
...target,
page: section.page,
source: section.target,
})),
),
[templateContent, selectedPage, recordSections],
);
const activeTarget = selection?.targetKey;
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
const selectedSection = [...(templateContent?.admin.sections ?? []), ...recordSections].find(
(section) =>
section.page === selectedPage &&
section.previewTargets?.some((target) => target.key === selectedTarget?.key),
);
const selectedRecordSource =
selectedTarget?.source === "offering" || selectedTarget?.source === "trust"
? selectedTarget.source
: undefined;
const offeringsQuery = useQuery({
queryKey: ["admin-offerings"],
queryFn: () => createApiClient().listAdminOfferings(),
enabled: selectedRecordSource === "offering",
});
const trustQuery = useQuery({
queryKey: ["trust-content"],
queryFn: () => createApiClient().listAdminTrustContent(),
enabled: selectedRecordSource === "trust",
});
const selectedRecord =
selectedRecordSource === "offering"
? offeringsQuery.data?.find((item) => item.id === selection?.recordId)
: selectedRecordSource === "trust"
? trustQuery.data?.find((item) => item.id === selection?.recordId)
: undefined;
const editableSections = filterSectionsForPreviewTarget(
visibleSections.filter((section) => section.target === "brand"),
selectedTarget?.key,
);
const handleTargetSelected = useCallback((key: string) => setActiveTarget(key), []);
const recordSection = useMemo(
() =>
selectedSection && selection?.targetKey
? {
...selectedSection,
fields: selectedSection.fields.filter(
(field) => field.previewTarget === selection.targetKey,
),
}
: undefined,
[selectedSection, selection?.targetKey],
);
const handleTargetSelected = useCallback(
(next?: PreviewSelection) =>
setSelection(
next
? resolvePreviewSelection(
next.targetKey,
next.recordId,
visibleTargets,
selectedPage ?? "home",
)
: undefined,
),
[visibleTargets, selectedPage],
);
const relatedTargets = [
...(templateContent?.admin.sections ?? [])
.filter((section) => section.page === selectedPage && section.target !== "brand")
@@ -235,6 +346,7 @@ export function PresentationEditor({
window.dispatchEvent(new Event("template-preview-refresh"));
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["publication-readiness"] });
},
@@ -248,7 +360,24 @@ export function PresentationEditor({
if (!pageOptions.some((item) => item.value === activePage))
setActivePage(pageOptions[0]?.value);
}, [activePage, pageOptions]);
useEffect(() => setActiveTarget(undefined), [selectedPage]);
useEffect(() => setSelection(undefined), [selectedPage, templateContent?.displayName]);
useEffect(() => {
if (!selection?.recordId) return;
const records =
selectedTarget?.source === "trust"
? previewWorkspace?.trustItems
: previewWorkspace?.offerings;
if (records && !records.some((item) => item.id === selection.recordId)) setSelection(undefined);
}, [
previewWorkspace?.offerings,
previewWorkspace?.trustItems,
selectedTarget?.source,
selection,
]);
useEffect(
() => setRecordDraft(undefined),
[selection?.targetKey, selection?.recordId, selectedPage],
);
useEffect(() => {
setPreviewConfig(config ?? {});
setPreviewBrandValues({});
@@ -270,6 +399,96 @@ export function PresentationEditor({
},
[brand, config, sections],
);
const draftWorkspace = useMemo(() => {
if (!previewWorkspace) return undefined;
const next: RuntimeWorkspace = {
...previewWorkspace,
brand: projectBrandAliases(
{
...previewWorkspace.brand,
...(previewBrand as unknown as Record<string, unknown>),
config: previewConfig,
},
previewConfig,
),
};
if (!recordDraft || !selectedRecord || !recordSection || recordDraft.id !== selectedRecord.id)
return next;
const values = recordDraft.values;
const config = applyPresentationValues(selectedRecord.config, [recordSection], values);
const standard = applyStandardEntityValues(
selectedRecord as unknown as Record<string, unknown>,
recordDraft.source,
[recordSection],
values,
);
if (recordDraft.source === "trust") {
next.trustItems = next.trustItems.map((item) =>
item.id === recordDraft.id
? {
...item,
title: typeof standard.title === "string" ? standard.title : item.title,
summary: typeof standard.summary === "string" ? standard.summary : item.summary,
content: typeof standard.content === "string" ? standard.content : item.content,
config,
}
: item,
);
next.trustPresentation = projectTrustPresentation(
next.trustItems,
templateContent?.trustContentTypes ?? [],
);
} else {
next.offerings = next.offerings.map((item) =>
item.id === recordDraft.id
? {
...item,
name: typeof standard.name === "string" ? standard.name : item.name,
summary:
typeof standard.summary === "string"
? standard.summary
: typeof standard.description === "string"
? standard.description
: item.summary,
priceText: typeof standard.priceText === "string" ? standard.priceText : null,
coverUrl: typeof standard.coverUrl === "string" ? standard.coverUrl : null,
presentation: {
...item.presentation,
...config,
...(config.presentation && typeof config.presentation === "object"
? (config.presentation as Record<string, unknown>)
: {}),
heroImage:
typeof config.detailHero === "string"
? config.detailHero
: typeof standard.coverUrl === "string"
? standard.coverUrl
: null,
details: {
...item.presentation.details,
...(config.details && typeof config.details === "object"
? (config.details as Record<string, unknown>)
: {}),
},
},
}
: item,
);
}
return next;
}, [
previewWorkspace,
previewBrand,
previewConfig,
recordDraft,
selectedRecord,
recordSection,
templateContent,
]);
const selectedDetailOfferingId =
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
? detailOfferingId
: draftWorkspace?.offerings[0]?.id;
return (
<Card
@@ -310,27 +529,31 @@ export function PresentationEditor({
<Row gutter={[24, 24]} align="top">
<Col xs={24} xl={12}>
<Typography.Title level={5}>页面预览</Typography.Title>
{selectedPage === "detail" && draftWorkspace?.offerings.length ? (
<Select
aria-label="选择详情页业务内容"
style={{ width: "100%", marginBottom: 12 }}
value={selectedDetailOfferingId}
options={draftWorkspace.offerings.map((item) => ({
value: item.id,
label: item.name,
}))}
onChange={(value) => {
setDetailOfferingId(value);
setSelection(undefined);
}}
/>
) : null}
<TemplatePreview
brand={previewBrand}
{...(previewWorkspace
? {
workspace: {
...previewWorkspace,
brand: {
...projectBrandAliases(
{
...previewWorkspace.brand,
...(previewBrand as unknown as Record<string, unknown>),
config: previewConfig,
},
previewConfig,
),
},
},
}
: {})}
{...(draftWorkspace ? { workspace: draftWorkspace } : {})}
page={selectedPage ?? "home"}
{...(selectedPage === "detail" && selectedDetailOfferingId
? { offeringId: selectedDetailOfferingId }
: {})}
{...(activeTarget ? { targetKey: activeTarget } : {})}
{...(selection ? { selection } : {})}
targets={visibleTargets}
onTargetSelected={handleTargetSelected}
/>
{visibleTargets.length ? (
@@ -339,7 +562,22 @@ export function PresentationEditor({
<Button
key={target.key}
type={activeTarget === target.key ? "primary" : "default"}
onClick={() => setActiveTarget(target.key)}
onClick={() => {
const recordId =
target.source === "offering"
? selectedPage === "detail"
? selectedDetailOfferingId
: draftWorkspace?.offerings[0]?.id
: target.source === "trust"
? draftWorkspace?.trustItems.find(
(item) => target.key === `trust:${item.type}`,
)?.id
: undefined;
handleTargetSelected({
targetKey: target.key,
...(recordId ? { recordId } : {}),
});
}}
>
{target.label}
</Button>
@@ -351,112 +589,182 @@ export function PresentationEditor({
<Typography.Title level={5}>
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
</Typography.Title>
<Form
form={form}
layout="vertical"
initialValues={initialValues}
onValuesChange={handleValuesChange}
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}
>
{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>
))}
{relevantPageLinks.length ? (
<Alert
type="info"
showIcon
style={{ marginBottom: 24 }}
message="这个页面还有关联内容"
description={
<Space wrap>
{relevantPageLinks.map((item) => (
{selectedRecordSource && selection?.recordId && selectedSection ? (
selectedRecord ? (
<RecordEditor
key={`${selectedRecordSource}:${selectedRecord.id}:${selectedSection.key}`}
source={selectedRecordSource}
record={selectedRecord}
section={recordSection!}
onDraft={(values) =>
setRecordDraft({
source: selectedRecordSource,
id: selectedRecord.id,
values,
})
}
onSaved={() => setRecordDraft(undefined)}
/>
) : (
<Alert
type={
(
selectedRecordSource === "offering"
? offeringsQuery.isError
: trustQuery.isError
)
? "error"
: "info"
}
message={
(
selectedRecordSource === "offering"
? offeringsQuery.isError
: trustQuery.isError
)
? "内容读取失败"
: (
selectedRecordSource === "offering"
? offeringsQuery.isSuccess
: trustQuery.isSuccess
)
? "对应内容已不存在,请重新选择页面中的区域"
: "正在读取对应内容"
}
{...((
selectedRecordSource === "offering"
? offeringsQuery.isError
: trustQuery.isError
)
? {
action: (
<Button
key={item.target}
type="link"
size="small"
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",
);
if (selectedRecordSource === "offering")
void offeringsQuery.refetch();
else void trustQuery.refetch();
}}
style={{ padding: 0 }}
>
{item.label}
重试
</Button>
),
}
: {})}
/>
)
) : (
<Form
form={form}
layout="vertical"
initialValues={initialValues}
onValuesChange={handleValuesChange}
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}
>
{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>
))}
</Space>
}
/>
) : null}
{!editableSections.some((section) => section.fields.length) &&
!relevantPageLinks.length ? (
<Typography.Paragraph type="secondary">
这个页面没有单独的品牌文案配置。
</Typography.Paragraph>
) : null}
{selectedTarget &&
!editableSections.some((section) => section.fields.length) &&
relevantPageLinks.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>
</Row>
</section>
))}
{relevantPageLinks.length ? (
<Alert
type="info"
showIcon
style={{ marginBottom: 24 }}
message="这个页面还有关联内容"
description={
<Space wrap>
{relevantPageLinks.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.some((section) => section.fields.length) &&
!relevantPageLinks.length ? (
<Typography.Paragraph type="secondary">
这个页面没有单独的品牌文案配置。
</Typography.Paragraph>
) : null}
{selectedTarget &&
!editableSections.some((section) => section.fields.length) &&
relevantPageLinks.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>
</>
@@ -465,6 +773,116 @@ export function PresentationEditor({
);
}
function RecordEditor({
source,
record,
section,
onDraft,
onSaved,
}: {
source: "offering" | "trust";
record: Offering | TrustContent;
section: TemplateAdminSection;
onDraft: (values: PresentationValues) => void;
onSaved: () => void;
}) {
const [form] = Form.useForm<PresentationValues>();
const queryClient = useQueryClient();
const initialValues = useMemo(
() =>
Object.fromEntries(
section.fields.map((field) => [
presentationFieldName(section.key, field.key),
readPresentationValue(
record.config,
field.binding,
field,
record as unknown as Record<string, unknown>,
),
]),
),
[record, section],
);
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
const save = useMutation({
mutationFn: async (values: PresentationValues): Promise<void> => {
const config = applyPresentationValues(record.config, [section], values);
const standard = applyStandardEntityValues(
record as unknown as Record<string, unknown>,
source,
[section],
values,
);
const changed = Object.fromEntries(
Object.entries(standard).filter(
([key, value]) =>
key !== "config" && value !== (record as unknown as Record<string, unknown>)[key],
),
);
const client = createApiClient();
if (source === "offering")
await client.updateAdminOffering(record.id, { ...changed, config });
else await client.updateAdminTrustContent(record.id, { ...changed, config });
},
onSuccess: () => {
message.success("内容已保存为草稿,发布后访客才会看到更新");
onSaved();
void queryClient.invalidateQueries({
queryKey: [source === "offering" ? "admin-offerings" : "trust-content"],
});
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
},
});
return (
<Form
form={form}
layout="vertical"
initialValues={initialValues}
onValuesChange={(_, values) => onDraft(values)}
onFinish={(values) => save.mutate(values)}
style={{ minHeight: 540, display: "flex", flexDirection: "column" }}
>
<Typography.Paragraph type="secondary">{section.description}</Typography.Paragraph>
<div style={{ flex: 1 }}>
<Row gutter={16}>
{section.fields.map((field) => (
<Col
key={field.key}
xs={24}
md={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}` }] }
: {})}
>
{renderField(field)}
</Form.Item>
)}
</Col>
))}
</Row>
</div>
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
<MutationError error={save.error} />
<Button type="primary" htmlType="submit" loading={save.isPending}>
保存此项内容
</Button>
</Space>
</Form>
);
}
function pageTitle(page: string): string {
return (
(
@@ -8,22 +8,31 @@ import type {
} 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;
onTargetSelected: (key: string) => void;
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);
@@ -70,7 +79,7 @@ export function TemplatePreview({
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);
onTargetSelected({ targetKey: message.targetKey });
};
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
@@ -110,7 +119,7 @@ export function TemplatePreview({
return () => window.removeEventListener("template-preview-refresh", refresh);
}, []);
if (!url)
if (!useComponent && !url)
return (
<Alert
type="warning"
@@ -122,15 +131,18 @@ export function TemplatePreview({
return (
<div className="template-preview">
{workspace ? (
{workspace && useComponent ? (
<ComponentTemplatePreview
workspace={workspace}
page={page}
{...(offeringId ? { offeringId } : {})}
{...(targetKey ? { targetKey } : {})}
{...(selection ? { selection } : {})}
targets={targets}
onTargetSelected={onTargetSelected}
/>
) : null}
{!workspace ? (
{!useComponent ? (
<>
{!ready && !error ? (
<div className="template-preview__loading">
+1 -1
View File
@@ -6,5 +6,5 @@ declare module "./component-renderers.jsx" {
workspace: RuntimeWorkspace;
page: string;
offeringId?: string;
}>;
}> | null;
}
@@ -24,5 +24,7 @@ export function resolveTemplateRenderer(workspace) {
config && typeof config === "object" && !Array.isArray(config)
? config.visualTemplateKey
: undefined;
return key === "linjing-editorial" ? EditorialPreview : FoodPreview;
if (key === "acheng-campus-food") return FoodPreview;
if (key === "linjing-editorial") return EditorialPreview;
return null;
}
@@ -33,12 +33,12 @@ function asObject(value: unknown): Record<string, unknown> {
function safePath(binding: string): string[] | null {
const prefixes = ["brand.config.", "offering.config.", "trust.config."];
const prefix = prefixes.find((candidate) => binding.startsWith(candidate));
const standardBrandField =
/^brand\.(avatarUrl|description|contactPhone|contactWechat|address|hours|deliveryNote)$/.test(
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 && !standardBrandField) return null;
const path = prefix ? binding.slice(prefix.length).split(".") : [binding.slice("brand.".length)];
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;
@@ -96,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)];
@@ -130,6 +131,24 @@ export function applyStandardBrandValues(
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,
@@ -0,0 +1,21 @@
export type PreviewSelection = { targetKey: string; recordId?: string };
export type PreviewTarget = {
key: string;
label: string;
source: "brand" | "offering" | "trust" | "inquiry";
page: 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 };
}
@@ -2,10 +2,12 @@ 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: "阿成",
@@ -148,3 +150,40 @@ const brandDraft = applyBrandPreviewValues(
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);