feat: add location autocomplete

This commit is contained in:
2026-04-10 15:40:38 -04:00
parent 12849b2362
commit 27492ee01f
6 changed files with 679 additions and 47 deletions

View File

@@ -3,8 +3,8 @@
import { addHours, addMinutes, isValid, parseISO } from "date-fns";
import { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { LucideMapPin } from "lucide-react";
import { DateTimePicker } from "@/components/date-time-picker";
import { LocationAutocomplete } from "@/components/location-autocomplete";
import { RecurrencePicker } from "@/components/recurrence-picker";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
@@ -19,12 +19,12 @@ import {
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { validateRecurrence, parseRecurrenceRule } from "@/lib/recurrence";
import {
type EventFormValues,
getDefaultEventFormValues,
validateEventFormValues,
type EventFormValues,
} from "@/lib/event-form";
import { parseRecurrenceRule, validateRecurrence } from "@/lib/recurrence";
interface EventDialogProps {
open: boolean;
@@ -46,7 +46,11 @@ export const EventDialog = ({
onReset,
}: EventDialogProps) => {
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
@@ -89,11 +93,16 @@ export const EventDialog = ({
{ label: "+3 hours", minutes: 180 },
];
const handleApplyDuration = (minutes: number, currentAllDay: boolean, currentStart: string) => {
const handleApplyDuration = (
minutes: number,
currentAllDay: boolean,
currentStart: string,
) => {
if (!currentStart) return;
const base = parseISO(currentStart);
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 = (value: number) => String(value).padStart(2, "0");
const result = currentAllDay
? `${next.getFullYear()}-${pad(next.getMonth() + 1)}-${pad(next.getDate())}`
@@ -108,14 +117,18 @@ 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,
});
}
}
return;
}
if (values.recurrenceRule) {
const recurrenceValidation = validateRecurrence(parseRecurrenceRule(values.recurrenceRule));
const recurrenceValidation = validateRecurrence(
parseRecurrenceRule(values.recurrenceRule),
);
if (!recurrenceValidation.isValid) {
setError("recurrenceRule", {
message:
@@ -143,14 +156,22 @@ export const EventDialog = ({
<form className="space-y-3" onSubmit={onSubmit}>
{isAiDraft && (
<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>
)}
<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>}
<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">
@@ -163,18 +184,27 @@ export const EventDialog = ({
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<div className="space-y-1.5">
<Label htmlFor="event-location">Location</Label>
<div className="relative">
<LucideMapPin className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground/50" />
<Input id="event-location" placeholder="Location" className="pl-8" {...register("location")} />
</div>
<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>}
{errors.url && (
<p className="text-xs text-destructive">{errors.url.message}</p>
)}
</div>
</div>
@@ -182,11 +212,17 @@ export const EventDialog = ({
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 className="flex items-center gap-2 py-1">
@@ -197,11 +233,16 @@ export const EventDialog = ({
<Checkbox
id="event-all-day"
checked={field.value}
onCheckedChange={(checked) => field.onChange(checked === true)}
onCheckedChange={(checked) =>
field.onChange(checked === true)
}
/>
)}
/>
<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>
@@ -211,45 +252,65 @@ export const EventDialog = ({
name="start"
control={control}
render={({ field }) => (
<DateTimePicker value={field.value} onChange={field.onChange} allDay={allDay} placeholder="Start date" />
<DateTimePicker
value={field.value}
onChange={field.onChange}
allDay={allDay}
placeholder="Start date"
/>
)}
/>
{!allDay && (
<Controller
name="end"
control={control}
render={() => (
<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, allDay, start)}
className="px-2 py-1 text-xs text-muted-foreground"
>
{label}
</Button>
))}
</div>
)}
/>
<Controller
name="end"
control={control}
render={() => (
<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, allDay, start)
}
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" />
<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>}
{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>
<DialogFooter className="gap-2 sm:gap-0">
<Button type="button" variant="ghost" onClick={() => handleOpenChange(false)}>
<Button
type="button"
variant="ghost"
onClick={() => handleOpenChange(false)}
>
Cancel
</Button>
<Button type="submit">{saveLabel}</Button>

View File

@@ -0,0 +1,222 @@
"use client";
import { LucideMapPin } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { Input } from "@/components/ui/input";
import {
type GoogleMapsLocationCapability,
type GoogleMapsSuggestion,
getGoogleMapsLocationCapability,
getGoogleMapsPlaceLabel,
getLocationAutocompletePlaceholder,
} from "@/lib/google-maps";
import { cn } from "@/lib/utils";
interface LocationAutocompleteProps {
capability?: GoogleMapsLocationCapability;
className?: string;
id: string;
onChange: (value: string) => void;
value: string;
}
const SEARCH_HELP_TEXT = "Search Google Maps or keep typing a custom location.";
const SEARCH_UNAVAILABLE_TEXT =
"Google Maps search is unavailable right now. You can still type a location.";
export const LocationAutocomplete = ({
capability,
className,
id,
onChange,
value,
}: LocationAutocompleteProps) => {
const resolvedCapability = capability ?? getGoogleMapsLocationCapability();
if (!resolvedCapability.enabled) {
return (
<ManualLocationInput
className={className}
id={id}
onChange={onChange}
placeholder={getLocationAutocompletePlaceholder(resolvedCapability)}
value={value}
/>
);
}
return (
<ServerLocationInput
capability={resolvedCapability}
className={className}
id={id}
onChange={onChange}
value={value}
/>
);
};
const ManualLocationInput = ({
className,
id,
onChange,
placeholder,
value,
}: Omit<LocationAutocompleteProps, "capability"> & { placeholder: string }) => {
return (
<div className="space-y-1.5" data-location-mode="manual">
<div className="relative">
<LucideMapPin className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground/50" />
<Input
className={cn("pl-8", className)}
id={id}
onChange={(event) => onChange(event.target.value)}
placeholder={placeholder}
value={value}
/>
</div>
</div>
);
};
const ServerLocationInput = ({
capability,
className,
id,
onChange,
value,
}: Omit<LocationAutocompleteProps, "capability"> & {
capability: GoogleMapsLocationCapability;
}) => {
const [hasSearchError, setHasSearchError] = useState(false);
const [isLoadingSuggestions, setIsLoadingSuggestions] = useState(false);
const [suggestions, setSuggestions] = useState<GoogleMapsSuggestion[]>([]);
const sessionTokenRef = useRef<string | null>(null);
const skipNextLookupRef = useRef(false);
const helperText = useMemo(() => {
return hasSearchError ? SEARCH_UNAVAILABLE_TEXT : SEARCH_HELP_TEXT;
}, [hasSearchError]);
useEffect(() => {
if (skipNextLookupRef.current) {
skipNextLookupRef.current = false;
return;
}
const query = value.trim();
if (!query || hasSearchError) {
setSuggestions([]);
setIsLoadingSuggestions(false);
return;
}
if (!sessionTokenRef.current) {
sessionTokenRef.current = crypto.randomUUID();
}
const controller = new AbortController();
setIsLoadingSuggestions(true);
void fetch(
`/api/location-autocomplete?input=${encodeURIComponent(query)}&sessionToken=${encodeURIComponent(sessionTokenRef.current)}`,
{ signal: controller.signal },
)
.then(async (response) => {
if (!response.ok) {
throw new Error("Autocomplete request failed");
}
return (await response.json()) as {
suggestions?: GoogleMapsSuggestion[];
};
})
.then((payload) => {
setSuggestions(payload.suggestions ?? []);
})
.catch((error) => {
if (controller.signal.aborted) {
return;
}
console.error("Location autocomplete failed", error);
setHasSearchError(true);
setSuggestions([]);
})
.finally(() => {
if (!controller.signal.aborted) {
setIsLoadingSuggestions(false);
}
});
return () => controller.abort();
}, [hasSearchError, value]);
const handleSuggestionSelect = (suggestion: GoogleMapsSuggestion) => {
const nextValue = getGoogleMapsPlaceLabel({
formattedAddress: suggestion.formattedAddress,
name: suggestion.text,
predictionText: suggestion.text,
});
if (!nextValue) {
return;
}
skipNextLookupRef.current = true;
sessionTokenRef.current = null;
setSuggestions([]);
onChange(nextValue);
};
const showSuggestions = suggestions.length > 0 && !hasSearchError;
return (
<div className="space-y-1.5" data-location-mode="google-maps-server">
<div className="relative">
<LucideMapPin className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground/50" />
<Input
aria-autocomplete="list"
aria-expanded={showSuggestions}
className={cn("pl-8", className)}
id={id}
onChange={(event) => {
setHasSearchError(false);
onChange(event.target.value);
}}
placeholder={getLocationAutocompletePlaceholder(capability)}
role="combobox"
value={value}
/>
{showSuggestions ? (
<div className="absolute left-0 right-0 top-[calc(100%+0.375rem)] z-20 rounded-md border border-border/60 bg-background/95 p-1 shadow-lg backdrop-blur-sm">
<div className="space-y-1" role="listbox">
{suggestions.map((suggestion) => {
const suggestionKey =
suggestion.placeId || suggestion.text || "suggestion";
return (
<div key={suggestionKey}>
<button
className="w-full rounded-sm px-3 py-2 text-left text-sm text-foreground transition hover:bg-accent hover:text-accent-foreground"
onClick={() => handleSuggestionSelect(suggestion)}
type="button"
>
{suggestion.text || "Use this place"}
</button>
</div>
);
})}
</div>
</div>
) : null}
</div>
<p className="text-xs text-muted-foreground">{helperText}</p>
{isLoadingSuggestions ? (
<p className="text-xs text-muted-foreground">
Loading place suggestions
</p>
) : null}
</div>
);
};