Files
persionalBrand/apps/admin/src/features/brand/InquiryPreviewEditor.tsx
T

144 lines
5.1 KiB
TypeScript

import { Alert, App, Button, Form, Input, Select, Space, Switch } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import type { RuntimeWorkspace } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { MutationError } from "../../components/QueryState.js";
type RuntimeInquiryForm = RuntimeWorkspace["inquiryForms"][number];
export function InquiryPreviewEditor({
runtime,
fieldKey,
onDraft,
onSaved,
}: {
runtime: RuntimeInquiryForm;
fieldKey: string;
onDraft: (fields: RuntimeInquiryForm["fields"]) => void;
onSaved?: () => void;
}) {
const { message } = App.useApp();
const [form] = Form.useForm<Record<string, unknown>>();
const cache = useQueryClient();
const query = useQuery({
queryKey: ["admin-inquiry-forms"],
queryFn: () => createApiClient().listAdminInquiryForms(),
});
const record = query.data?.find((item) => item.id === runtime.key);
const field = runtime.fields.find((item) => item.key === fieldKey);
useEffect(() => {
if (!record || !field) return;
form.setFieldsValue({ ...field });
}, [field, fieldKey, form, record, runtime.key]);
const update = (values: Record<string, unknown>) =>
runtime.fields.map((item) => (item.key === fieldKey ? { ...item, ...values } : item));
const save = useMutation({
mutationFn: async (values: Record<string, unknown>) => {
if (!record || !field) throw new Error("表单已不存在,请刷新后重试");
const fieldsSnapshot = record.fieldsSnapshot.map((item) => {
if (!item || typeof item !== "object" || (item as { key?: string }).key !== fieldKey)
return item;
const type =
values.type === "tel"
? "phone"
: values.type === "checkbox"
? "multi-select"
: values.type;
return { ...item, ...values, type };
});
return createApiClient().updateAdminInquiryForm(record.id, { fieldsSnapshot });
},
onSuccess: () => {
onSaved?.();
message.success("表单字段已保存为草稿");
void cache.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
void cache.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
void cache.invalidateQueries({ queryKey: ["publication-readiness"] });
},
});
if (query.isError)
return (
<Alert
type="error"
title="表单读取失败"
action={<Button onClick={() => void query.refetch()}>重试</Button>}
/>
);
if (!record)
return (
<Alert
type="info"
title={query.isPending ? "正在读取表单" : "未找到对应表单,请刷新后重试"}
/>
);
if (!field) return <Alert type="warning" title="字段已不存在" />;
return (
<Form<Record<string, unknown>>
form={form}
layout="vertical"
initialValues={field}
onValuesChange={(_, values) => onDraft(update(values))}
onFinish={(values) => save.mutate(values)}
>
<p className="admin-section-description admin-offset-bottom">
{record.name} · 编辑字段:{field.label}
</p>
<Form.Item
name="label"
label="字段标题"
rules={[{ required: true, message: "请填写字段标题" }]}
>
<Input />
</Form.Item>
<Form.Item name="type" label="输入方式">
<Select
options={[
{ value: "text", label: "简短文字" },
{ value: "textarea", label: "详细说明" },
{ value: "tel", label: "联系电话" },
{ value: "number", label: "数字" },
{ value: "date", label: "日期" },
{ value: "select", label: "单项选择" },
{ value: "radio", label: "单选按钮" },
{ value: "checkbox", label: "多项选择" },
]}
/>
</Form.Item>
<Form.Item name="required" label="必填" valuePropName="checked">
<Switch />
</Form.Item>
<Form.List name="options">
{(fields, { add, remove }) => (
<div>
{fields.length ? <h4 className="admin-subhead admin-offset-bottom-xs">选项</h4> : null}
{fields.map(({ key, name }) => (
<Space key={key} align="start">
<Form.Item name={[name, "label"]} label="选项名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name={[name, "value"]} label="选项标识" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Button onClick={() => remove(name)}>删除</Button>
</Space>
))}
<Button onClick={() => add({ label: "新选项", value: crypto.randomUUID() })}>
添加选项
</Button>
</div>
)}
</Form.List>
<MutationError error={save.error} />
<Button
className="admin-offset-top-lg"
type="primary"
htmlType="submit"
loading={save.isPending}
>
保存表单字段
</Button>
</Form>
);
}