refactor: 建立代码标准并拆分品牌编辑状态

This commit is contained in:
que01 committed 2026-10-12 03:08:24 +08:00
1 parent 567921e726
commit 3003e7801d
4 files changed
+344 -172

No files matched your search

@@ -11,9 +11,8 @@ import {
Space,
Tag,
Typography,
message,
} from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import type {
@@ -24,7 +23,6 @@ import type {
} 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 { TemplateListField } from "../../components/TemplateListField.js";
import { TemplateFieldRenderer } from "../../components/TemplateFieldRenderer.js";
import { MutationError } from "../../components/QueryState.js";
@@ -38,17 +36,20 @@ import {
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";
import {
usePresentationRecordQueries,
useBrandPresentationSections,
useBrandSaveMutation,
useBrandPresentationForm,
useBrandPreviewDraft,
} from "./presentation-editor-state.js";
import { useRecordPreview } from "./presentation-editor-record-preview.js";
interface PresentationEditorProps {
templateContent: AdminTemplateContent | null | undefined;
@@ -136,7 +137,6 @@ export function PresentationEditor({
error,
initialSelection,
}: PresentationEditorProps) {
const [form] = Form.useForm<PresentationValues>();
const queryClient = useQueryClient();
const navigate = useNavigate();
const breakpoints = Grid.useBreakpoint();
@@ -149,45 +149,12 @@ export function PresentationEditor({
id: string;
values: PresentationValues;
}>();
const [previewConfig, setPreviewConfig] = useState(config ?? {});
const [previewBrandValues, setPreviewBrandValues] = useState<Record<string, unknown>>({});
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 = 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 sections = useBrandPresentationSections(templateContent);
const pageOptions = useMemo(() => {
const pages = new Map<string, string>();
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
@@ -248,23 +215,10 @@ export function PresentationEditor({
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 { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries(
selectedRecordSource,
selection?.recordId,
);
const editableSections = filterSectionsForPreviewTarget(
visibleSections.filter((section) =>
section.fields.some((field) => field.binding.startsWith("brand.")),
@@ -342,58 +296,9 @@ export function PresentationEditor({
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<string, unknown>,
);
}
}
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<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: 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]);
const formState = useBrandPresentationForm({ brand, config, sections });
const { form, initialValues } = formState;
const save = useBrandSaveMutation({ ...formState, brand, config, sections, queryClient });
useEffect(() => {
const initialPage =
@@ -453,62 +358,16 @@ export function PresentationEditor({
() => setRecordDraft(undefined),
[selection?.targetKey, selection?.recordId, selectedPage],
);
useEffect(() => {
setPreviewConfig(config ?? {});
setPreviewBrandValues({});
}, [config, initialValues]);
const previewBrand = useMemo(
() => ({ ...brand, ...previewBrandValues, config: previewConfig }),
[brand, previewBrandValues, previewConfig],
);
const recordPreview = useMemo(() => {
if (!recordDraft || !selectedRecord || !recordSection) return undefined;
const config = applyPresentationValues(
selectedRecord.config,
[recordSection],
recordDraft.values,
);
return {
config,
standard: applyStandardEntityValues(
selectedRecord as unknown as Record<string, unknown>,
recordDraft.source,
[recordSection],
recordDraft.values,
),
};
}, [recordDraft, selectedRecord, recordSection]);
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<string, unknown>,
config,
sections,
synchronized,
);
setPreviewConfig((next.config as Record<string, unknown>) ?? {});
setPreviewBrandValues(next);
},
[brand, config, sections, form],
);
const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({
brand,
config,
sections,
form,
onDirty: () => setBrandDirty(true),
});
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
const previewConfig = previewBrand.config;
const draftWorkspace = useMemo(() => {
if (!previewWorkspace) return undefined;
const next: RuntimeWorkspace = {
@@ -652,8 +511,7 @@ export function PresentationEditor({
guardDraft(() => {
setBrandDirty(false);
form.setFieldsValue(initialValues);
setPreviewConfig(config ?? {});
setPreviewBrandValues({});
resetPreview();
setRecordDraft(undefined);
setInquiryDraft(undefined);
setActivePage(value);
@@ -669,8 +527,7 @@ export function PresentationEditor({
guardDraft(() => {
setBrandDirty(false);
form.setFieldsValue(initialValues);
setPreviewConfig(config ?? {});
setPreviewBrandValues({});
resetPreview();
setRecordDraft(undefined);
setInquiryDraft(undefined);
setActivePage(String(value));
@@ -0,0 +1,39 @@
import { useMemo } from "react";
import type { Offering, TrustContent } from "@personal-brand/api-client";
import type { TemplateAdminSection } from "@personal-brand/api-client";
import { applyPresentationValues, applyStandardEntityValues } from "./presentation-bindings.js";
import type { PresentationValues } from "./presentation-bindings.js";
export interface RecordDraft {
source: "offering" | "trust";
id: string;
values: PresentationValues;
}
export function useRecordPreview({
recordDraft,
selectedRecord,
recordSection,
}: {
recordDraft?: RecordDraft | undefined;
selectedRecord?: Offering | TrustContent | undefined;
recordSection?: TemplateAdminSection | undefined;
}) {
return useMemo(() => {
if (!recordDraft || !selectedRecord || !recordSection) return undefined;
const config = applyPresentationValues(
selectedRecord.config,
[recordSection],
recordDraft.values,
);
return {
config,
standard: applyStandardEntityValues(
selectedRecord as unknown as Record<string, unknown>,
recordDraft.source,
[recordSection],
recordDraft.values,
),
};
}, [recordDraft, selectedRecord, recordSection]);
}
@@ -0,0 +1,226 @@
import { Form, message } from "antd";
import { useMutation, useQuery } from "@tanstack/react-query";
import type { QueryClient } from "@tanstack/react-query";
import { 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 {
applyBrandPreviewValues,
applyPresentationValues,
applyStandardBrandValues,
presentationFieldName,
readPresentationValue,
type PresentationValues,
} from "./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]);
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
return { form, initialValues };
}
interface BrandSaveMutationOptions extends BrandPresentationFormState {
brand: BrandProfile;
config: Record<string, unknown> | null | undefined;
sections: TemplateAdminSection[];
queryClient: QueryClient;
}
export function useBrandSaveMutation({
brand,
config,
sections,
queryClient,
}: BrandSaveMutationOptions) {
return useMutation({
mutationFn: (values: PresentationValues) => {
const nextConfig = applyPresentationValues(config, sections, values);
const contentConfig = { ...nextConfig };
delete contentConfig.visualTemplateKey;
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: contentConfig });
},
onSuccess: () => {
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 = {
...(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<string, unknown>,
config,
sections,
synchronized,
);
setPreviewConfig((next.config as Record<string, unknown>) ?? {});
setPreviewBrandValues(next);
};
const previewBrand = useMemo(
() => ({ ...brand, ...previewBrandValues, config: previewConfig }),
[brand, previewBrandValues, previewConfig],
);
return {
previewBrand,
handleValuesChange,
resetPreview: () => {
setPreviewConfig(config ?? {});
setPreviewBrandValues({});
},
};
}
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 };
}
+50
View File
@@ -0,0 +1,50 @@
# 代码结构与重构标准
这份标准用于控制现有模块继续膨胀,并约束后续大文件重构。它不是替代 `docs/engineering-delivery-checklist.md`,而是补充结构边界。
## 通用规则
- 页面、Controller、Service 只保留一个明确入口;独立业务规则、数据映射、授权判断和视图状态必须拆出命名模块。
- 单文件超过 500 行必须提供拆分计划;超过 800 行应拆分。拆分要按职责,不按行数机械切分。
- 禁止在页面组件内内联完整 API 调用、复杂 JSON 转换和多层级业务规则。
- 禁止新增全局工具函数堆积文件;按领域模块导出,不建 `utils.ts` 黑洞。
- 迁移、DTO、API Client 类型、页面、测试和文档随行为一起变更。
## Admin React 标准
- 页面组件负责组合布局和路由;不直接实现超过一个相关领域的业务逻辑。
- 一个页面由以下边界组成:
- 页面组件:布局、路由、页面状态组合。
- hooks:数据查询、mutation、表单初始化、草稿与预览状态。
- 领域工具:纯函数,可单测,不调用 `fetch`。
- feature 组件:局部 UI 区块。
- shared components:跨 feature 使用的表单字段、状态和基础控件。
- React Query 的 query key、失效和成功提示统一放在 hooks 中;页面不要散落 `invalidateQueries`。
- 表单初始化、同步字段、脏检查和失败恢复不能重复实现;优先复用同一模块。
- 类型边界使用 API Client 导出类型,不在页面重建后端响应形状。
## API NestJS 标准
- Controller 只处理认证入口、DTO、状态码、响应形状和路由。
- 授权、Prisma、模板安装、快照组装、工作流推进必须进入 Service 或 Guard。
- 同一个领域不要分散在根目录和 modules 中;新代码必须归入领域模块,旧 Controller 重构时逐步迁移。
- DTO 是唯一输入边界;禁止 `Partial<T>`、`any`、未验证 JSON 和 Controller 内私有 schema。
- 授权测试、成功行为、失败路径和品牌隔离测试是结构重构不可删除的回归线。
## API Client 标准
- 按资源拆分方法模块和类型模块;`index.ts` 只做聚合导出和 Client 组装。
- 一个资源定义一组类型、一组方法、一致的错误语义,不在 Client 内做页面专用逻辑。
## Config 与模板包标准
- manifest、runtime、admin 契约、示例内容分别放独立模块;避免一个大索引文件同时承载所有契约。
- 模板字段必须声明 binding、输入类型和预览目标;模板键使用 allow-list,不接受任意字符串。
## 重构流程
1. 先建立或修改标准,再动代码。
2. 每轮只处理一个高影响热点,保持外部行为不变。
3. 重构后运行 `pnpm format:check`、`pnpm lint`、`pnpm typecheck`、相关测试和生产构建。
4. 行为变化必须有测试;纯结构重构也必须保留所有授权、品牌隔离和关键 UI 状态测试。
5. 在分支完成并全量验证后合并回 `main`。