Compare commits

...

5 Commits

7 changed files with 674 additions and 543 deletions

View File

@@ -16,7 +16,6 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import { import {
Drawer, Drawer,
DrawerContent, DrawerContent,
@@ -32,9 +31,11 @@ import { useIsMobile } from "@/hooks/use-mobile";
import { import {
type EventFormValues, type EventFormValues,
getDefaultEventFormValues, getDefaultEventFormValues,
validateEventFormStep,
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";
const STEP_FIELDS: Record<1 | 2 | 3, (keyof EventFormValues)[]> = { const STEP_FIELDS: Record<1 | 2 | 3, (keyof EventFormValues)[]> = {
1: ["title", "url"], 1: ["title", "url"],
@@ -63,7 +64,11 @@ export const EventDialog = ({
}: EventDialogProps) => { }: EventDialogProps) => {
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const isAiDraft = dialogSource === "ai" && !editingId; const isAiDraft = dialogSource === "ai" && !editingId;
const titleText = editingId ? "Edit Event" : isAiDraft ? "Review AI Draft" : "New Event"; const titleText = editingId
? "Edit Event"
: isAiDraft
? "Review AI Draft"
: "New Event";
const descriptionText = editingId const descriptionText = editingId
? "Update the event details below. Title and start date are required." ? "Update the event details below. Title and start date are required."
: isAiDraft : isAiDraft
@@ -72,13 +77,14 @@ export const EventDialog = ({
const saveLabel = editingId ? "Update Event" : "Save Event"; const saveLabel = editingId ? "Update Event" : "Save Event";
const { const {
clearErrors,
control, control,
getValues,
handleSubmit, handleSubmit,
register, register,
reset, reset,
setError, setError,
setValue, setValue,
trigger,
watch, watch,
formState: { errors }, formState: { errors },
} = useForm<EventFormValues>({ } = useForm<EventFormValues>({
@@ -102,9 +108,23 @@ export const EventDialog = ({
onOpenChange(nextOpen); onOpenChange(nextOpen);
}; };
const handleNext = async () => { const handleNext = () => {
const valid = await trigger(STEP_FIELDS[step]); const stepFields = STEP_FIELDS[step];
if (valid) advanceStep(); clearErrors(stepFields);
const stepValidation = validateEventFormStep(getValues(), stepFields);
if (stepValidation.success) {
advanceStep();
return;
}
for (const [fieldName, messages] of Object.entries(
stepValidation.fieldErrors,
)) {
const firstMessage = messages?.[0];
if (firstMessage) {
setError(fieldName as keyof EventFormValues, { message: firstMessage });
}
}
}; };
const handleSave = handleSubmit((values) => { const handleSave = handleSubmit((values) => {
@@ -115,12 +135,21 @@ export const EventDialog = ({
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, { message: firstMessage }); setError(fieldName as keyof EventFormValues, {
message: firstMessage,
});
const ownerStep = ( const ownerStep = (
Object.entries(STEP_FIELDS) as [string, (keyof EventFormValues)[]][] Object.entries(STEP_FIELDS) as [string, (keyof EventFormValues)[]][]
).find(([, fields]) => fields.includes(fieldName as keyof EventFormValues))?.[0]; ).find(([, fields]) =>
const ownerStepNum = ownerStep ? (Number(ownerStep) as 1 | 2 | 3) : null; fields.includes(fieldName as keyof EventFormValues),
if (ownerStepNum !== null && (firstErrorStep === null || ownerStepNum < firstErrorStep)) { )?.[0];
const ownerStepNum = ownerStep
? (Number(ownerStep) as 1 | 2 | 3)
: null;
if (
ownerStepNum !== null &&
(firstErrorStep === null || ownerStepNum < firstErrorStep)
) {
firstErrorStep = ownerStepNum; firstErrorStep = ownerStepNum;
} }
} }
@@ -130,7 +159,9 @@ export const EventDialog = ({
} }
if (values.recurrenceRule) { if (values.recurrenceRule) {
const recurrenceValidation = validateRecurrence(parseRecurrenceRule(values.recurrenceRule)); const recurrenceValidation = validateRecurrence(
parseRecurrenceRule(values.recurrenceRule),
);
if (!recurrenceValidation.isValid) { if (!recurrenceValidation.isValid) {
setError("recurrenceRule", { setError("recurrenceRule", {
message: message:
@@ -145,6 +176,7 @@ export const EventDialog = ({
} }
onSave(result.data); onSave(result.data);
setStep(1);
reset(getDefaultEventFormValues()); reset(getDefaultEventFormValues());
}); });
@@ -155,25 +187,37 @@ export const EventDialog = ({
<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]">{titleText}</DialogTitle> <DialogTitle className="text-[28px] tracking-[-0.06em]">
{titleText}
</DialogTitle>
<DialogDescription>{descriptionText}</DialogDescription> <DialogDescription>{descriptionText}</DialogDescription>
</DialogHeader> </DialogHeader>
<form className="grid gap-6 px-6 py-5" onSubmit={handleSave}> <form className="grid gap-6 px-6 py-5" onSubmit={handleSave}>
{isAiDraft && <AiDraftBanner />} {isAiDraft && <AiDraftBanner />}
<section className="grid gap-3"> <section className="grid gap-3">
<p className="font-mono text-[11px] uppercase text-muted-foreground">Event details</p> <p className="font-mono text-[11px] uppercase text-muted-foreground">
Event details
</p>
<DetailsStep {...stepProps} isAiDraft={false} /> <DetailsStep {...stepProps} isAiDraft={false} />
</section> </section>
<section className="grid gap-3"> <section className="grid gap-3">
<p className="font-mono text-[11px] uppercase text-muted-foreground">Schedule</p> <p className="font-mono text-[11px] uppercase text-muted-foreground">
Schedule
</p>
<ScheduleStep {...stepProps} isAiDraft={false} /> <ScheduleStep {...stepProps} isAiDraft={false} />
</section> </section>
<section className="grid gap-3"> <section className="grid gap-3">
<p className="font-mono text-[11px] uppercase text-muted-foreground">Recurrence</p> <p className="font-mono text-[11px] uppercase text-muted-foreground">
Recurrence
</p>
<RecurrenceStep {...stepProps} isAiDraft={false} /> <RecurrenceStep {...stepProps} isAiDraft={false} />
</section> </section>
<DialogFooter> <DialogFooter>
<Button type="button" variant="ghost" onClick={() => handleOpenChange(false)}> <Button
type="button"
variant="ghost"
onClick={() => handleOpenChange(false)}
>
Cancel Cancel
</Button> </Button>
<Button type="submit">{saveLabel}</Button> <Button type="submit">{saveLabel}</Button>
@@ -263,8 +307,8 @@ interface StepProps {
function AiDraftBanner() { function AiDraftBanner() {
return ( return (
<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 dates, times, location, This draft was generated from natural language. Double-check dates, times,
recurrence, and links before saving. location, recurrence, and links before saving.
</div> </div>
); );
} }
@@ -287,7 +331,9 @@ function DetailsStep({
className="font-medium" className="font-medium"
{...register("title")} {...register("title")}
/> />
{errors.title && <p className="text-xs text-destructive">{errors.title.message}</p>} {errors.title && (
<p className="text-xs text-destructive">{errors.title.message}</p>
)}
</div> </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>
@@ -298,7 +344,11 @@ function DetailsStep({
{...register("description")} {...register("description")}
/> />
</div> </div>
<div className={isMobile ? "grid grid-cols-1 gap-3" : "grid grid-cols-2 gap-3"}> <div
className={
isMobile ? "grid grid-cols-1 gap-3" : "grid grid-cols-2 gap-3"
}
>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label htmlFor="event-location">Location</Label> <Label htmlFor="event-location">Location</Label>
<Controller <Controller
@@ -316,7 +366,9 @@ function DetailsStep({
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label htmlFor="event-url">URL</Label> <Label htmlFor="event-url">URL</Label>
<Input id="event-url" placeholder="URL" {...register("url")} /> <Input id="event-url" placeholder="URL" {...register("url")} />
{errors.url && <p className="text-xs text-destructive">{errors.url.message}</p>} {errors.url && (
<p className="text-xs text-destructive">{errors.url.message}</p>
)}
</div> </div>
</div> </div>
</div> </div>
@@ -344,7 +396,8 @@ function ScheduleStep({
if (!start) return; if (!start) return;
const base = parseISO(start); const base = parseISO(start);
if (!isValid(base)) return; if (!isValid(base)) return;
const next = minutes < 60 ? addMinutes(base, minutes) : addHours(base, minutes / 60); const next =
minutes < 60 ? addMinutes(base, minutes) : addHours(base, minutes / 60);
const pad = (v: number) => String(v).padStart(2, "0"); const pad = (v: number) => String(v).padStart(2, "0");
const result = allDay const result = allDay
? `${next.getFullYear()}-${pad(next.getMonth() + 1)}-${pad(next.getDate())}` ? `${next.getFullYear()}-${pad(next.getMonth() + 1)}-${pad(next.getDate())}`
@@ -367,7 +420,10 @@ function ScheduleStep({
/> />
)} )}
/> />
<Label htmlFor="event-all-day" className="cursor-pointer text-sm font-normal"> <Label
htmlFor="event-all-day"
className="cursor-pointer text-sm font-normal"
>
All day All day
</Label> </Label>
</div> </div>
@@ -413,8 +469,12 @@ function ScheduleStep({
/> />
)} )}
/> />
{errors.start && <p className="text-xs text-destructive">{errors.start.message}</p>} {errors.start && (
{errors.end && <p className="text-xs text-destructive">{errors.end.message}</p>} <p className="text-xs text-destructive">{errors.start.message}</p>
)}
{errors.end && (
<p className="text-xs text-destructive">{errors.end.message}</p>
)}
</div> </div>
</div> </div>
); );
@@ -434,11 +494,17 @@ function RecurrenceStep({
name="recurrenceRule" name="recurrenceRule"
control={control} control={control}
render={({ field }) => ( render={({ field }) => (
<RecurrencePicker value={field.value} onChange={field.onChange} start={start} /> <RecurrencePicker
value={field.value}
onChange={field.onChange}
start={start}
/>
)} )}
/> />
{errors.recurrenceRule && ( {errors.recurrenceRule && (
<p className="text-xs text-destructive">{errors.recurrenceRule.message}</p> <p className="text-xs text-destructive">
{errors.recurrenceRule.message}
</p>
)} )}
</div> </div>
); );

View File

@@ -4,7 +4,6 @@ import * as DialogPrimitive from "@radix-ui/react-dialog";
import { XIcon } from "lucide-react"; import { XIcon } from "lucide-react";
import type * as React from "react"; import type * as React from "react";
import { useIsMobile } from "@/hooks/use-mobile";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
function Dialog({ function Dialog({
@@ -55,16 +54,13 @@ function DialogContent({
}: React.ComponentProps<typeof DialogPrimitive.Content> & { }: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean; showCloseButton?: boolean;
}) { }) {
const isMobile = useIsMobile();
return ( return (
<DialogPortal data-slot="dialog-portal"> <DialogPortal data-slot="dialog-portal">
<DialogOverlay /> <DialogOverlay />
<DialogPrimitive.Content <DialogPrimitive.Content
data-slot="dialog-content" data-slot="dialog-content"
className={cn( className={cn(
"bg-card text-card-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-5 rounded-[10px] p-6 shadow-xl duration-200", "bg-card text-card-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-5 rounded-[10px] p-6 shadow-xl duration-200 max-w-lg",
isMobile ? undefined : "max-w-lg",
className, className,
)} )}
{...props} {...props}
@@ -95,17 +91,10 @@ function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
} }
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) { function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
const isMobile = useIsMobile();
return ( return (
<div <div
data-slot="dialog-footer" data-slot="dialog-footer"
className={cn( className={cn("flex flex-row justify-end gap-2", className)}
isMobile
? "flex flex-col-reverse gap-2"
: "flex flex-row justify-end gap-2",
className,
)}
{...props} {...props}
/> />
); );

View File

@@ -5,19 +5,27 @@ import { Drawer as DrawerPrimitive } from "vaul";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
function Drawer({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Root>) { function Drawer({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
return <DrawerPrimitive.Root data-slot="drawer" {...props} />; return <DrawerPrimitive.Root data-slot="drawer" {...props} />;
} }
function DrawerTrigger({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Trigger>) { function DrawerTrigger({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />; return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />;
} }
function DrawerPortal({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Portal>) { function DrawerPortal({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />; return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />;
} }
function DrawerClose({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Close>) { function DrawerClose({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />; return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />;
} }
@@ -90,7 +98,10 @@ function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
); );
} }
function DrawerTitle({ className, ...props }: React.ComponentProps<typeof DrawerPrimitive.Title>) { function DrawerTitle({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
return ( return (
<DrawerPrimitive.Title <DrawerPrimitive.Title
data-slot="drawer-title" data-slot="drawer-title"

View File

@@ -110,3 +110,27 @@ export const getEventValidationIssues = (
export const validateEventFormValues = (values: EventFormValues) => export const validateEventFormValues = (values: EventFormValues) =>
eventFormSchema.safeParse(values); eventFormSchema.safeParse(values);
export const validateEventFormStep = (
values: EventFormValues,
fields: Array<keyof EventFormValues>,
) => {
const result = validateEventFormValues(values);
if (result.success) {
return { success: true as const, fieldErrors: {} };
}
const allFieldErrors = result.error.flatten().fieldErrors;
const fieldErrors: Partial<Record<keyof EventFormValues, string[]>> = {};
for (const field of fields) {
const messages = allFieldErrors[field];
if (messages?.length) {
fieldErrors[field] = messages;
}
}
return {
success: Object.keys(fieldErrors).length === 0,
fieldErrors,
};
};

View File

@@ -77,6 +77,20 @@ describe("EventDialog public modes", () => {
expect(source).toContain("setStep(1)"); expect(source).toContain("setStep(1)");
}); });
test("event-dialog resets step to 1 after successful save", () => {
const source = readFileSync("src/components/event-dialog.tsx", "utf8");
expect(source).toMatch(/onSave\(result\.data\);\s*setStep\(1\);\s*reset/);
});
test("event-dialog validates mobile drawer steps with schema-backed step validation", () => {
const source = readFileSync("src/components/event-dialog.tsx", "utf8");
expect(source).toContain("validateEventFormStep");
expect(source).toContain("getValues()");
expect(source).toContain("fieldErrors");
});
test("dialog.tsx no longer forks on isMobile in DialogContent", () => { test("dialog.tsx no longer forks on isMobile in DialogContent", () => {
const source = readFileSync("src/components/ui/dialog.tsx", "utf8"); const source = readFileSync("src/components/ui/dialog.tsx", "utf8");

View File

@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";
import { import {
getDefaultEventFormValues, getDefaultEventFormValues,
getEventFormValuesFromEvent, getEventFormValuesFromEvent,
validateEventFormStep,
validateEventFormValues, validateEventFormValues,
} from "@/lib/event-form"; } from "@/lib/event-form";
@@ -70,4 +71,31 @@ describe("event form defaults and validation", () => {
expect(result.error.flatten().fieldErrors.url?.[0]).toContain("valid URL"); expect(result.error.flatten().fieldErrors.url?.[0]).toContain("valid URL");
} }
}); });
test("validates only the requested mobile drawer step", () => {
const values = {
...getDefaultEventFormValues(),
url: "not-a-url",
end: "2026-04-09T09:30:00.000Z",
};
const detailsResult = validateEventFormStep(values, ["title", "url"]);
const scheduleResult = validateEventFormStep(values, ["start", "end"]);
expect(detailsResult.success).toBe(false);
if (!detailsResult.success) {
expect(detailsResult.fieldErrors.title?.[0]).toContain("Title is required");
expect(detailsResult.fieldErrors.url?.[0]).toContain("valid URL");
expect(detailsResult.fieldErrors.start).toBeUndefined();
expect(detailsResult.fieldErrors.end).toBeUndefined();
}
expect(scheduleResult.success).toBe(false);
if (!scheduleResult.success) {
expect(scheduleResult.fieldErrors.start?.[0]).toContain("Start date is required");
expect(scheduleResult.fieldErrors.end?.[0]).toContain("valid");
expect(scheduleResult.fieldErrors.title).toBeUndefined();
expect(scheduleResult.fieldErrors.url).toBeUndefined();
}
});
}); });

View File

@@ -26,7 +26,6 @@ const DIRECT_HOOK_FILES = [
"src/components/settings-panel.tsx", "src/components/settings-panel.tsx",
"src/components/ui/calendar.tsx", "src/components/ui/calendar.tsx",
"src/components/ui/date-picker.tsx", "src/components/ui/date-picker.tsx",
"src/components/ui/dialog.tsx",
"src/components/ui/input-group.tsx", "src/components/ui/input-group.tsx",
"src/components/ui/textarea.tsx", "src/components/ui/textarea.tsx",
]; ];