import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { useDeepCompareEffect } from "ahooks"; import { Alert, Button, Form, Input, Radio } from "antd"; import { createSchemaFieldRule } from "antd-zod"; import dayjs from "dayjs"; import { z } from "zod"; import { usePanel } from "../PanelProvider"; import { useZustandShallowSelector } from "@/hooks"; import { type WorkflowNode, type WorkflowNodeConfig } from "@/domain/workflow"; import { useWorkflowStore } from "@/stores/workflow"; import { validCronExpression, getNextCronExecutions } from "@/utils/cron"; export type StartNodeFormProps = { data: WorkflowNode; }; const initFormModel = () => { return { executionMethod: "auto", crontab: "0 0 * * *", } as WorkflowNodeConfig; }; const StartNodeForm = ({ data }: StartNodeFormProps) => { const { t } = useTranslation(); const { updateNode } = useWorkflowStore(useZustandShallowSelector(["updateNode"])); const { hidePanel } = usePanel(); const formSchema = z .object({ executionMethod: z.string({ message: t("workflow.nodes.start.form.trigger.placeholder") }).min(1, t("workflow.nodes.start.form.trigger.placeholder")), crontab: z.string().nullish(), }) .superRefine((data, ctx) => { if (data.executionMethod !== "auto") { return; } if (!validCronExpression(data.crontab!)) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: t("workflow.nodes.start.form.trigger_cron.errmsg.invalid"), path: ["crontab"], }); } }); const formRule = createSchemaFieldRule(formSchema); const [formInst] = Form.useForm>(); const [formPending, setFormPending] = useState(false); const [initialValues, setInitialValues] = useState>>( (data?.config as Partial>) ?? initFormModel() ); useDeepCompareEffect(() => { setInitialValues((data?.config as Partial>) ?? initFormModel()); }, [data?.config]); const [triggerType, setTriggerType] = useState(data?.config?.executionMethod); const [triggerCronLastExecutions, setTriggerCronExecutions] = useState([]); useEffect(() => { setTriggerType(data?.config?.executionMethod); setTriggerCronExecutions(getNextCronExecutions(data?.config?.crontab as string, 5)); }, [data?.config?.executionMethod, data?.config?.crontab]); const handleTriggerTypeChange = (value: string) => { setTriggerType(value); if (value === "auto") { formInst.setFieldValue("crontab", formInst.getFieldValue("crontab") || initFormModel().crontab); } }; const handleTriggerCronChange = (value: string) => { setTriggerCronExecutions(getNextCronExecutions(value, 5)); }; const handleFormFinish = async (values: z.infer) => { setFormPending(true); try { await updateNode({ ...data, config: { ...values }, validated: true }); hidePanel(); } finally { setFormPending(false); } }; return (
} > handleTriggerTypeChange(e.target.value)}> {t("workflow.nodes.start.form.trigger.option.auto.label")} {t("workflow.nodes.start.form.trigger.option.manual.label")}
); }; export default StartNodeForm;