refactor(ui): useAntdForm

This commit is contained in:
Fu Diwei
2024-12-25 14:51:32 +08:00
parent c9024c5611
commit 4d0f7c2e02
43 changed files with 779 additions and 677 deletions

View File

@@ -1,7 +1,8 @@
import { forwardRef, useImperativeHandle, useMemo, useState } from "react";
import { useCreation, useDeepCompareEffect } from "ahooks";
import { forwardRef, useImperativeHandle, useMemo } from "react";
import { useCreation } from "ahooks";
import { Form } from "antd";
import { useAntdForm } from "@/hooks";
import { NOTIFY_CHANNELS, type NotifyChannelsSettingsContent } from "@/domain/settings";
import NotifyChannelEditFormBarkFields from "./NotifyChannelEditFormBarkFields";
import NotifyChannelEditFormDingTalkFields from "./NotifyChannelEditFormDingTalkFields";
@@ -12,26 +13,28 @@ import NotifyChannelEditFormTelegramFields from "./NotifyChannelEditFormTelegram
import NotifyChannelEditFormWebhookFields from "./NotifyChannelEditFormWebhookFields";
import NotifyChannelEditFormWeComFields from "./NotifyChannelEditFormWeComFields";
type NotifyChannelEditFormModelType = NotifyChannelsSettingsContent[keyof NotifyChannelsSettingsContent];
type NotifyChannelEditFormModelValues = NotifyChannelsSettingsContent[keyof NotifyChannelsSettingsContent];
export type NotifyChannelEditFormProps = {
className?: string;
style?: React.CSSProperties;
channel: string;
disabled?: boolean;
model?: NotifyChannelEditFormModelType;
onModelChange?: (model: NotifyChannelEditFormModelType) => void;
model?: NotifyChannelEditFormModelValues;
onModelChange?: (model: NotifyChannelEditFormModelValues) => void;
};
export type NotifyChannelEditFormInstance = {
getFieldsValue: () => NotifyChannelEditFormModelType;
getFieldsValue: () => NotifyChannelEditFormModelValues;
resetFields: () => void;
validateFields: () => Promise<NotifyChannelEditFormModelType>;
validateFields: () => Promise<NotifyChannelEditFormModelValues>;
};
const NotifyChannelEditForm = forwardRef<NotifyChannelEditFormInstance, NotifyChannelEditFormProps>(
({ className, style, channel, disabled, model, onModelChange }, ref) => {
const [form] = Form.useForm();
const { form: formInst, formProps } = useAntdForm({
initialValues: model,
});
const formName = useCreation(() => `notifyChannelEditForm_${Math.random().toString(36).substring(2, 10)}${new Date().getTime()}`, []);
const formFieldsComponent = useMemo(() => {
/*
@@ -58,36 +61,31 @@ const NotifyChannelEditForm = forwardRef<NotifyChannelEditFormInstance, NotifyCh
}
}, [channel]);
const [initialValues, setInitialValues] = useState(model);
useDeepCompareEffect(() => {
setInitialValues(model);
}, [model]);
const handleFormChange = (_: unknown, fields: NotifyChannelEditFormModelType) => {
onModelChange?.(fields);
const handleFormChange = (_: unknown, values: NotifyChannelEditFormModelValues) => {
onModelChange?.(values);
};
useImperativeHandle(ref, () => ({
getFieldsValue: () => {
return form.getFieldsValue(true);
return formInst.getFieldsValue(true);
},
resetFields: () => {
return form.resetFields();
return formInst.resetFields();
},
validateFields: () => {
return form.validateFields();
return formInst.validateFields();
},
}));
return (
<Form
{...formProps}
className={className}
style={style}
form={form}
form={formInst}
disabled={disabled}
initialValues={initialValues}
layout="vertical"
name={formName}
layout="vertical"
onValuesChange={handleFormChange}
>
{formFieldsComponent}

View File

@@ -56,13 +56,13 @@ const NotifyChannelEditFormEmailFields = () => {
</div>
<div className="w-2/5">
<Form.Item name="smtpPort" label={t("settings.notification.channel.form.email_smtp_port.label")} rules={[formRule]} initialValue={465}>
<Form.Item name="smtpPort" label={t("settings.notification.channel.form.email_smtp_port.label")} rules={[formRule]}>
<InputNumber className="w-full" placeholder={t("settings.notification.channel.form.email_smtp_port.placeholder")} min={1} max={65535} />
</Form.Item>
</div>
<div className="w-1/5">
<Form.Item name="smtpTLS" label={t("settings.notification.channel.form.email_smtp_tls.label")} rules={[formRule]} initialValue={true}>
<Form.Item name="smtpTLS" label={t("settings.notification.channel.form.email_smtp_tls.label")} rules={[formRule]}>
<Switch onChange={handleTLSSwitchChange} />
</Form.Item>
</div>

View File

@@ -25,10 +25,10 @@ const NotifyChannel = ({ className, style, channel }: NotifyChannelProps) => {
const { channels, setChannel } = useNotifyChannelStore();
const channelConfig = useDeepCompareMemo(() => channels[channel], [channels, channel]);
const [channelFormChanged, setChannelFormChanged] = useState(false);
const channelFormRef = useRef<NotifyChannelEditFormInstance>(null);
const [channelFormChanged, setChannelFormChanged] = useState(false);
const handleClickSubmit = async () => {
const handleSubmit = async () => {
await channelFormRef.current!.validateFields();
try {
@@ -49,7 +49,7 @@ const NotifyChannel = ({ className, style, channel }: NotifyChannelProps) => {
<NotifyChannelEditForm ref={channelFormRef} className="mt-2" channel={channel} model={channelConfig} onModelChange={() => setChannelFormChanged(true)} />
<Space className="mb-2">
<Button type="primary" disabled={!channelFormChanged} onClick={handleClickSubmit}>
<Button type="primary" disabled={!channelFormChanged} onClick={handleSubmit}>
{t("common.button.save")}
</Button>

View File

@@ -7,6 +7,7 @@ import { z } from "zod";
import { ClientResponseError } from "pocketbase";
import Show from "@/components/Show";
import { useAntdForm } from "@/hooks";
import { defaultNotifyTemplate, SETTINGS_NAMES, type NotifyTemplatesSettingsContent } from "@/domain/settings";
import { get as getSettings, save as saveSettings } from "@/repository/settings";
import { getErrMsg } from "@/utils/error";
@@ -35,11 +36,29 @@ const NotifyTemplateForm = ({ className, style }: NotifyTemplateFormProps) => {
.max(1000, t("common.errmsg.string_max", { max: 1000 })),
});
const formRule = createSchemaFieldRule(formSchema);
const [form] = Form.useForm<z.infer<typeof formSchema>>();
const [formPending, setFormPending] = useState(false);
const {
form: formInst,
formPending,
formProps,
} = useAntdForm<z.infer<typeof formSchema>>({
initialValues: defaultNotifyTemplate,
onSubmit: async (values) => {
try {
const settings = await getSettings<NotifyTemplatesSettingsContent>(SETTINGS_NAMES.NOTIFY_TEMPLATES);
await saveSettings<NotifyTemplatesSettingsContent>({
...settings,
content: {
notifyTemplates: [values],
},
});
const [initialValues, setInitialValues] = useState<Partial<z.infer<typeof formSchema>>>();
const [initialChanged, setInitialChanged] = useState(false);
messageApi.success(t("common.text.operation_succeeded"));
} catch (err) {
notificationApi.error({ message: t("common.text.request_error"), description: getErrMsg(err) });
}
},
});
const [formChanged, setFormChanged] = useState(false);
const { loading } = useRequest(
() => {
@@ -55,33 +74,13 @@ const NotifyTemplateForm = ({ className, style }: NotifyTemplateFormProps) => {
},
onFinally: (_, resp) => {
const template = resp?.content?.notifyTemplates?.[0] ?? defaultNotifyTemplate;
setInitialValues(template);
formInst.setFieldsValue(template);
},
}
);
const handleInputChange = () => {
setInitialChanged(true);
};
const handleFormFinish = async (fields: z.infer<typeof formSchema>) => {
setFormPending(true);
try {
const settings = await getSettings<NotifyTemplatesSettingsContent>(SETTINGS_NAMES.NOTIFY_TEMPLATES);
await saveSettings<NotifyTemplatesSettingsContent>({
...settings,
content: {
notifyTemplates: [fields],
},
});
messageApi.success(t("common.text.operation_succeeded"));
} catch (err) {
notificationApi.error({ message: t("common.text.request_error"), description: getErrMsg(err) });
} finally {
setFormPending(false);
}
setFormChanged(true);
};
return (
@@ -90,11 +89,11 @@ const NotifyTemplateForm = ({ className, style }: NotifyTemplateFormProps) => {
{NotificationContextHolder}
<Show when={!loading} fallback={<Skeleton active />}>
<Form form={form} disabled={formPending} initialValues={initialValues} layout="vertical" onFinish={handleFormFinish}>
<Form {...formProps} form={formInst} disabled={formPending} layout="vertical">
<Form.Item
name="subject"
label={t("settings.notification.template.form.subject.label")}
extra={t("settings.notification.template.form.subject.tooltip")}
extra={t("settings.notification.template.form.subject.extra")}
rules={[formRule]}
>
<Input placeholder={t("settings.notification.template.form.subject.placeholder")} onChange={handleInputChange} />
@@ -103,7 +102,7 @@ const NotifyTemplateForm = ({ className, style }: NotifyTemplateFormProps) => {
<Form.Item
name="message"
label={t("settings.notification.template.form.message.label")}
extra={t("settings.notification.template.form.message.tooltip")}
extra={t("settings.notification.template.form.message.extra")}
rules={[formRule]}
>
<Input.TextArea
@@ -114,7 +113,7 @@ const NotifyTemplateForm = ({ className, style }: NotifyTemplateFormProps) => {
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" disabled={!initialChanged} loading={formPending}>
<Button type="primary" htmlType="submit" disabled={!formChanged} loading={formPending}>
{t("common.button.save")}
</Button>
</Form.Item>