Files
persionalBrand/apps/admin/src/features/brand/presentation-editor-state.ts
T
que01 aa2b6f35b0
CI / Browser smoke (pull_request) Successful in 47s
CI / Static checks (pull_request) Successful in 58s
CI / API integration (pull_request) Successful in 1m7s
CI / Production build (pull_request) Successful in 1m24s
refactor: 抽取共享 getFullFormValues 表单读取工具
2026-10-29 14:24:23 +08:00

231 lines
7.2 KiB
TypeScript

import { App, Form } from "antd";
import { useMutation, useQuery } from "@tanstack/react-query";
import type { QueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import type { FormInstance } from "antd";
import type {
AdminTemplateContent,
BrandProfile,
Offering,
TemplateAdminSection,
TrustContent,
} from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { getFullFormValues } from "../../lib/form-values.js";
import {
applyBrandPreviewValues,
applyPresentationValues,
applyStandardBrandValues,
presentationFieldName,
readPresentationValue,
type PresentationValues,
} from "../../lib/presentation/presentation-bindings.js";
const standardBrandBindings = [
"brand.name",
"brand.tagline",
"brand.avatarUrl",
"brand.description",
"brand.contactPhone",
"brand.contactWechat",
"brand.address",
] as const;
export interface BrandPresentationFormState {
form: FormInstance<PresentationValues>;
initialValues: PresentationValues;
}
export function useBrandPresentationSections(
templateContent: AdminTemplateContent | null | undefined,
): TemplateAdminSection[] {
return 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.") ||
(standardBrandBindings as readonly string[]).includes(field.binding),
),
}));
}, [templateContent]);
}
export function useBrandPresentationForm({
brand,
config,
sections,
}: {
brand: BrandProfile;
config: Record<string, unknown> | null | undefined;
sections: TemplateAdminSection[];
}): BrandPresentationFormState {
const [form] = Form.useForm<PresentationValues>();
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<string, unknown>,
);
}
}
return values;
}, [brand, config, sections]);
return { form, initialValues };
}
interface BrandSaveMutationOptions extends BrandPresentationFormState {
brand: BrandProfile;
config: Record<string, unknown> | null | undefined;
sections: TemplateAdminSection[];
queryClient: QueryClient;
onSaved: () => void;
}
export function useBrandSaveMutation({
brand,
config,
sections,
queryClient,
onSaved,
}: BrandSaveMutationOptions) {
const { message } = App.useApp();
return useMutation({
mutationFn: (values: PresentationValues) => {
const nextConfig = applyPresentationValues(config, sections, values);
const standard = applyStandardBrandValues(
brand as unknown as Record<string, unknown>,
sections,
values,
);
const changed = Object.fromEntries(
Object.entries(standard).filter(
([key, value]) =>
key !== "config" && value !== (brand as unknown as Record<string, unknown>)[key],
),
);
return createApiClient().updateAdminBrand({ ...changed, config: nextConfig });
},
onSuccess: () => {
onSaved();
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"] });
},
});
}
export function useBrandPreviewDraft({
brand,
config,
sections,
form,
onDirty,
}: {
brand: BrandProfile;
config: Record<string, unknown> | null | undefined;
sections: TemplateAdminSection[];
form: BrandPresentationFormState["form"];
onDirty: () => void;
}) {
const [previewConfig, setPreviewConfig] = useState(config ?? {});
const [previewBrandValues, setPreviewBrandValues] = useState<Record<string, unknown>>({});
useEffect(() => {
setPreviewConfig(config ?? {});
setPreviewBrandValues({});
}, [config, form]);
const handleValuesChange = (changed: PresentationValues, allValues: PresentationValues) => {
onDirty();
const synchronized: PresentationValues = {
...getFullFormValues<PresentationValues>(form),
...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<string, unknown>,
config,
sections,
synchronized,
);
setPreviewConfig((next.config as Record<string, unknown>) ?? {});
setPreviewBrandValues(next);
};
const previewBrand = useMemo(
() => ({ ...brand, ...previewBrandValues, config: previewConfig }),
[brand, previewBrandValues, previewConfig],
);
const resetPreview = useCallback(() => {
setPreviewConfig(config ?? {});
setPreviewBrandValues({});
}, [config]);
return {
previewBrand,
handleValuesChange,
resetPreview,
};
}
export function usePresentationRecordQueries(
source: "offering" | "trust" | undefined,
recordId: string | undefined,
) {
const offeringsQuery = useQuery({
queryKey: ["admin-offerings"],
queryFn: () => createApiClient().listAdminOfferings(),
enabled: source === "offering",
refetchOnMount: "always",
});
const trustQuery = useQuery({
queryKey: ["trust-content"],
queryFn: () => createApiClient().listAdminTrustContent(),
enabled: source === "trust",
});
const selectedRecord =
source === "offering"
? offeringsQuery.data?.find((item: Offering) => item.id === recordId)
: source === "trust"
? trustQuery.data?.find((item: TrustContent) => item.id === recordId)
: undefined;
return { offeringsQuery, trustQuery, selectedRecord };
}