Repository Public
1// Palette de recherche rapide (⌘K) : villes, gestionnaires, pages.23import { useEffect, useMemo, useRef, useState } from "react";4import { createPortal } from "react-dom";5import { useNavigate } from "react-router";6import { useQuery } from "@tanstack/react-query";7import { AnimatePresence, LayoutGroup, motion } from "motion/react";8import { SlideMark } from "@/lib/motion";9import { ArrowRight, CornerDownLeft, Search } from "lucide-react";10import { IconDoorOpen, IconManagement, IconNeighborhood } from "@/brand/icons";11import { fetchManagers, fetchVilles } from "@/lib/api";12import { cn } from "@/lib/cn";13import { fmtInt, slugify } from "@/lib/format";14import { Kbd } from "@/ui/primitives";1516interface Item {17 key: string;18 icon: React.ComponentType<{ className?: string; size?: number }>;19 title: string;20 meta?: string;21 to: string;22}2324const PAGES: Item[] = [25 { key: "p-carte", icon: IconNeighborhood, title: "Explorer la carte", meta: "Tous les logements", to: "/recherche" },26 { key: "p-deals", icon: IconDoorOpen, title: "Bons prix", meta: "Sous le marché", to: "/recherche?deal=sous" },27 { key: "p-gest", icon: IconManagement, title: "Gestionnaires immobiliers", meta: "Annuaire", to: "/gestionnaires" },28 { key: "p-villes", icon: IconNeighborhood, title: "Toutes les villes", to: "/villes" },29 { key: "p-stats", icon: IconDoorOpen, title: "Marché locatif", meta: "Statistiques", to: "/stats" },30 { key: "p-jv", icon: IconDoorOpen, title: "Comment fonctionne la juste valeur", to: "/juste-valeur" },31 { key: "p-scores", icon: IconDoorOpen, title: "Scores de quartier", to: "/scores" },32 { key: "p-dem", icon: IconManagement, title: "Déménageurs", to: "/demenageurs" },33];3435const norm = (s: string) => slugify(s).replace(/-/g, " ");3637export function CommandPalette({ open, onClose }: { open: boolean; onClose: () => void }) {38 const [q, setQ] = useState("");39 const [idx, setIdx] = useState(0);40 const input = useRef<HTMLInputElement>(null);41 const list = useRef<HTMLDivElement>(null);42 const navigate = useNavigate();4344 const villes = useQuery({ queryKey: ["villes"], queryFn: fetchVilles, enabled: open, staleTime: 6e5 });45 const managers = useQuery({ queryKey: ["managers"], queryFn: fetchManagers, enabled: open, staleTime: 6e5 });4647 useEffect(() => {48 if (!open) return;49 setQ("");50 setIdx(0);51 const t = window.setTimeout(() => input.current?.focus(), 30);52 const overflow = document.body.style.overflow;53 document.body.style.overflow = "hidden";54 return () => {55 window.clearTimeout(t);56 document.body.style.overflow = overflow;57 };58 }, [open]);5960 const groups = useMemo(() => {61 const n = norm(q.trim());62 const cities: Item[] = (villes.data?.villes ?? [])63 .filter((v) => (n ? norm(v.city).includes(n) : true))64 .slice(0, n ? 7 : 6)65 .map((v) => ({66 key: `v-${v.slug}`,67 icon: IconNeighborhood,68 title: v.city,69 meta: `${fmtInt(v.n)} logements${v.avg_price ? ` · ${fmtInt(v.avg_price)} $ en moyenne` : ""}`,70 to: `/ville/${v.slug}`,71 }));72 const mgrs: Item[] = n73 ? (managers.data?.managers ?? [])74 .filter((m) => norm(m.name).includes(n))75 .slice(0, 6)76 .map((m) => ({77 key: `m-${m.id}`,78 icon: IconManagement,79 title: m.name,80 meta: m.active_listings ? `${fmtInt(m.active_listings)} logements à louer` : m.region,81 to: `/g/${m.id}`,82 }))83 : [];84 const pages = PAGES.filter((p) => (n ? norm(p.title + " " + (p.meta ?? "")).includes(n) : true)).slice(0, n ? 4 : 5);85 const free: Item[] = q.trim()86 ? [{ key: "free", icon: Search, title: `Chercher « ${q.trim()} »`, meta: "Titre, adresse, quartier", to: `/recherche?q=${encodeURIComponent(q.trim())}` }]87 : [];88 return [89 { label: "", items: free },90 { label: "Villes", items: cities },91 { label: "Gestionnaires", items: mgrs },92 { label: "Aller à", items: pages },93 ].filter((g) => g.items.length);94 }, [q, villes.data, managers.data]);9596 const flat = useMemo(() => groups.flatMap((g) => g.items), [groups]);97 useEffect(() => setIdx(0), [q]);9899 const go = (item: Item | undefined) => {100 if (!item) return;101 onClose();102 navigate(item.to);103 };104105 const onKey = (e: React.KeyboardEvent) => {106 if (e.key === "ArrowDown" || e.key === "ArrowUp") {107 e.preventDefault();108 const next = (idx + (e.key === "ArrowDown" ? 1 : -1) + flat.length) % Math.max(1, flat.length);109 setIdx(next);110 list.current?.querySelector(`[data-i="${next}"]`)?.scrollIntoView({ block: "nearest" });111 } else if (e.key === "Enter") {112 e.preventDefault();113 go(flat[idx]);114 } else if (e.key === "Escape") {115 onClose();116 }117 };118119 let i = -1;120 return createPortal(121 <AnimatePresence>122 {open && (123 <div className="fixed inset-0 z-[95] flex items-start justify-center px-3 pt-[9vh] sm:pt-[14vh]">124 <motion.div125 className="absolute inset-0 bg-scrim"126 initial={{ opacity: 0 }}127 animate={{ opacity: 1 }}128 exit={{ opacity: 0 }}129 onClick={onClose}130 />131 <motion.div132 role="dialog"133 aria-modal="true"134 aria-label="Recherche rapide"135 initial={{ opacity: 0, y: -6 }}136 animate={{ opacity: 1, y: 0 }}137 exit={{ opacity: 0, y: -4 }}138 transition={{ duration: 0.16, ease: [0.2, 0.7, 0.2, 1] }}139 className="relative w-full max-w-xl overflow-hidden rounded-[14px] border border-line-2 bg-surface shadow-float"140 >141 <div className="flex items-center gap-3 border-b border-line px-5">142 <Search className="size-5 shrink-0 text-ink-3" />143 <input144 ref={input}145 value={q}146 onChange={(e) => setQ(e.target.value)}147 onKeyDown={onKey}148 placeholder="Ville, quartier, gestionnaire, adresse…"149 aria-label="Recherche rapide"150 className="h-15 w-full bg-transparent text-[1.05rem] text-ink outline-none placeholder:text-ink-3"151 />152 <Kbd>Échap</Kbd>153 </div>154 <LayoutGroup id="palette">155 <div ref={list} className="max-h-[56vh] overflow-y-auto overscroll-contain p-2">156 {groups.map((g) => (157 <div key={g.label || "free"} className="mb-1">158 {g.label && <div className="eyebrow px-3 pb-1.5 pt-3">{g.label}</div>}159 {g.items.map((item) => {160 i += 1;161 const me = i;162 const Icon = item.icon;163 return (164 <button165 key={item.key}166 type="button"167 data-i={me}168 onMouseEnter={() => setIdx(me)}169 onClick={() => go(item)}170 className={cn(171 "relative flex w-full items-center gap-3 rounded-[8px] px-3 py-2.5 text-left",172 )}173 >174 {me === idx && <SlideMark id="palette-mark" className="absolute inset-0 rounded-[8px] bg-surface-2" />}175 <span className={cn("relative grid size-9 shrink-0 place-items-center rounded-[8px] transition-colors duration-150", me === idx ? "bg-ink text-bg" : "bg-surface-2 text-ink-2")}>176 <Icon className="size-[18px]" size={18} />177 </span>178 <span className="relative min-w-0 flex-1">179 <span className="block truncate text-[0.95rem] font-medium text-ink">{item.title}</span>180 {item.meta && <span className="block truncate text-xs text-ink-3">{item.meta}</span>}181 </span>182 <span className="relative">{me === idx ? <CornerDownLeft className="size-4 text-ink-3" /> : <ArrowRight className="size-4 text-ink-3/50" />}</span>183 </button>184 );185 })}186 </div>187 ))}188 {!flat.length && <div className="px-4 py-10 text-center text-sm text-ink-3">Aucun résultat.</div>}189 </div>190 </LayoutGroup>191 </motion.div>192 </div>193 )}194 </AnimatePresence>,195 document.body,196 );197}198