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

@@ -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 (
(