refactor: extract DetailsStep, ScheduleStep, RecurrenceStep into EventDialog

This commit is contained in:
2026-05-24 22:19:27 -04:00
parent cad1e809a8
commit 260b77ee10

View File

@@ -9,344 +9,484 @@ import { RecurrencePicker } from "@/components/recurrence-picker";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox"; import { Checkbox } from "@/components/ui/checkbox";
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
DialogDescription, DialogDescription,
DialogFooter, DialogFooter,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import { useIsMobile } from "@/hooks/use-mobile"; import { useIsMobile } from "@/hooks/use-mobile";
import { import {
type EventFormValues, type EventFormValues,
getDefaultEventFormValues, getDefaultEventFormValues,
validateEventFormValues, validateEventFormValues,
} from "@/lib/event-form"; } from "@/lib/event-form";
import { parseRecurrenceRule, validateRecurrence } from "@/lib/recurrence"; import { parseRecurrenceRule, validateRecurrence } from "@/lib/recurrence";
import { cn } from "@/lib/utils";
interface EventDialogProps { interface EventDialogProps {
open: boolean; open: boolean;
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
editingId: string | null; editingId: string | null;
dialogSource: "manual" | "ai"; dialogSource: "manual" | "ai";
initialValues: EventFormValues; initialValues: EventFormValues;
onSave: (values: EventFormValues) => void; onSave: (values: EventFormValues) => void;
onReset: () => void; onReset: () => void;
} }
export const EventDialog = ({ export const EventDialog = ({
open, open,
onOpenChange, onOpenChange,
editingId, editingId,
dialogSource, dialogSource,
initialValues, initialValues,
onSave, onSave,
onReset, onReset,
}: EventDialogProps) => { }: EventDialogProps) => {
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const isAiDraft = dialogSource === "ai" && !editingId; const isAiDraft = dialogSource === "ai" && !editingId;
const titleText = editingId const titleText = editingId ? "Edit Event" : isAiDraft ? "Review AI Draft" : "New Event";
? "Edit Event" const descriptionText = editingId
: isAiDraft ? "Update the event details below. Title and start date are required."
? "Review AI Draft" : isAiDraft
: "New Event"; ? "AI filled in this event from your prompt. Review each field, then save when it looks right."
const descriptionText = editingId : "Create an event manually. Title and start date are required.";
? "Update the event details below. Title and start date are required." const saveLabel = editingId ? "Update Event" : "Save Event";
: isAiDraft
? "AI filled in this event from your prompt. Review each field, then save when it looks right."
: "Create an event manually. Title and start date are required.";
const saveLabel = editingId ? "Update Event" : "Save Event";
const { const {
control, control,
handleSubmit, handleSubmit,
register, register,
reset, reset,
setError, setError,
setValue, setValue,
watch, watch,
formState: { errors }, formState: { errors },
} = useForm<EventFormValues>({ } = useForm<EventFormValues>({
defaultValues: getDefaultEventFormValues(), defaultValues: getDefaultEventFormValues(),
}); });
useEffect(() => { useEffect(() => {
reset(initialValues); reset(initialValues);
}, [initialValues, reset]); }, [initialValues, reset]);
const allDay = watch("allDay"); const allDay = watch("allDay");
const start = watch("start"); const start = watch("start");
const handleOpenChange = (nextOpen: boolean) => { const handleOpenChange = (nextOpen: boolean) => {
if (!nextOpen) { if (!nextOpen) {
reset(getDefaultEventFormValues()); reset(getDefaultEventFormValues());
onReset(); onReset();
} }
onOpenChange(nextOpen); onOpenChange(nextOpen);
}; };
const DURATIONS = [ const DURATIONS = [
{ label: "+15 min", minutes: 15 }, { label: "+15 min", minutes: 15 },
{ label: "+30 min", minutes: 30 }, { label: "+30 min", minutes: 30 },
{ label: "+1 hour", minutes: 60 }, { label: "+1 hour", minutes: 60 },
{ label: "+3 hours", minutes: 180 }, { label: "+3 hours", minutes: 180 },
]; ];
const handleApplyDuration = ( const handleApplyDuration = (minutes: number, currentAllDay: boolean, currentStart: string) => {
minutes: number, if (!currentStart) return;
currentAllDay: boolean, const base = parseISO(currentStart);
currentStart: string, if (!isValid(base)) return;
) => { const next = minutes < 60 ? addMinutes(base, minutes) : addHours(base, minutes / 60);
if (!currentStart) return; const pad = (value: number) => String(value).padStart(2, "0");
const base = parseISO(currentStart); const result = currentAllDay
if (!isValid(base)) return; ? `${next.getFullYear()}-${pad(next.getMonth() + 1)}-${pad(next.getDate())}`
const next = : `${next.getFullYear()}-${pad(next.getMonth() + 1)}-${pad(next.getDate())}T${pad(next.getHours())}:${pad(next.getMinutes())}:00`;
minutes < 60 ? addMinutes(base, minutes) : addHours(base, minutes / 60); setValue("end", result, { shouldDirty: true });
const pad = (value: number) => String(value).padStart(2, "0"); };
const result = currentAllDay
? `${next.getFullYear()}-${pad(next.getMonth() + 1)}-${pad(next.getDate())}`
: `${next.getFullYear()}-${pad(next.getMonth() + 1)}-${pad(next.getDate())}T${pad(next.getHours())}:${pad(next.getMinutes())}:00`;
setValue("end", result, { shouldDirty: true });
};
const onSubmit = handleSubmit((values) => { const onSubmit = handleSubmit((values) => {
const result = validateEventFormValues(values); const result = validateEventFormValues(values);
if (!result.success) { if (!result.success) {
const fieldErrors = result.error.flatten().fieldErrors; const fieldErrors = result.error.flatten().fieldErrors;
for (const [fieldName, messages] of Object.entries(fieldErrors)) { for (const [fieldName, messages] of Object.entries(fieldErrors)) {
const firstMessage = messages?.[0]; const firstMessage = messages?.[0];
if (firstMessage) { if (firstMessage) {
setError(fieldName as keyof EventFormValues, { setError(fieldName as keyof EventFormValues, {
message: firstMessage, message: firstMessage,
}); });
} }
} }
return; return;
} }
if (values.recurrenceRule) { if (values.recurrenceRule) {
const recurrenceValidation = validateRecurrence( const recurrenceValidation = validateRecurrence(parseRecurrenceRule(values.recurrenceRule));
parseRecurrenceRule(values.recurrenceRule), if (!recurrenceValidation.isValid) {
); setError("recurrenceRule", {
if (!recurrenceValidation.isValid) { message:
setError("recurrenceRule", { recurrenceValidation.errors.rule ||
message: recurrenceValidation.errors.count ||
recurrenceValidation.errors.rule || recurrenceValidation.errors.until ||
recurrenceValidation.errors.count || "Invalid recurrence.",
recurrenceValidation.errors.until || });
"Invalid recurrence.", return;
}); }
return; }
}
}
onSave(result.data); onSave(result.data);
reset(getDefaultEventFormValues()); reset(getDefaultEventFormValues());
}); });
return ( return (
<Dialog open={open} onOpenChange={handleOpenChange}> <Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="max-w-2xl rounded-[10px] bg-card p-0 shadow-xl"> <DialogContent className="max-w-2xl rounded-[10px] bg-card p-0 shadow-xl">
<DialogHeader className="px-6 py-5 shadow-[inset_0_-1px_0_0_var(--color-border)]"> <DialogHeader className="px-6 py-5 shadow-[inset_0_-1px_0_0_var(--color-border)]">
<DialogTitle className="text-[28px] tracking-[-0.06em]"> <DialogTitle className="text-[28px] tracking-[-0.06em]">{titleText}</DialogTitle>
{titleText} <DialogDescription>{descriptionText}</DialogDescription>
</DialogTitle> </DialogHeader>
<DialogDescription>{descriptionText}</DialogDescription>
</DialogHeader>
<form className="grid gap-6 px-6 py-5" onSubmit={onSubmit}> <form className="grid gap-6 px-6 py-5" onSubmit={onSubmit}>
{isAiDraft && ( {isAiDraft && (
<div className="rounded-md border border-primary/20 bg-primary/5 px-3 py-2 text-xs leading-relaxed text-primary"> <div className="rounded-md border border-primary/20 bg-primary/5 px-3 py-2 text-xs leading-relaxed text-primary">
This draft was generated from natural language. Double-check This draft was generated from natural language. Double-check dates, times, location,
dates, times, location, recurrence, and links before saving. recurrence, and links before saving.
</div> </div>
)} )}
<section className="grid gap-3"> <section className="grid gap-3">
<p className="font-mono text-[11px] uppercase text-muted-foreground"> <p className="font-mono text-[11px] uppercase text-muted-foreground">Event details</p>
Event details <div className="space-y-1.5">
</p> <Label htmlFor="event-title">Title</Label>
<div className="space-y-1.5"> <Input
<Label htmlFor="event-title">Title</Label> id="event-title"
<Input placeholder="Event title"
id="event-title" className="font-medium"
placeholder="Event title" {...register("title")}
className="font-medium" />
{...register("title")} {errors.title && <p className="text-xs text-destructive">{errors.title.message}</p>}
/> </div>
{errors.title && (
<p className="text-xs text-destructive">
{errors.title.message}
</p>
)}
</div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label htmlFor="event-description">Description / notes</Label> <Label htmlFor="event-description">Description / notes</Label>
<Textarea <Textarea
id="event-description" id="event-description"
className="field-sizing-content min-h-[60px] max-h-40 resize-none placeholder:text-muted-foreground/50" className="field-sizing-content min-h-[60px] max-h-40 resize-none placeholder:text-muted-foreground/50"
placeholder="Add a description..." placeholder="Add a description..."
{...register("description")} {...register("description")}
/> />
</div> </div>
<div <div className={isMobile ? "grid grid-cols-1 gap-3" : "grid grid-cols-2 gap-3"}>
className={ <div className="space-y-1.5">
isMobile ? "grid grid-cols-1 gap-3" : "grid grid-cols-2 gap-3" <Label htmlFor="event-location">Location</Label>
} <Controller
> name="location"
<div className="space-y-1.5"> control={control}
<Label htmlFor="event-location">Location</Label> render={({ field }) => (
<Controller <LocationAutocomplete
name="location" id="event-location"
control={control} onChange={field.onChange}
render={({ field }) => ( value={field.value}
<LocationAutocomplete />
id="event-location" )}
onChange={field.onChange} />
value={field.value} </div>
/> <div className="space-y-1.5">
)} <Label htmlFor="event-url">URL</Label>
/> <Input id="event-url" placeholder="URL" {...register("url")} />
</div> {errors.url && <p className="text-xs text-destructive">{errors.url.message}</p>}
<div className="space-y-1.5"> </div>
<Label htmlFor="event-url">URL</Label> </div>
<Input id="event-url" placeholder="URL" {...register("url")} /> </section>
{errors.url && (
<p className="text-xs text-destructive">
{errors.url.message}
</p>
)}
</div>
</div>
</section>
<section className="grid gap-3"> <section className="grid gap-3">
<p className="font-mono text-[11px] uppercase text-muted-foreground"> <p className="font-mono text-[11px] uppercase text-muted-foreground">Schedule</p>
Schedule
</p>
<div className="flex items-center gap-2 py-1"> <div className="flex items-center gap-2 py-1">
<Controller <Controller
name="allDay" name="allDay"
control={control} control={control}
render={({ field }) => ( render={({ field }) => (
<Checkbox <Checkbox
id="event-all-day" id="event-all-day"
checked={field.value} checked={field.value}
onCheckedChange={(checked) => onCheckedChange={(checked) => field.onChange(checked === true)}
field.onChange(checked === true) />
} )}
/> />
)} <Label htmlFor="event-all-day" className="cursor-pointer text-sm font-normal">
/> All day
<Label </Label>
htmlFor="event-all-day" </div>
className="cursor-pointer text-sm font-normal"
>
All day
</Label>
</div>
<div className="space-y-2"> <div className="space-y-2">
<Controller <Controller
name="start" name="start"
control={control} control={control}
render={({ field }) => ( render={({ field }) => (
<DateTimePicker <DateTimePicker
value={field.value} value={field.value}
onChange={field.onChange} onChange={field.onChange}
allDay={allDay} allDay={allDay}
placeholder="Start date" placeholder="Start date"
/> />
)} )}
/> />
{!allDay && ( {!allDay && (
<Controller <Controller
name="end" name="end"
control={control} control={control}
render={() => ( render={() => (
<div className="flex gap-1 pl-0.5"> <div className="flex gap-1 pl-0.5">
{DURATIONS.map(({ label, minutes }) => ( {DURATIONS.map(({ label, minutes }) => (
<Button <Button
key={label} key={label}
type="button" type="button"
variant="ghost" variant="ghost"
size="sm" size="sm"
disabled={!start} disabled={!start}
onClick={() => onClick={() => handleApplyDuration(minutes, allDay, start)}
handleApplyDuration(minutes, allDay, start) className="px-2 py-1 text-xs text-muted-foreground"
} >
className="px-2 py-1 text-xs text-muted-foreground" {label}
> </Button>
{label} ))}
</Button> </div>
))} )}
</div> />
)} )}
/> <Controller
)} name="end"
<Controller control={control}
name="end" render={({ field }) => (
control={control} <DateTimePicker
render={({ field }) => ( value={field.value}
<DateTimePicker onChange={field.onChange}
value={field.value} allDay={allDay}
onChange={field.onChange} placeholder="End date"
allDay={allDay} />
placeholder="End date" )}
/> />
)} {errors.start && <p className="text-xs text-destructive">{errors.start.message}</p>}
/> {errors.end && <p className="text-xs text-destructive">{errors.end.message}</p>}
{errors.start && ( </div>
<p className="text-xs text-destructive"> </section>
{errors.start.message}
</p>
)}
{errors.end && (
<p className="text-xs text-destructive">{errors.end.message}</p>
)}
</div>
</section>
<section className="grid gap-3"> <section className="grid gap-3">
<p className="font-mono text-[11px] uppercase text-muted-foreground"> <p className="font-mono text-[11px] uppercase text-muted-foreground">Recurrence</p>
Recurrence <Controller
</p> name="recurrenceRule"
<Controller control={control}
name="recurrenceRule" render={({ field }) => (
control={control} <RecurrencePicker value={field.value} onChange={field.onChange} start={start} />
render={({ field }) => ( )}
<RecurrencePicker />
value={field.value} {errors.recurrenceRule && (
onChange={field.onChange} <p className="text-xs text-destructive">{errors.recurrenceRule.message}</p>
start={start} )}
/> </section>
)}
/>
{errors.recurrenceRule && (
<p className="text-xs text-destructive">
{errors.recurrenceRule.message}
</p>
)}
</section>
<DialogFooter className={isMobile ? "gap-2" : "gap-0"}> <DialogFooter className={isMobile ? "gap-2" : "gap-0"}>
<Button <Button type="button" variant="ghost" onClick={() => handleOpenChange(false)}>
type="button" Cancel
variant="ghost" </Button>
onClick={() => handleOpenChange(false)} <Button type="submit">{saveLabel}</Button>
> </DialogFooter>
Cancel </form>
</Button> </DialogContent>
<Button type="submit">{saveLabel}</Button> </Dialog>
</DialogFooter> );
</form>
</DialogContent>
</Dialog>
);
}; };
interface StepProps {
control: ReturnType<typeof useForm<EventFormValues>>["control"];
register: ReturnType<typeof useForm<EventFormValues>>["register"];
errors: ReturnType<typeof useForm<EventFormValues>>["formState"]["errors"];
watch: ReturnType<typeof useForm<EventFormValues>>["watch"];
setValue: ReturnType<typeof useForm<EventFormValues>>["setValue"];
isAiDraft: boolean;
}
function AiDraftBanner() {
return (
<div className="rounded-md border border-primary/20 bg-primary/5 px-3 py-2 text-xs leading-relaxed text-primary">
This draft was generated from natural language. Double-check dates, times, location,
recurrence, and links before saving.
</div>
);
}
function DetailsStep({
control,
register,
errors,
isAiDraft,
}: Omit<StepProps, "watch" | "setValue">) {
const isMobile = useIsMobile();
return (
<div className="grid gap-4">
{isAiDraft && <AiDraftBanner />}
<div className="space-y-1.5">
<Label htmlFor="event-title">Title</Label>
<Input
id="event-title"
placeholder="Event title"
className="font-medium"
{...register("title")}
/>
{errors.title && <p className="text-xs text-destructive">{errors.title.message}</p>}
</div>
<div className="space-y-1.5">
<Label htmlFor="event-description">Description / notes</Label>
<Textarea
id="event-description"
className="field-sizing-content min-h-[60px] max-h-40 resize-none placeholder:text-muted-foreground/50"
placeholder="Add a description..."
{...register("description")}
/>
</div>
<div className={isMobile ? "grid grid-cols-1 gap-3" : "grid grid-cols-2 gap-3"}>
<div className="space-y-1.5">
<Label htmlFor="event-location">Location</Label>
<Controller
name="location"
control={control}
render={({ field }) => (
<LocationAutocomplete
id="event-location"
onChange={field.onChange}
value={field.value}
/>
)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="event-url">URL</Label>
<Input id="event-url" placeholder="URL" {...register("url")} />
{errors.url && <p className="text-xs text-destructive">{errors.url.message}</p>}
</div>
</div>
</div>
);
}
function ScheduleStep({
control,
errors,
watch,
setValue,
isAiDraft,
}: Omit<StepProps, "register">) {
const allDay = watch("allDay");
const start = watch("start");
const DURATIONS = [
{ label: "+15 min", minutes: 15 },
{ label: "+30 min", minutes: 30 },
{ label: "+1 hour", minutes: 60 },
{ label: "+3 hours", minutes: 180 },
];
const handleApplyDuration = (minutes: number) => {
if (!start) return;
const base = parseISO(start);
if (!isValid(base)) return;
const next = minutes < 60 ? addMinutes(base, minutes) : addHours(base, minutes / 60);
const pad = (v: number) => String(v).padStart(2, "0");
const result = allDay
? `${next.getFullYear()}-${pad(next.getMonth() + 1)}-${pad(next.getDate())}`
: `${next.getFullYear()}-${pad(next.getMonth() + 1)}-${pad(next.getDate())}T${pad(next.getHours())}:${pad(next.getMinutes())}:00`;
setValue("end", result, { shouldDirty: true });
};
return (
<div className="grid gap-4">
{isAiDraft && <AiDraftBanner />}
<div className="flex items-center gap-2 py-1">
<Controller
name="allDay"
control={control}
render={({ field }) => (
<Checkbox
id="event-all-day"
checked={field.value}
onCheckedChange={(checked) => field.onChange(checked === true)}
/>
)}
/>
<Label htmlFor="event-all-day" className="cursor-pointer text-sm font-normal">
All day
</Label>
</div>
<div className="space-y-2">
<Controller
name="start"
control={control}
render={({ field }) => (
<DateTimePicker
value={field.value}
onChange={field.onChange}
allDay={allDay}
placeholder="Start date"
/>
)}
/>
{!allDay && (
<div className="flex gap-1 pl-0.5">
{DURATIONS.map(({ label, minutes }) => (
<Button
key={label}
type="button"
variant="ghost"
size="sm"
disabled={!start}
onClick={() => handleApplyDuration(minutes)}
className="px-2 py-1 text-xs text-muted-foreground"
>
{label}
</Button>
))}
</div>
)}
<Controller
name="end"
control={control}
render={({ field }) => (
<DateTimePicker
value={field.value}
onChange={field.onChange}
allDay={allDay}
placeholder="End date"
/>
)}
/>
{errors.start && <p className="text-xs text-destructive">{errors.start.message}</p>}
{errors.end && <p className="text-xs text-destructive">{errors.end.message}</p>}
</div>
</div>
);
}
function RecurrenceStep({
control,
errors,
watch,
isAiDraft,
}: Omit<StepProps, "register" | "setValue">) {
const start = watch("start");
return (
<div className="grid gap-4">
{isAiDraft && <AiDraftBanner />}
<Controller
name="recurrenceRule"
control={control}
render={({ field }) => (
<RecurrencePicker value={field.value} onChange={field.onChange} start={start} />
)}
/>
{errors.recurrenceRule && (
<p className="text-xs text-destructive">{errors.recurrenceRule.message}</p>
)}
</div>
);
}