Compare commits

...

6 Commits

9 changed files with 742 additions and 597 deletions

View File

@@ -9,437 +9,503 @@ import { RecurrencePicker } from "@/components/recurrence-picker";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
Drawer,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
} from "@/components/ui/drawer";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useIsMobile } from "@/hooks/use-mobile";
import {
type EventFormValues,
getDefaultEventFormValues,
validateEventFormValues,
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"],
2: ["start", "end"],
3: ["recurrenceRule"],
1: ["title", "url"],
2: ["start", "end"],
3: ["recurrenceRule"],
};
interface EventDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
editingId: string | null;
dialogSource: "manual" | "ai";
initialValues: EventFormValues;
onSave: (values: EventFormValues) => void;
onReset: () => void;
open: boolean;
onOpenChange: (open: boolean) => void;
editingId: string | null;
dialogSource: "manual" | "ai";
initialValues: EventFormValues;
onSave: (values: EventFormValues) => void;
onReset: () => void;
}
export const EventDialog = ({
open,
onOpenChange,
editingId,
dialogSource,
initialValues,
onSave,
onReset,
open,
onOpenChange,
editingId,
dialogSource,
initialValues,
onSave,
onReset,
}: EventDialogProps) => {
const isMobile = useIsMobile();
const isAiDraft = dialogSource === "ai" && !editingId;
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
? "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 isMobile = useIsMobile();
const isAiDraft = dialogSource === "ai" && !editingId;
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
? "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 {
control,
handleSubmit,
register,
reset,
setError,
setValue,
trigger,
watch,
formState: { errors },
} = useForm<EventFormValues>({
defaultValues: getDefaultEventFormValues(),
});
const {
clearErrors,
control,
getValues,
handleSubmit,
register,
reset,
setError,
setValue,
watch,
formState: { errors },
} = useForm<EventFormValues>({
defaultValues: getDefaultEventFormValues(),
});
const [step, setStep] = useState<1 | 2 | 3>(1);
const advanceStep = () => setStep((s) => Math.min(s + 1, 3) as 1 | 2 | 3);
const retreatStep = () => setStep((s) => Math.max(s - 1, 1) as 1 | 2 | 3);
const [step, setStep] = useState<1 | 2 | 3>(1);
const advanceStep = () => setStep((s) => Math.min(s + 1, 3) as 1 | 2 | 3);
const retreatStep = () => setStep((s) => Math.max(s - 1, 1) as 1 | 2 | 3);
useEffect(() => {
reset(initialValues);
}, [initialValues, reset]);
useEffect(() => {
reset(initialValues);
}, [initialValues, reset]);
const handleOpenChange = (nextOpen: boolean) => {
if (!nextOpen) {
reset(getDefaultEventFormValues());
setStep(1);
onReset();
}
onOpenChange(nextOpen);
};
const handleOpenChange = (nextOpen: boolean) => {
if (!nextOpen) {
reset(getDefaultEventFormValues());
setStep(1);
onReset();
}
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;
}
const handleSave = handleSubmit((values) => {
const result = validateEventFormValues(values);
if (!result.success) {
const fieldErrors = result.error.flatten().fieldErrors;
let firstErrorStep: 1 | 2 | 3 | null = null;
for (const [fieldName, messages] of Object.entries(fieldErrors)) {
const firstMessage = messages?.[0];
if (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)) {
firstErrorStep = ownerStepNum;
}
}
}
if (firstErrorStep !== null) setStep(firstErrorStep);
return;
}
for (const [fieldName, messages] of Object.entries(
stepValidation.fieldErrors,
)) {
const firstMessage = messages?.[0];
if (firstMessage) {
setError(fieldName as keyof EventFormValues, { message: firstMessage });
}
}
};
if (values.recurrenceRule) {
const recurrenceValidation = validateRecurrence(parseRecurrenceRule(values.recurrenceRule));
if (!recurrenceValidation.isValid) {
setError("recurrenceRule", {
message:
recurrenceValidation.errors.rule ||
recurrenceValidation.errors.count ||
recurrenceValidation.errors.until ||
"Invalid recurrence.",
});
setStep(3);
return;
}
}
const handleSave = handleSubmit((values) => {
const result = validateEventFormValues(values);
if (!result.success) {
const fieldErrors = result.error.flatten().fieldErrors;
let firstErrorStep: 1 | 2 | 3 | null = null;
for (const [fieldName, messages] of Object.entries(fieldErrors)) {
const firstMessage = messages?.[0];
if (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)
) {
firstErrorStep = ownerStepNum;
}
}
}
if (firstErrorStep !== null) setStep(firstErrorStep);
return;
}
onSave(result.data);
reset(getDefaultEventFormValues());
});
if (values.recurrenceRule) {
const recurrenceValidation = validateRecurrence(
parseRecurrenceRule(values.recurrenceRule),
);
if (!recurrenceValidation.isValid) {
setError("recurrenceRule", {
message:
recurrenceValidation.errors.rule ||
recurrenceValidation.errors.count ||
recurrenceValidation.errors.until ||
"Invalid recurrence.",
});
setStep(3);
return;
}
}
const stepProps = { control, register, errors, watch, setValue, isAiDraft };
onSave(result.data);
setStep(1);
reset(getDefaultEventFormValues());
});
if (!isMobile) {
return (
<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>
<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>
<DetailsStep {...stepProps} isAiDraft={false} />
</section>
<section className="grid gap-3">
<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>
<RecurrenceStep {...stepProps} isAiDraft={false} />
</section>
<DialogFooter>
<Button type="button" variant="ghost" onClick={() => handleOpenChange(false)}>
Cancel
</Button>
<Button type="submit">{saveLabel}</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
const stepProps = { control, register, errors, watch, setValue, isAiDraft };
const progressBars = (
<div className="grid grid-cols-3 gap-1.5 px-4 pt-2 pb-3">
{([1, 2, 3] as const).map((n) => (
<div
key={n}
className={cn(
"h-[3px] rounded-full transition-colors duration-200",
n <= step ? "bg-foreground" : "bg-muted",
)}
/>
))}
</div>
);
if (!isMobile) {
return (
<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>
<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>
<DetailsStep {...stepProps} isAiDraft={false} />
</section>
<section className="grid gap-3">
<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>
<RecurrenceStep {...stepProps} isAiDraft={false} />
</section>
<DialogFooter>
<Button
type="button"
variant="ghost"
onClick={() => handleOpenChange(false)}
>
Cancel
</Button>
<Button type="submit">{saveLabel}</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
const stepTitles: Record<1 | 2 | 3, string> = {
1: "Event Details",
2: "Schedule",
3: "Recurrence",
};
const progressBars = (
<div className="grid grid-cols-3 gap-1.5 px-4 pt-2 pb-3">
{([1, 2, 3] as const).map((n) => (
<div
key={n}
className={cn(
"h-[3px] rounded-full transition-colors duration-200",
n <= step ? "bg-foreground" : "bg-muted",
)}
/>
))}
</div>
);
return (
<Drawer open={open} onOpenChange={handleOpenChange}>
<DrawerContent>
<DrawerHeader>
<div className="flex items-start justify-between gap-3">
<div>
<DrawerTitle>{stepTitles[step]}</DrawerTitle>
<DrawerDescription className="mt-1">
{step === 1 && "Title and start date are required."}
{step === 2 && "Set your event's date and time."}
{step === 3 && "Optionally repeat this event."}
</DrawerDescription>
</div>
<span className="shrink-0 rounded-full bg-muted px-2.5 py-1 text-xs text-muted-foreground">
{step} / 3
</span>
</div>
</DrawerHeader>
{progressBars}
<form onSubmit={handleSave}>
<div className="overflow-y-auto px-4 pb-4 max-h-[55dvh]">
{step === 1 && <DetailsStep {...stepProps} />}
{step === 2 && <ScheduleStep {...stepProps} />}
{step === 3 && <RecurrenceStep {...stepProps} />}
</div>
<DrawerFooter>
<Button
type="button"
variant="outline"
onClick={step === 1 ? () => handleOpenChange(false) : retreatStep}
>
{step === 1 ? "Cancel" : "Back"}
</Button>
{step < 3 ? (
<Button type="button" onClick={handleNext}>
Next
</Button>
) : (
<Button type="submit">{saveLabel}</Button>
)}
</DrawerFooter>
</form>
</DrawerContent>
</Drawer>
);
const stepTitles: Record<1 | 2 | 3, string> = {
1: "Event Details",
2: "Schedule",
3: "Recurrence",
};
return (
<Drawer open={open} onOpenChange={handleOpenChange}>
<DrawerContent>
<DrawerHeader>
<div className="flex items-start justify-between gap-3">
<div>
<DrawerTitle>{stepTitles[step]}</DrawerTitle>
<DrawerDescription className="mt-1">
{step === 1 && "Title and start date are required."}
{step === 2 && "Set your event's date and time."}
{step === 3 && "Optionally repeat this event."}
</DrawerDescription>
</div>
<span className="shrink-0 rounded-full bg-muted px-2.5 py-1 text-xs text-muted-foreground">
{step} / 3
</span>
</div>
</DrawerHeader>
{progressBars}
<form onSubmit={handleSave}>
<div className="overflow-y-auto px-4 pb-4 max-h-[55dvh]">
{step === 1 && <DetailsStep {...stepProps} />}
{step === 2 && <ScheduleStep {...stepProps} />}
{step === 3 && <RecurrenceStep {...stepProps} />}
</div>
<DrawerFooter>
<Button
type="button"
variant="outline"
onClick={step === 1 ? () => handleOpenChange(false) : retreatStep}
>
{step === 1 ? "Cancel" : "Back"}
</Button>
{step < 3 ? (
<Button type="button" onClick={handleNext}>
Next
</Button>
) : (
<Button type="submit">{saveLabel}</Button>
)}
</DrawerFooter>
</form>
</DrawerContent>
</Drawer>
);
};
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;
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>
);
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,
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>
);
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,
control,
errors,
watch,
setValue,
isAiDraft,
}: Omit<StepProps, "register">) {
const allDay = watch("allDay");
const start = watch("start");
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 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 });
};
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>
);
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,
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>
);
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>
);
}

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,123 +5,134 @@ import { Drawer as DrawerPrimitive } from "vaul";
import { cn } from "@/lib/utils";
function Drawer({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Root>) {
return <DrawerPrimitive.Root data-slot="drawer" {...props} />;
function Drawer({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
return <DrawerPrimitive.Root data-slot="drawer" {...props} />;
}
function DrawerTrigger({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />;
function DrawerTrigger({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />;
}
function DrawerPortal({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />;
function DrawerPortal({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />;
}
function DrawerClose({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Close>) {
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />;
function DrawerClose({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />;
}
function DrawerOverlay({
className,
...props
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
return (
<DrawerPrimitive.Overlay
data-slot="drawer-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className,
)}
{...props}
/>
);
return (
<DrawerPrimitive.Overlay
data-slot="drawer-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className,
)}
{...props}
/>
);
}
function DrawerContent({
className,
children,
...props
className,
children,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
return (
<DrawerPortal data-slot="drawer-portal">
<DrawerOverlay />
<DrawerPrimitive.Content
data-slot="drawer-content"
className={cn(
"group/drawer-content fixed z-50 flex h-auto flex-col bg-background",
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:max-w-sm",
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:max-w-sm",
className,
)}
{...props}
>
<div className="mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full bg-muted group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
);
return (
<DrawerPortal data-slot="drawer-portal">
<DrawerOverlay />
<DrawerPrimitive.Content
data-slot="drawer-content"
className={cn(
"group/drawer-content fixed z-50 flex h-auto flex-col bg-background",
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:max-w-sm",
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:max-w-sm",
className,
)}
{...props}
>
<div className="mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full bg-muted group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
);
}
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="drawer-header"
className={cn(
"flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center",
className,
)}
{...props}
/>
);
return (
<div
data-slot="drawer-header"
className={cn(
"flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center",
className,
)}
{...props}
/>
);
}
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="drawer-footer"
className={cn(
"sticky bottom-0 grid grid-cols-[0.8fr_1.2fr] gap-3 bg-gradient-to-t from-card via-card/95 to-transparent px-4 pb-6 pt-4",
className,
)}
{...props}
/>
);
return (
<div
data-slot="drawer-footer"
className={cn(
"sticky bottom-0 grid grid-cols-[0.8fr_1.2fr] gap-3 bg-gradient-to-t from-card via-card/95 to-transparent px-4 pb-6 pt-4",
className,
)}
{...props}
/>
);
}
function DrawerTitle({ className, ...props }: React.ComponentProps<typeof DrawerPrimitive.Title>) {
return (
<DrawerPrimitive.Title
data-slot="drawer-title"
className={cn("font-semibold text-foreground", className)}
{...props}
/>
);
function DrawerTitle({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
return (
<DrawerPrimitive.Title
data-slot="drawer-title"
className={cn("font-semibold text-foreground", className)}
{...props}
/>
);
}
function DrawerDescription({
className,
...props
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
return (
<DrawerPrimitive.Description
data-slot="drawer-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
);
return (
<DrawerPrimitive.Description
data-slot="drawer-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
);
}
export {
Drawer,
DrawerClose,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerOverlay,
DrawerPortal,
DrawerTitle,
DrawerTrigger,
Drawer,
DrawerClose,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerOverlay,
DrawerPortal,
DrawerTitle,
DrawerTrigger,
};

View File

@@ -54,9 +54,12 @@ function composeRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {
* A custom hook that composes multiple refs
* Accepts callback refs and RefObject(s)
*/
function useComposedRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {
// biome-ignore lint/correctness/useExhaustiveDependencies: we want to memoize by all values
return React.useCallback(composeRefs(...refs), refs);
function useComposedRefs<T>(
ref1: PossibleRef<T>,
ref2: PossibleRef<T>,
ref3?: PossibleRef<T>,
): React.RefCallback<T> {
return React.useMemo(() => composeRefs(ref1, ref2, ref3), [ref1, ref2, ref3]);
}
export { composeRefs, useComposedRefs };

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

@@ -1,65 +1,76 @@
import { describe, expect, test } from "bun:test";
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
import { EventCard } from "@/components/event-card";
import type { CalendarEvent } from "@/lib/types";
const sampleEvent: CalendarEvent = {
id: "evt_1",
title: "Design Review",
start: "2026-04-09T10:00:00+00:00",
end: "2026-04-09T11:00:00+00:00",
description: "Review the updated event list UI.",
location: "Studio A",
url: "https://example.com/event",
allDay: false,
id: "evt_1",
title: "Design Review",
start: "2026-04-09T10:00:00+00:00",
end: "2026-04-09T11:00:00+00:00",
description: "Review the updated event list UI.",
location: "Studio A",
url: "https://example.com/event",
allDay: false,
};
describe("EventCard actions trigger", () => {
test("shows the triple-dots trigger without requiring hover and exposes an aria-label for the icon-only button", () => {
const markup = renderToStaticMarkup(
EventCard({
event: sampleEvent,
onEdit: () => {},
onDelete: () => {},
}),
);
beforeEach(() => {
globalThis.document = {
addEventListener: () => {},
removeEventListener: () => {},
} as unknown as Document;
});
expect(markup).toContain('aria-label="Event actions"');
expect(markup).not.toContain("opacity-0");
expect(markup).not.toContain("group-hover:opacity-100");
});
afterEach(() => {
delete (globalThis as { document?: Document }).document;
});
test("renders friendly shared date formatting instead of native locale strings", () => {
const markup = renderToStaticMarkup(
EventCard({
event: sampleEvent,
onEdit: () => {},
onDelete: () => {},
}),
);
test("shows the triple-dots trigger without requiring hover and exposes an aria-label for the icon-only button", () => {
const markup = renderToStaticMarkup(
EventCard({
event: sampleEvent,
onEdit: () => {},
onDelete: () => {},
}),
);
expect(markup).toContain("10:0011:00");
expect(markup).not.toContain("AM");
});
expect(markup).toContain('aria-label="Event actions"');
expect(markup).not.toContain("opacity-0");
expect(markup).not.toContain("group-hover:opacity-100");
});
test("renders inline warning copy for invalid event ranges", () => {
const markup = renderToStaticMarkup(
EventCard({
event: {
id: "evt_invalid",
title: "Broken Event",
start: "2026-04-09T11:00:00+00:00",
end: "2026-04-09T10:00:00+00:00",
allDay: false,
},
onEdit: () => {},
onDelete: () => {},
}),
);
test("renders friendly shared date formatting instead of native locale strings", () => {
const markup = renderToStaticMarkup(
EventCard({
event: sampleEvent,
onEdit: () => {},
onDelete: () => {},
}),
);
expect(markup).toContain("Warning:");
expect(markup).toContain("end time is before start time");
expect(markup).not.toContain("Preview");
expect(markup).not.toContain("Ship");
});
expect(markup).toContain("10:0011:00");
expect(markup).not.toContain("AM");
});
test("renders inline warning copy for invalid event ranges", () => {
const markup = renderToStaticMarkup(
EventCard({
event: {
id: "evt_invalid",
title: "Broken Event",
start: "2026-04-09T11:00:00+00:00",
end: "2026-04-09T10:00:00+00:00",
allDay: false,
},
onEdit: () => {},
onDelete: () => {},
}),
);
expect(markup).toContain("Warning:");
expect(markup).toContain("end time is before start time");
expect(markup).not.toContain("Preview");
expect(markup).not.toContain("Ship");
});
});

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

@@ -1,73 +1,101 @@
import { describe, expect, test } from "bun:test";
import {
getDefaultEventFormValues,
getEventFormValuesFromEvent,
validateEventFormValues,
getDefaultEventFormValues,
getEventFormValuesFromEvent,
validateEventFormStep,
validateEventFormValues,
} from "@/lib/event-form";
describe("event form defaults and validation", () => {
test("returns manual-create defaults with blank values", () => {
expect(getDefaultEventFormValues()).toEqual({
title: "",
description: "",
location: "",
url: "",
start: "",
end: "",
allDay: false,
recurrenceRule: undefined,
});
});
test("returns manual-create defaults with blank values", () => {
expect(getDefaultEventFormValues()).toEqual({
title: "",
description: "",
location: "",
url: "",
start: "",
end: "",
allDay: false,
recurrenceRule: undefined,
});
});
test("maps edit and AI-prefilled events into form values", () => {
const values = getEventFormValuesFromEvent({
title: "AI Draft",
location: "Studio A",
start: "2026-04-09T10:00:00.000Z",
recurrenceRule: "FREQ=WEEKLY;INTERVAL=1;BYDAY=TH",
});
test("maps edit and AI-prefilled events into form values", () => {
const values = getEventFormValuesFromEvent({
title: "AI Draft",
location: "Studio A",
start: "2026-04-09T10:00:00.000Z",
recurrenceRule: "FREQ=WEEKLY;INTERVAL=1;BYDAY=TH",
});
expect(values.title).toBe("AI Draft");
expect(values.location).toBe("Studio A");
expect(values.start).toBe("2026-04-09T10:00:00.000Z");
expect(values.recurrenceRule).toBe("FREQ=WEEKLY;INTERVAL=1;BYDAY=TH");
});
expect(values.title).toBe("AI Draft");
expect(values.location).toBe("Studio A");
expect(values.start).toBe("2026-04-09T10:00:00.000Z");
expect(values.recurrenceRule).toBe("FREQ=WEEKLY;INTERVAL=1;BYDAY=TH");
});
test("requires title and start values", () => {
const result = validateEventFormValues(getDefaultEventFormValues());
test("requires title and start values", () => {
const result = validateEventFormValues(getDefaultEventFormValues());
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.flatten().fieldErrors.title?.[0]).toContain("Title is required");
expect(result.error.flatten().fieldErrors.start?.[0]).toContain("Start date is required");
}
});
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.flatten().fieldErrors.title?.[0]).toContain("Title is required");
expect(result.error.flatten().fieldErrors.start?.[0]).toContain("Start date is required");
}
});
test("requires end to be after start when present", () => {
const result = validateEventFormValues({
...getDefaultEventFormValues(),
title: "Planning",
start: "2026-04-09T10:00:00.000Z",
end: "2026-04-09T09:30:00.000Z",
});
test("requires end to be after start when present", () => {
const result = validateEventFormValues({
...getDefaultEventFormValues(),
title: "Planning",
start: "2026-04-09T10:00:00.000Z",
end: "2026-04-09T09:30:00.000Z",
});
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.flatten().fieldErrors.end?.[0]).toContain("after the start date");
}
});
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.flatten().fieldErrors.end?.[0]).toContain("after the start date");
}
});
test("requires an optional URL to be valid when provided", () => {
const result = validateEventFormValues({
...getDefaultEventFormValues(),
title: "Planning",
start: "2026-04-09T10:00:00.000Z",
url: "not-a-url",
});
test("requires an optional URL to be valid when provided", () => {
const result = validateEventFormValues({
...getDefaultEventFormValues(),
title: "Planning",
start: "2026-04-09T10:00:00.000Z",
url: "not-a-url",
});
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.flatten().fieldErrors.url?.[0]).toContain("valid URL");
}
});
expect(result.success).toBe(false);
if (!result.success) {
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",
];