import { NormalisedAutomation, TimerLifeCycle, Trigger, TriggerDTO } from 'ontime-types'; import { useEffect } from 'react'; import { useForm } from 'react-hook-form'; import { addTrigger, editTrigger } from '../../../../common/api/automation'; import { maybeAxiosError } from '../../../../common/api/utils'; import Button from '../../../../common/components/buttons/Button'; import Input from '../../../../common/components/input/input/Input'; import Modal from '../../../../common/components/modal/Modal'; import Select from '../../../../common/components/select/Select'; import * as Panel from '../../panel-utils/PanelUtils'; import { cycles } from './automationUtils'; const formId = 'trigger-form'; interface TriggerFormProps { automations: NormalisedAutomation; trigger: Trigger | null; onCancel: () => void; postSubmit: () => void; } export default function TriggerForm({ automations, trigger, onCancel, postSubmit }: TriggerFormProps) { const { handleSubmit, register, setFocus, setError, watch, setValue, formState: { errors, isSubmitting, isValid, isDirty }, } = useForm({ defaultValues: { title: trigger?.title, trigger: trigger?.trigger ?? (cycles[0].value as TimerLifeCycle | undefined), automationId: trigger?.automationId ?? automations?.[Object.keys(automations)[0]]?.id, }, resetOptions: { keepDirtyValues: true, }, }); // give initial focus to the title field useEffect(() => { setFocus('title'); }, [setFocus]); const onSubmit = async (values: TriggerDTO) => { if (trigger) { try { await editTrigger(trigger.id, { id: trigger.id, ...values }); postSubmit(); } catch (error) { setError('root', { message: `Failed to save changes to trigger ${maybeAxiosError(error)}` }); } return; } // otherwise we are creating a new automation try { await addTrigger(values); postSubmit(); } catch (error) { setError('root', { message: `Failed to save trigger ${maybeAxiosError(error)}` }); } }; const automationSelect = Object.keys(automations).map((automation) => { return { value: automation, label: automations[automation].title, }; }); const canSubmit = isDirty && isValid; return ( } footerElements={ <> {errors.root && {errors.root.message}} } /> ); }