import { useState } from "react"; import { useTranslation } from "react-i18next"; import { useRequest } from "ahooks"; import { Button, Form, Input, message, notification, Skeleton } from "antd"; import { createSchemaFieldRule } from "antd-zod"; import { ClientResponseError } from "pocketbase"; import { z } from "zod"; 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"; export type NotifyTemplateFormProps = { className?: string; style?: React.CSSProperties; }; const NotifyTemplateForm = ({ className, style }: NotifyTemplateFormProps) => { const { t } = useTranslation(); const [messageApi, MessageContextHolder] = message.useMessage(); const [notificationApi, NotificationContextHolder] = notification.useNotification(); const formSchema = z.object({ subject: z .string() .min(1, t("settings.notification.template.form.subject.placeholder")) .max(1000, t("common.errmsg.string_max", { max: 1000 })) .trim(), message: z .string() .min(1, t("settings.notification.template.form.message.placeholder")) .max(1000, t("common.errmsg.string_max", { max: 1000 })) .trim(), }); const formRule = createSchemaFieldRule(formSchema); const { form: formInst, formPending, formProps, } = useAntdForm>({ initialValues: defaultNotifyTemplate, onSubmit: async (values) => { try { const settings = await getSettings(SETTINGS_NAMES.NOTIFY_TEMPLATES); await saveSettings({ ...settings, content: { notifyTemplates: [values], }, }); 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( () => { return getSettings(SETTINGS_NAMES.NOTIFY_TEMPLATES); }, { onError: (err) => { if (err instanceof ClientResponseError && err.isAbort) { return; } console.error(err); }, onFinally: (_, resp) => { const template = resp?.content?.notifyTemplates?.[0] ?? defaultNotifyTemplate; formInst.setFieldsValue(template); }, } ); const handleInputChange = () => { setFormChanged(true); }; return (
{MessageContextHolder} {NotificationContextHolder} }>
); }; export default NotifyTemplateForm;