import { Alert, Button, Divider, Col, Form, Grid, Input, InputNumber, Row, Select, Segmented, Space, Tag, Typography, message, } from "antd"; 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, } from "@personal-brand/api-client"; import type { BrandProfile } 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 { RecordContentEditor } from "../../components/RecordContentEditor.js"; import { TemplatePreview } from "./TemplatePreview.js"; import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js"; import { resolvePreviewSelection, previewTrustRecordId, type PreviewSelection, type PreviewTarget, } from "./preview-selection.js"; import { applyBrandPreviewValues, applyStandardBrandValues, applyStandardEntityValues, applyPresentationValues, filterSectionsForPreviewTarget, presentationFieldName, readPresentationValue, type PresentationValues, } from "./presentation-bindings.js"; import "./PresentationEditor.css"; import { useEditorDraft } from "./use-editor-draft.js"; interface PresentationEditorProps { templateContent: AdminTemplateContent | null | undefined; previewWorkspace?: RuntimeWorkspace | undefined; config: Record | null | undefined; brand: BrandProfile; loading?: boolean; error?: unknown; initialSelection?: PreviewSelection; } function trustSection( declaration: NonNullable[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 }, ...(declaration.previewTargets ?? []).filter( (target) => !target.page || target.page === page, ), ], 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 ?? []) .filter((field) => { const target = declaration.previewTargets?.find( (target) => target.key === field.previewTarget, ); return !target?.page || target.page === page; }) .map((field) => ({ ...field, previewTarget: field.previewTarget ?? `trust:${declaration.type}`, })), ].map((field) => ({ ...field, previewTarget: (field as TemplateAdminField).previewTarget ?? `trust:${declaration.type}`, })), }; } function renderField(field: TemplateAdminField) { if (field.input === "textarea") return ( ); if (field.input === "image") return ; if (field.input === "number") return ; if (field.input === "boolean") return ( ); return ( ); } function previewTargetSource( section: TemplateAdminSection, targetKey: string, ): "brand" | "offering" | "trust" | "inquiry" { const fields = section.fields.filter((field) => field.previewTarget === targetKey); if (fields.some((field) => field.binding.startsWith("offering."))) return "offering"; if (fields.some((field) => field.binding.startsWith("trust."))) return "trust"; if (fields.some((field) => field.binding.startsWith("brand."))) return "brand"; return section.target; } export function PresentationEditor({ templateContent, previewWorkspace, config, brand, loading, error, initialSelection, }: PresentationEditorProps) { const [form] = Form.useForm(); const queryClient = useQueryClient(); const navigate = useNavigate(); const breakpoints = Grid.useBreakpoint(); const [activePage, setActivePage] = useState(); const [selection, setSelection] = useState(initialSelection); const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection)); const [detailOfferingId, setDetailOfferingId] = useState(); const [recordDraft, setRecordDraft] = useState<{ source: "offering" | "trust"; id: string; values: PresentationValues; }>(); const [previewConfig, setPreviewConfig] = useState(config ?? {}); const [previewBrandValues, setPreviewBrandValues] = useState>({}); const [inquiryDraft, setInquiryDraft] = useState(); const [brandDirty, setBrandDirty] = useState(false); const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft); const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand"); const sections = useMemo(() => { const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({ ...field, binding: field.binding ?? `brand.config.templateData.${field.key}`, })); return [ ...[...new Set(declaredTemplateFields.map((field) => field.page ?? "home"))].map((page) => ({ key: `template-data:${page}`, title: "模板专属内容", description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。", page, target: "brand" as const, fields: declaredTemplateFields.filter((field) => (field.page ?? "home") === page), })), ...(templateContent?.admin.sections ?? []), ].map((section) => ({ ...section, fields: section.fields.filter( (field) => field.binding.startsWith("brand.config.") || [ "brand.name", "brand.tagline", "brand.avatarUrl", "brand.description", "brand.contactPhone", "brand.contactWechat", "brand.address", ].includes(field.binding), ), })); }, [templateContent]); const pageOptions = useMemo(() => { const pages = new Map(); for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label); for (const section of templateContent?.admin.sections ?? []) { const navigation = templateContent?.navigation.find((item) => item.page === section.page); if (!pages.has(section.page)) pages.set(section.page, navigation?.label ?? pageTitle(section.page)); } return [...pages].map(([value, label]) => ({ value, label })); }, [templateContent]); const selectedPage = pageOptions.some((item) => item.value === activePage) ? activePage : pageOptions[0]?.value; const visibleSections = sections.filter((section) => section.page === selectedPage); 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 && (selectedPage !== "detail" || section.target === "brand"), ) .flatMap((section) => (section.previewTargets ?? []).map((target) => ({ ...target, page: section.page, source: previewTargetSource(section, target.key), ...(section.key.startsWith("trust:") ? { trustType: section.key.slice(6) } : {}), })), ) .concat( selectedPage === "inquiry" && inquiryRuntime ? inquiryRuntime.fields.map((field) => ({ key: `inquiry-field:${field.key}`, label: field.label, page: "inquiry", source: "inquiry" as const, })) : [], ), [templateContent, selectedPage, recordSections, inquiryRuntime], ); 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", refetchOnMount: "always", }); 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.fields.some((field) => field.binding.startsWith("brand.")), ), selectedTarget?.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) => { const select = () => setSelection( next ? resolvePreviewSelection( next.targetKey, next.recordId, visibleTargets, selectedPage ?? "home", ) : undefined, ); if (recordDraft || inquiryDraft) guardDraft(() => { setInquiryDraft(undefined); setRecordDraft(undefined); select(); }); else select(); }, [visibleTargets, selectedPage, recordDraft, inquiryDraft, guardDraft], ); const relatedTargets = [ ...(templateContent?.admin.sections ?? []) .filter((section) => section.page === selectedPage && section.target !== "brand") .map((section) => section.target), ...((templateContent?.trustContentTypes ?? []).some((item) => item.pages?.includes(selectedPage ?? ""), ) ? ["trust"] : []), ]; const pageLinks = [...new Set(relatedTargets)].flatMap((target) => target === "trust" ? (templateContent?.trustContentTypes ?? []) .filter((item) => item.pages?.includes(selectedPage ?? "")) .map((item) => ({ target: `trust:${item.type}`, label: `编辑${item.label}`, })) : [ { target, label: ( { offering: "管理此页展示的业务内容", inquiry: "管理此页的咨询表单" } as Record< string, string > )[target], }, ], ); const relevantPageLinks = selectedSection ? pageLinks.filter((item) => { if (item.target.startsWith("trust:")) return selectedSection.target === "trust"; return item.target === selectedSection.target; }) : pageLinks; const initialValues = useMemo(() => { const values: PresentationValues = {}; for (const section of sections) { for (const field of section.fields) { values[presentationFieldName(section.key, field.key)] = readPresentationValue( config, field.binding, field, brand as unknown as Record, ); } } return values; }, [config, sections]); const save = useMutation({ mutationFn: (values: PresentationValues) => { const nextConfig = applyPresentationValues(config, sections, values); // 页面内容编辑不提交模板选择,避免触发切换模板的权限校验。 const contentConfig = { ...nextConfig }; delete contentConfig.visualTemplateKey; const standard = applyStandardBrandValues( brand as unknown as Record, sections, values, ); const changed = Object.fromEntries( Object.entries(standard).filter( ([key, value]) => key !== "config" && value !== (brand as unknown as Record)[key], ), ); return createApiClient().updateAdminBrand({ ...changed, config: contentConfig, }); }, onSuccess: () => { setBrandDirty(false); 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: ["admin-preview-workspace"] }); void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] }); void queryClient.invalidateQueries({ queryKey: ["publication-readiness"] }); }, }); useEffect(() => { form.setFieldsValue(initialValues); }, [form, initialValues]); useEffect(() => { const initialPage = typeof initialSelection === "object" && "page" in initialSelection ? String(initialSelection.page) : undefined; if (initialPage) { setActivePage( pageOptions.some((item) => item.value === initialPage) ? initialPage : pageOptions[0]?.value, ); return; } if (!activePage && pageOptions.length) setActivePage(pageOptions[0]?.value); }, [activePage, initialSelection, pageOptions]); useEffect(() => { if (hasInitializedSelection) return; if (!pageOptions.length) return; if (!initialSelection) return; const requestedPage = typeof initialSelection === "object" && "page" in initialSelection ? String(initialSelection.page) : undefined; const resolvedPage = requestedPage && pageOptions.some((item) => item.value === requestedPage) ? requestedPage : (pageOptions[0]?.value ?? "home"); setSelection( resolvePreviewSelection( initialSelection.targetKey, initialSelection.recordId, visibleTargets, resolvedPage, ), ); setActivePage(resolvedPage); setHasInitializedSelection(true); }, [hasInitializedSelection, initialSelection, pageOptions, selectedPage, visibleTargets]); useEffect(() => { if (!initialSelection) setSelection(undefined); }, [initialSelection, 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({}); }, [config]); const previewBrand = useMemo( () => ({ ...brand, ...previewBrandValues, config: previewConfig }), [brand, previewBrandValues, previewConfig], ); const handleValuesChange = useCallback( (changed: PresentationValues, allValues: PresentationValues) => { setBrandDirty(true); const synchronized: PresentationValues = { ...(form.getFieldsValue(true) as PresentationValues), ...allValues, }; for (const section of sections) { for (const field of section.fields) { const name = presentationFieldName(section.key, field.key); if (!Object.prototype.hasOwnProperty.call(changed, name)) continue; for (const peer of sections) { for (const item of peer.fields) { if (item.binding === field.binding) synchronized[presentationFieldName(peer.key, item.key)] = changed[name]; } } } } form.setFieldsValue(synchronized); const next = applyBrandPreviewValues( brand as unknown as Record, config, sections, synchronized, ); setPreviewConfig((next.config as Record) ?? {}); setPreviewBrandValues(next); }, [brand, config, sections, form], ); const draftWorkspace = useMemo(() => { if (!previewWorkspace) return undefined; const next: RuntimeWorkspace = { ...previewWorkspace, templateData: { ...previewWorkspace.templateData, ...(previewConfig.templateData && typeof previewConfig.templateData === "object" && !Array.isArray(previewConfig.templateData) ? (previewConfig.templateData as Record) : {}), }, inquiryForms: previewWorkspace.inquiryForms.map((item) => item.key === inquiryRuntime?.key && inquiryDraft ? { ...item, fields: inquiryDraft } : item, ), brand: projectBrandAliases( { ...previewWorkspace.brand, ...(previewBrand as unknown as Record), 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, 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) : {}), ...(typeof config.categoryLabel === "string" ? { categoryLabel: config.categoryLabel } : {}), ...(typeof config.area === "string" ? { area: config.area } : {}), ...(typeof config.series === "string" ? { series: config.series } : {}), ...(typeof config.spaceType === "string" ? { spaceType: config.spaceType } : {}), heroImage: typeof config.detailHero === "string" ? config.detailHero : typeof standard.coverUrl === "string" ? standard.coverUrl : null, details: { ...item.presentation.details, ...(config.details && typeof config.details === "object" && "background" in config.details ? (config.details as RuntimeWorkspace["offerings"][number]["presentation"]["details"]) : {}), }, }, } : item, ); } return next; }, [ previewWorkspace, previewBrand, previewConfig, recordDraft, selectedRecord, recordSection, templateContent, inquiryDraft, inquiryRuntime, ]); const selectedDetailOfferingId = detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId) ? detailOfferingId : draftWorkspace?.offerings[0]?.id; return (
小程序页面配置 按页面查找内容。这里修改的是草稿,发布后访客才会看到更新。
{templateContent ? {templateContent.displayName} : null}
{loading ? : null} {error ? ( ) : null} {!loading && !error && !templateContent ? ( ) : null} {templateContent ? ( <> {breakpoints.xs ? ( ({ value: item.id, label: item.name, }))} onChange={(value) => { setDetailOfferingId(value); setSelection(undefined); }} /> ) : null}
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")} {save.isPending ? "正在保存" : save.isError ? "保存失败,请重试" : brandDirty || recordDraft || inquiryDraft ? "有未保存修改" : "草稿已同步"} {selectedPage === "detail" && !selectedTarget ? ( { void navigate("/admin/services"); }} > 管理业务内容 } /> ) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? ( item.key === inquiryRuntime.key) ?? inquiryRuntime } fieldKey={activeTarget.slice("inquiry-field:".length)} onDraft={setInquiryDraft} onSaved={() => setInquiryDraft(undefined)} /> ) : selectedTarget?.composite ? ( {(selectedTarget.children ?? []).map((childKey) => { const child = visibleTargets.find((item) => item.key === childKey); if (!child) return null; return ( ); })} } /> ) : selectedRecordSource && selection?.recordId && selectedSection ? ( selectedRecord ? ( setRecordDraft({ source: selectedRecordSource, id: selectedRecord.id, values, }) } onSaved={() => setRecordDraft(undefined)} /> ) : ( { if (selectedRecordSource === "offering") void offeringsQuery.refetch(); else void trustQuery.refetch(); }} > 重试 ), } : {})} /> ) ) : selectedRecordSource ? ( guardDraft(() => { void navigate( selectedRecordSource === "trust" ? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}` : "/admin/services", ); }) } > 配置此区域内容 } /> ) : !selectedTarget ? (
选择要编辑的区域 点击预览中的内容,或使用区域列表,查看并修改对应字段。
) : (
save.mutate(form.getFieldsValue(true) as PresentationValues)} style={{ minHeight: 0, display: "flex", flexDirection: "column" }} >
{editableSections.map((section, index) => (
{selectedTarget && index > 0 ? : null} {selectedTarget ? fieldTargetTitle(section, selectedTarget.label) : section.title} {!selectedTarget ? ( {section.description} ) : null} {section.fields.map((field) => ( {field.input === "list" ? ( ) : ( {renderField(field)} )} ))}
))} {relevantPageLinks.length ? ( {relevantPageLinks.map((item) => ( ))} } /> ) : null} {!editableSections.some((section) => section.fields.length) && !relevantPageLinks.length ? ( 这个页面没有单独的品牌文案配置。 ) : null} {selectedTarget && !editableSections.some((section) => section.fields.length) && relevantPageLinks.length ? ( 此区域内容由对应的业务管理页面维护。 ) : null}
)}
) : null}
); } function pageTitle(page: string): string { return ( ( { home: "首页", offerings: "业务展示", service: "服务说明", detail: "详情页", inquiry: "咨询页", success: "提交成功页", records: "记录页", profile: "主理人页", } as Record )[page] ?? page ); } function fieldTargetTitle(section: { title: string }, targetLabel: string): string { return section.title === targetLabel ? targetLabel : `${targetLabel} · ${section.title}`; }