refactor: 抽取业务与信任内容公共编辑器

This commit is contained in:
que01 committed 2026-10-10 17:03:41 +08:00
1 parent d2ce2d2a84
commit d0ef25cfb3
3 files changed
+221 -137

No files matched your search

@@ -0,0 +1,192 @@
import {
Alert,
Button,
Col,
Form,
Input,
InputNumber,
Row,
Select,
Space,
Switch,
Typography,
message,
} from "antd";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useEffect, useMemo } from "react";
import type {
Offering,
TemplateAdminField,
TemplateAdminSection,
TrustContent,
} from "@personal-brand/api-client";
import { createApiClient } from "../lib/api.js";
import { ImageUrlField } from "./ImageUrlField.js";
import { TemplateListField } from "./TemplateListField.js";
import { MutationError } from "./QueryState.js";
import {
applyPresentationValues,
applyStandardEntityValues,
presentationFieldName,
readPresentationValue,
type PresentationValues,
} from "../features/brand/presentation-bindings.js";
export type RecordContentSource = "offering" | "trust";
export interface RecordContentEditorProps {
source: RecordContentSource;
record: Offering | TrustContent;
section: TemplateAdminSection;
context: "visual" | "services";
onDraft?: (values: PresentationValues) => void;
onSaved?: () => void;
}
function renderField(field: TemplateAdminField) {
if (field.input === "textarea")
return (
<Input.TextArea
rows={3}
maxLength={field.maxLength}
showCount={!!field.maxLength}
placeholder={field.placeholder}
/>
);
if (field.input === "image")
return <ImageUrlField {...(field.placeholder ? { placeholder: field.placeholder } : {})} />;
if (field.input === "phone") return <Input type="tel" placeholder={field.placeholder} />;
if (field.input === "number") return <InputNumber min={0} placeholder={field.placeholder} />;
if (field.input === "boolean") return <Switch />;
if (field.input === "select")
return <Select options={(field.options ?? []).map((item) => ({ ...item }))} />;
if (field.input === "multi-select")
return (
<Select
mode="multiple"
options={(field.options ?? []).map((item) => ({ ...item }))}
placeholder={field.placeholder}
/>
);
return <Input placeholder={field.placeholder} />;
}
export function RecordContentFields({ section }: { section: TemplateAdminSection }) {
return (
<Row gutter={16}>
{section.fields.map((field) => (
<Col key={field.key} xs={24} md={24}>
{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>
);
}
export function RecordContentEditor({
source,
record,
section,
context,
onDraft,
onSaved,
}: RecordContentEditorProps) {
const [form] = Form.useForm<PresentationValues>();
const queryClient = useQueryClient();
const recordName = "name" in record ? record.name : record.title;
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: 0, display: "flex", flexDirection: "column" }}
>
<Alert
type="info"
showIcon
message={
source === "offering"
? `正在编辑业务提供项:${recordName}`
: `正在编辑信任内容:${recordName}`
}
description={
context === "visual"
? "这里修改的是业务或信任记录本身;业务提供项列表中打开同一项目,看到并修改的是同一份数据。"
: "这里修改的内容也会显示在小程序页面对应的卡片、列表或详情中;两处入口修改的是同一份数据。"
}
/>
{save.isPending ? <Typography.Text type="secondary">正在保存内容…</Typography.Text> : null}
<Typography.Paragraph type="secondary">{section.description}</Typography.Paragraph>
<div style={{ flex: 1 }}>
<RecordContentFields section={section} />
</div>
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
<MutationError error={save.error} />
<Button type="primary" htmlType="submit" loading={save.isPending}>
保存此项内容
</Button>
</Space>
</Form>
);
}