417 lines
14 KiB
TypeScript
417 lines
14 KiB
TypeScript
import { useQueryClient } from "@tanstack/react-query";
|
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
import { useNavigate, type NavigateFunction } from "react-router-dom";
|
|
import type {
|
|
AdminTemplateContent,
|
|
BrandProfile,
|
|
Offering,
|
|
RuntimeWorkspace,
|
|
TemplateAdminSection,
|
|
TrustContent,
|
|
} from "@personal-brand/api-client";
|
|
import type { FormInstance } from "antd";
|
|
import { filterSectionsForPreviewTarget } from "../../lib/presentation/presentation-bindings.js";
|
|
import type { PresentationValues } from "../../lib/presentation/presentation-bindings.js";
|
|
import {
|
|
resolvePreviewSelection,
|
|
previewTrustRecordId,
|
|
type PreviewSelection,
|
|
type PreviewTarget,
|
|
} from "./preview-selection.js";
|
|
import { useEditorDraft } from "./use-editor-draft.js";
|
|
import {
|
|
useBrandPresentationForm,
|
|
useBrandPresentationSections,
|
|
useBrandPreviewDraft,
|
|
useBrandSaveMutation,
|
|
usePresentationRecordQueries,
|
|
} from "./presentation-editor-state.js";
|
|
import { useRecordPreview, type RecordDraft } from "./presentation-editor-record-preview.js";
|
|
import { pageTitle, previewTargetSource, trustSection } from "./presentation-editor-helpers.js";
|
|
import { useDraftWorkspace } from "./use-draft-workspace.js";
|
|
|
|
export interface PresentationEditorControllerInput {
|
|
templateContent: AdminTemplateContent | null | undefined;
|
|
previewWorkspace?: RuntimeWorkspace | undefined;
|
|
config: Record<string, unknown> | null | undefined;
|
|
brand: BrandProfile;
|
|
initialSelection?: PreviewSelection;
|
|
}
|
|
|
|
export interface PresentationRecordQuery {
|
|
isError: boolean;
|
|
isSuccess: boolean;
|
|
refetch: () => unknown;
|
|
}
|
|
|
|
export interface PresentationEditorController {
|
|
pageOptions: { value: string; label: string }[];
|
|
selectedPage: string | undefined;
|
|
visibleTargets: PreviewTarget[];
|
|
selectedTarget: PreviewTarget | undefined;
|
|
selectedSection: TemplateAdminSection | undefined;
|
|
selectedRecordSource: "offering" | "trust" | undefined;
|
|
selectedRecord: Offering | TrustContent | undefined;
|
|
recordSection: TemplateAdminSection | undefined;
|
|
editableSections: TemplateAdminSection[];
|
|
relevantPageLinks: { target: string; label: string | undefined }[];
|
|
inquiryRuntime: RuntimeWorkspace["inquiryForms"][number] | undefined;
|
|
draftWorkspace: RuntimeWorkspace | undefined;
|
|
previewBrand: BrandProfile;
|
|
selectedDetailOfferingId: string | undefined;
|
|
form: FormInstance<PresentationValues>;
|
|
initialValues: PresentationValues;
|
|
save: {
|
|
error: unknown;
|
|
isError: boolean;
|
|
isPending: boolean;
|
|
mutate: (values: PresentationValues) => void;
|
|
};
|
|
offeringsQuery: PresentationRecordQuery;
|
|
trustQuery: PresentationRecordQuery;
|
|
recordDraft: RecordDraft | undefined;
|
|
inquiryDraft: RuntimeWorkspace["inquiryForms"][number]["fields"] | undefined;
|
|
brandDirty: boolean;
|
|
selection: PreviewSelection | undefined;
|
|
activeTarget: string | undefined;
|
|
guardDraft: (action: () => void) => void;
|
|
selectPage: (page: string) => void;
|
|
selectDetailOffering: (id: string) => void;
|
|
selectPreviewTarget: (target: PreviewTarget) => void;
|
|
handleTargetSelected: (next?: PreviewSelection) => void;
|
|
setRecordDraft: (draft: RecordDraft | undefined) => void;
|
|
setInquiryDraft: (fields: RuntimeWorkspace["inquiryForms"][number]["fields"] | undefined) => void;
|
|
handleValuesChange: (changed: PresentationValues, allValues: PresentationValues) => void;
|
|
navigate: NavigateFunction;
|
|
}
|
|
|
|
/**
|
|
* PresentationEditor 的状态与派生数据集中在此处。
|
|
* 视图组件只负责渲染,避免页面组件继续膨胀。
|
|
*/
|
|
export function usePresentationEditorController({
|
|
templateContent,
|
|
previewWorkspace,
|
|
config,
|
|
brand,
|
|
initialSelection,
|
|
}: PresentationEditorControllerInput): PresentationEditorController {
|
|
const queryClient = useQueryClient();
|
|
const navigate = useNavigate();
|
|
const [activePage, setActivePage] = useState<string>();
|
|
const [selection, setSelection] = useState<PreviewSelection | undefined>(initialSelection);
|
|
const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection));
|
|
const [detailOfferingId, setDetailOfferingId] = useState<string>();
|
|
const [recordDraft, setRecordDraft] = useState<RecordDraft>();
|
|
const [inquiryDraft, setInquiryDraft] =
|
|
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
|
|
const [brandDirty, setBrandDirty] = useState(false);
|
|
const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft);
|
|
const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand");
|
|
const sections = useBrandPresentationSections(templateContent);
|
|
const pageOptions = useMemo(() => {
|
|
const pages = new Map<string, string>();
|
|
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<PreviewTarget[]>(
|
|
() =>
|
|
[...(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, trustQuery, selectedRecord } = usePresentationRecordQueries(
|
|
selectedRecordSource,
|
|
selection?.recordId,
|
|
);
|
|
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 formState = useBrandPresentationForm({ brand, config, sections });
|
|
const { form, initialValues } = formState;
|
|
const save = useBrandSaveMutation({
|
|
...formState,
|
|
brand,
|
|
config,
|
|
sections,
|
|
queryClient,
|
|
onSaved: () => setBrandDirty(false),
|
|
});
|
|
|
|
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],
|
|
);
|
|
const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({
|
|
brand,
|
|
config,
|
|
sections,
|
|
form,
|
|
onDirty: () => setBrandDirty(true),
|
|
});
|
|
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
|
|
useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
|
|
const draftWorkspace = useDraftWorkspace({
|
|
previewWorkspace,
|
|
previewBrand,
|
|
inquiryRuntime,
|
|
inquiryDraft,
|
|
recordDraft,
|
|
selectedRecord,
|
|
recordSection,
|
|
recordPreview,
|
|
templateContent,
|
|
});
|
|
const selectedDetailOfferingId =
|
|
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
|
|
? detailOfferingId
|
|
: draftWorkspace?.offerings[0]?.id;
|
|
|
|
const selectPage = useCallback(
|
|
(page: string) => {
|
|
guardDraft(() => {
|
|
setBrandDirty(false);
|
|
resetPreview();
|
|
setRecordDraft(undefined);
|
|
setInquiryDraft(undefined);
|
|
setActivePage(page);
|
|
});
|
|
},
|
|
[guardDraft, resetPreview],
|
|
);
|
|
const selectDetailOffering = useCallback((id: string) => {
|
|
setDetailOfferingId(id);
|
|
setSelection(undefined);
|
|
}, []);
|
|
const selectPreviewTarget = useCallback(
|
|
(target: PreviewTarget) => {
|
|
const recordId =
|
|
target.source === "offering"
|
|
? selectedPage === "detail"
|
|
? selectedDetailOfferingId
|
|
: draftWorkspace?.offerings[0]?.id
|
|
: target.source === "trust"
|
|
? previewTrustRecordId(draftWorkspace?.trustItems ?? [], target.trustType)
|
|
: undefined;
|
|
handleTargetSelected({
|
|
targetKey: target.key,
|
|
...(recordId ? { recordId } : {}),
|
|
});
|
|
},
|
|
[handleTargetSelected, selectedPage, selectedDetailOfferingId, draftWorkspace],
|
|
);
|
|
|
|
return {
|
|
pageOptions,
|
|
selectedPage,
|
|
visibleTargets,
|
|
selectedTarget,
|
|
selectedSection,
|
|
selectedRecordSource,
|
|
selectedRecord,
|
|
recordSection,
|
|
editableSections,
|
|
relevantPageLinks,
|
|
inquiryRuntime,
|
|
draftWorkspace,
|
|
previewBrand,
|
|
selectedDetailOfferingId,
|
|
form,
|
|
initialValues,
|
|
save,
|
|
offeringsQuery,
|
|
trustQuery,
|
|
recordDraft,
|
|
inquiryDraft,
|
|
brandDirty,
|
|
selection,
|
|
activeTarget,
|
|
guardDraft,
|
|
selectPage,
|
|
selectDetailOffering,
|
|
selectPreviewTarget,
|
|
handleTargetSelected,
|
|
setRecordDraft,
|
|
setInquiryDraft,
|
|
handleValuesChange,
|
|
navigate,
|
|
};
|
|
}
|