Locations added

This commit is contained in:
cdricms
2025-03-10 16:25:12 +01:00
parent 7cb633b4c6
commit 4cf85981eb
32 changed files with 1504 additions and 227 deletions

View File

@@ -0,0 +1,197 @@
"use client";
import * as React from "react";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Trash2, MilestoneIcon, Clock } from "lucide-react";
import { Location } from "@/types/types";
import getOsmEmbedUrl from "@/lib/osmEmbed";
import LocationDialog from "./location-dialog";
import openNavigationApp from "@/lib/openNavigationMap";
import formatLocation from "@/lib/formatLocation";
interface LocationCardProps {
location: Location;
onUpdate?: (location: Location) => void;
onDelete?: (location: Location) => void;
canUpdate?: boolean;
canDelete?: boolean;
}
export const LocationCard: React.FC<LocationCardProps> = ({
location,
onUpdate,
onDelete,
canDelete = false,
canUpdate = false,
}) => {
const [isDialogOpen, setIsDialogOpen] = React.useState(false);
const handleDelete = () => {
onDelete?.(location);
setIsDialogOpen(false);
};
return (
<Card className="w-full max-w-md">
<CardHeader className="flex flex-row justify-between align-middle">
<div>
<CardTitle>{location.street}</CardTitle>
<CardDescription>
{location.city}, {location.postalCode}
</CardDescription>
</div>
<Button
onClick={() => openNavigationApp(formatLocation(location))}
className="m-0"
>
<MilestoneIcon />
</Button>
</CardHeader>
<CardContent className="space-y-4">
{/* OSM Embed Map */}
{location.latitude && location.longitude && (
<div className="h-[200px] w-full rounded-lg border overflow-hidden">
<iframe
width="100%"
height="100%"
src={getOsmEmbedUrl(
location.latitude,
location.longitude,
)}
title="OpenStreetMap Preview"
loading="lazy"
/>
</div>
)}
<div className="flex gap-2 overflow-y-auto">
{location.events?.slice(0, 3).map((event) => (
<div
key={event.id}
className="border rounded-lg p-3 text-sm shadow-sm hover:shadow-md transition-shadow"
>
{/* Event Title */}
<p className="font-semibold truncate">
{event.title || `Event ${event.id}`}
</p>
{/* Event Start Date/Time */}
{event.start && (
<div className="flex items-center gap-1 text-gray-500 dark:text-gray-400 text-xs">
<Clock className="h-3 w-3" />
<span>
{new Date(event.start).toLocaleString(
"fr-FR",
{
month: "short",
day: "numeric",
hour: "numeric",
minute: "numeric",
},
)}
</span>
{event.end && (
<>
<span></span>
<span>
{new Date(
event.end,
).toLocaleString("fr-FR", {
month: "short",
day: "numeric",
hour: "numeric",
minute: "numeric",
})}
</span>
</>
)}
</div>
)}
{/* Full-day Badge */}
{event.fullday && (
<span className="inline-block mt-1 text-xs bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded-full px-2 py-0.5">
Full Day
</span>
)}
</div>
))}
</div>
{/* Action Buttons */}
<div className="flex justify-between">
<LocationDialog
location={location}
onUpdate={canUpdate ? onUpdate : undefined}
onDelete={canDelete ? onDelete : undefined}
/>
{canDelete && (
<Dialog
open={isDialogOpen}
onOpenChange={setIsDialogOpen}
>
<DialogTrigger asChild>
<Button
variant="destructive"
className="flex items-center gap-2"
>
<Trash2 className="h-4 w-4" />
Supprimer
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>
Confirmation de suppression
</DialogTitle>
<DialogDescription>
Cela supprimera définitivement cette
adresse:{" "}
<span className="font-semibold">
{location.street}
</span>
, {location.city}, {location.postalCode}
?
<br />
Êtes-vous sûr de vouloir continuer ?
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
variant="outline"
onClick={() => setIsDialogOpen(false)}
>
Annuler
</Button>
<Button
variant="destructive"
onClick={handleDelete}
>
Supprimer
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)}
</div>
</CardContent>
</Card>
);
};

View File

@@ -0,0 +1,79 @@
import { DialogProps } from "@radix-ui/react-dialog";
import { LocationForm, LocationFormValues } from "./location-form";
import { useState } from "react";
import { UseFormReturn } from "react-hook-form";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "../ui/dialog";
import { Button } from "../ui/button";
import { Location } from "@/types/types";
const LocationDialog: React.FC<
{
onDelete?: (location: Location) => void;
onUpdate?: (formValues: LocationFormValues) => void;
onAdd?: (formValues: LocationFormValues) => void;
location?: Location;
} & DialogProps
> = ({ open, onOpenChange, onDelete, onUpdate, onAdd, location }) => {
const [form, setForm] = useState<UseFormReturn<LocationFormValues>>();
const submitForm = (event: "add" | "update") => {
const callback = event === "add" ? onAdd : onUpdate;
if (callback) form?.handleSubmit(callback)();
};
if (!(onAdd || onUpdate)) return;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogTrigger asChild>
<Button>
{!location
? "Ajouter une nouvelle adresse"
: "Modifier l'adresse"}
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>
{!location ? "Nouvelle adresse" : "Modifier"}
</DialogTitle>
</DialogHeader>
<LocationForm location={location} setForm={setForm} />
<DialogFooter className="flex flex-row justify-end">
{onUpdate && (
<Button
variant="outline"
onClick={() => submitForm("update")}
type="submit"
>
Actualiser
</Button>
)}
{onDelete && (
<Button
variant="destructive"
onClick={() => location && onDelete(location)}
type="submit"
>
Supprimer
</Button>
)}
{onAdd && !onUpdate && !onDelete && (
<Button onClick={() => submitForm("add")} type="submit">
Ajouter
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
);
};
export default LocationDialog;

View File

@@ -0,0 +1,252 @@
"use client";
import * as React from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import useDebounce from "@/hooks/use-debounce";
import { OpenStreetMapLocation } from "@/types/types";
import getOsmEmbedUrl from "@/lib/osmEmbed";
import { Location } from "@/types/types";
// Zod schema for validation
const locationFormSchema = z.object({
id: z.number().optional(),
street: z.string().min(1, "Street is required"),
city: z.string().min(1, "City is required"),
postalCode: z.string().min(1, "Postal code is required"),
latitude: z.number().optional(),
longitude: z.number().optional(),
});
export type LocationFormValues = z.infer<typeof locationFormSchema>;
export const LocationForm: React.FC<{
location?: Location;
setForm: React.Dispatch<
React.SetStateAction<
ReturnType<typeof useForm<LocationFormValues>> | undefined
>
>;
}> = ({ location, setForm }) => {
const [osmQuery, setOsmQuery] = React.useState("");
const [suggestions, setSuggestions] = React.useState<
OpenStreetMapLocation[]
>([]);
const [isLoading, setIsLoading] = React.useState(false);
const form = useForm<LocationFormValues>({
resolver: zodResolver(locationFormSchema),
defaultValues: location || {
street: "",
city: "",
postalCode: "",
},
});
React.useEffect(() => {
setForm(form);
}, [form, setForm]);
// Fetch suggestions from OpenStreetMap Nominatim API
const fetchSuggestions = async (query: string) => {
if (!query || query.length < 3) {
setSuggestions([]);
return;
}
setIsLoading(true);
try {
const url = new URL("https://nominatim.openstreetmap.org/search");
url.searchParams.append("q", query);
url.searchParams.append("format", "json");
url.searchParams.append("addressdetails", "1");
url.searchParams.append("limit", "5");
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: OpenStreetMapLocation[] = await response.json();
setSuggestions(data);
} catch (error) {
console.error("Error fetching OSM suggestions:", error);
setSuggestions([]);
} finally {
setIsLoading(false);
}
};
const debouncedFetchSuggestions = useDebounce(fetchSuggestions, 300);
// Handle form submission
const onSubmit = (data: LocationFormValues) => {
console.log("New Location:", data);
// Here you can send the data to your backend (e.g., via API call)
};
const longitude = form.watch("longitude");
const latitude = form.watch("latitude");
// Helper function to construct street from OSM address
const getStreetFromAddress = (
address: OpenStreetMapLocation["address"],
): string => {
const houseNumber = address.house_number || "";
const road = address.road || "";
return (
[houseNumber, road].filter(Boolean).join(" ").trim() ||
"Unknown Street"
);
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
{/* Autocomplete Input */}
<Command className="rounded-lg border shadow-md h-40">
<CommandInput
placeholder="Écrivez pour trouver une adresse..."
value={osmQuery}
onValueChange={(value) => {
setOsmQuery(value);
debouncedFetchSuggestions(value);
}}
/>
<CommandList>
{isLoading && <CommandEmpty>Loading...</CommandEmpty>}
{!isLoading &&
suggestions.length === 0 &&
osmQuery.length < 1 && (
<CommandEmpty>No results found.</CommandEmpty>
)}
{!isLoading && suggestions.length > 0 && (
<CommandGroup heading="Suggestions">
{suggestions.map((suggestion) => (
<CommandItem
key={suggestion.place_id}
onSelect={() => {
const address = suggestion.address;
form.setValue(
"street",
getStreetFromAddress(address),
);
form.setValue(
"city",
address.city ||
address.town ||
address.village ||
"",
);
form.setValue(
"postalCode",
address.postcode || "",
);
form.setValue(
"latitude",
parseFloat(suggestion.lat),
);
form.setValue(
"longitude",
parseFloat(suggestion.lon),
);
}}
>
{suggestion.display_name}
</CommandItem>
))}
</CommandGroup>
)}
</CommandList>
</Command>
{/* Editable Fields */}
<FormField
control={form.control}
name="street"
render={({ field }) => (
<FormItem>
<FormLabel>Rue</FormLabel>
<FormControl>
<Input
placeholder="Entrer une rue"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="city"
render={({ field }) => (
<FormItem>
<FormLabel>Ville</FormLabel>
<FormControl>
<Input
placeholder="Entrer une ville"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="postalCode"
render={({ field }) => (
<FormItem>
<FormLabel>Code postal</FormLabel>
<FormControl>
<Input
placeholder="Entrer un code postal"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* OSM Embed Map Preview */}
{latitude && longitude && (
<div className="mt-6">
<h3 className="text-lg font-semibold mb-2">
Prévisualisation
</h3>
<div className="h-[300px] w-full rounded-lg border overflow-hidden">
<iframe
width="100%"
height="100%"
src={getOsmEmbedUrl(latitude, longitude)}
title="OpenStreetMap Preview"
/>
</div>
</div>
)}
</form>
</Form>
);
};