Compare commits

...

5 Commits

7 changed files with 674 additions and 543 deletions

View File

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

View File

@@ -4,7 +4,6 @@ import * as DialogPrimitive from "@radix-ui/react-dialog";
import { XIcon } from "lucide-react";
import type * as React from "react";
import { useIsMobile } from "@/hooks/use-mobile";
import { cn } from "@/lib/utils";
function Dialog({
@@ -55,16 +54,13 @@ function DialogContent({
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean;
}) {
const isMobile = useIsMobile();
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
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",
isMobile ? undefined : "max-w-lg",
"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",
className,
)}
{...props}
@@ -95,17 +91,10 @@ function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
const isMobile = useIsMobile();
return (
<div
data-slot="dialog-footer"
className={cn(
isMobile
? "flex flex-col-reverse gap-2"
: "flex flex-row justify-end gap-2",
className,
)}
className={cn("flex flex-row justify-end gap-2", className)}
{...props}
/>
);

View File

@@ -5,19 +5,27 @@ import { Drawer as DrawerPrimitive } from "vaul";
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} />;
}
function DrawerTrigger({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
function DrawerTrigger({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
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} />;
}
function DrawerClose({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Close>) {
function DrawerClose({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
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 (
<DrawerPrimitive.Title
data-slot="drawer-title"

View File

@@ -110,3 +110,27 @@ export const getEventValidationIssues = (
export const validateEventFormValues = (values: EventFormValues) =>
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)");
});
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", () => {
const source = readFileSync("src/components/ui/dialog.tsx", "utf8");

View File

@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";
import {
getDefaultEventFormValues,
getEventFormValuesFromEvent,
validateEventFormStep,
validateEventFormValues,
} from "@/lib/event-form";
@@ -70,4 +71,31 @@ describe("event form defaults and validation", () => {
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/ui/calendar.tsx",
"src/components/ui/date-picker.tsx",
"src/components/ui/dialog.tsx",
"src/components/ui/input-group.tsx",
"src/components/ui/textarea.tsx",
];