SPB Git

Repository Public

CommandPalette.tsx 7.2 KB 171 lines tsx

1// Palette de recherche rapide (⌘K) : pages et recherche libre.23import { useEffect, useMemo, useRef, useState } from "react";4import { createPortal } from "react-dom";5import { useNavigate } from "react-router";6import { AnimatePresence, LayoutGroup, motion } from "motion/react";7import { SlideMark } from "@/lib/motion";8import { ArrowRight, CornerDownLeft, Search } from "lucide-react";9import { IconBroker, IconHouseOpen, IconInspection, IconKey, IconMortgage, IconMover, IconNeighborhood } from "@/brand/icons";10import { cn } from "@/lib/cn";11import { slugify } from "@/lib/format";12import { Kbd } from "@/ui/primitives";1314interface Item {15  key: string;16  icon: React.ComponentType<{ className?: string; size?: number }>;17  title: string;18  meta?: string;19  to: string;20}2122// Le socle ne propose que les pages et la recherche libre ; la page Explorer23// pourra y brancher les villes et les agences (groupes « Villes », « Agences »).24const PAGES: Item[] = [25  { key: "p-carte", icon: IconHouseOpen, title: "Explorer la carte", meta: "Toutes les propriétés", to: "/recherche" },26  { key: "p-villes", icon: IconNeighborhood, title: "Toutes les villes", to: "/villes" },27  { key: "p-courtiers", icon: IconBroker, title: "Courtiers et agences", meta: "Annuaire", to: "/agences" },28  { key: "p-marche", icon: IconNeighborhood, title: "Marché immobilier", meta: "Statistiques", to: "/marche" },29  { key: "p-taux", icon: IconMortgage, title: "Taux hypothécaires", to: "/taux" },30  { key: "p-vp", icon: IconKey, title: "Le vrai prix : la méthode", to: "/vrai-prix" },31  { key: "p-insp", icon: IconInspection, title: "Inspecteurs en bâtiment", to: "/inspecteurs" },32  { key: "p-dem", icon: IconMover, 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  useEffect(() => {45    if (!open) return;46    setQ("");47    setIdx(0);48    const t = window.setTimeout(() => input.current?.focus(), 30);49    const overflow = document.body.style.overflow;50    document.body.style.overflow = "hidden";51    return () => {52      window.clearTimeout(t);53      document.body.style.overflow = overflow;54    };55  }, [open]);5657  const groups = useMemo(() => {58    const n = norm(q.trim());59    const pages = PAGES.filter((p) => (n ? norm(p.title + " " + (p.meta ?? "")).includes(n) : true)).slice(0, n ? 5 : 8);60    const free: Item[] = q.trim()61      ? [{ key: "free", icon: Search, title: `Chercher « ${q.trim()} »`, meta: "Titre, adresse, quartier", to: `/recherche?q=${encodeURIComponent(q.trim())}` }]62      : [];63    return [64      { label: "", items: free },65      { label: "Aller à", items: pages },66    ].filter((g) => g.items.length);67  }, [q]);6869  const flat = useMemo(() => groups.flatMap((g) => g.items), [groups]);70  useEffect(() => setIdx(0), [q]);7172  const go = (item: Item | undefined) => {73    if (!item) return;74    onClose();75    navigate(item.to);76  };7778  const onKey = (e: React.KeyboardEvent) => {79    if (e.key === "ArrowDown" || e.key === "ArrowUp") {80      e.preventDefault();81      const next = (idx + (e.key === "ArrowDown" ? 1 : -1) + flat.length) % Math.max(1, flat.length);82      setIdx(next);83      list.current?.querySelector(`[data-i="${next}"]`)?.scrollIntoView({ block: "nearest" });84    } else if (e.key === "Enter") {85      e.preventDefault();86      go(flat[idx]);87    } else if (e.key === "Escape") {88      onClose();89    }90  };9192  let i = -1;93  return createPortal(94    <AnimatePresence>95      {open && (96        <div className="fixed inset-0 z-[95] flex items-start justify-center px-3 pt-[9vh] sm:pt-[14vh]">97          <motion.div98            className="absolute inset-0 bg-scrim"99            initial={{ opacity: 0 }}100            animate={{ opacity: 1 }}101            exit={{ opacity: 0 }}102            onClick={onClose}103          />104          <motion.div105            role="dialog"106            aria-modal="true"107            aria-label="Recherche rapide"108            initial={{ opacity: 0, y: -6 }}109            animate={{ opacity: 1, y: 0 }}110            exit={{ opacity: 0, y: -4 }}111            transition={{ duration: 0.16, ease: [0.2, 0.7, 0.2, 1] }}112            className="relative w-full max-w-xl overflow-hidden rounded-[14px] border border-line-2 bg-surface shadow-float"113          >114            <div className="flex items-center gap-3 border-b border-line px-5">115              <Search className="size-5 shrink-0 text-ink-3" />116              <input117                ref={input}118                value={q}119                onChange={(e) => setQ(e.target.value)}120                onKeyDown={onKey}121                placeholder="Ville, quartier, adresse…"122                aria-label="Recherche rapide"123                className="h-15 w-full bg-transparent text-[1.05rem] text-ink outline-none placeholder:text-ink-3"124              />125              <Kbd>Échap</Kbd>126            </div>127            <LayoutGroup id="palette">128            <div ref={list} className="max-h-[56vh] overflow-y-auto overscroll-contain p-2">129              {groups.map((g) => (130                <div key={g.label || "free"} className="mb-1">131                  {g.label && <div className="eyebrow px-3 pb-1.5 pt-3">{g.label}</div>}132                  {g.items.map((item) => {133                    i += 1;134                    const me = i;135                    const Icon = item.icon;136                    return (137                      <button138                        key={item.key}139                        type="button"140                        data-i={me}141                        onMouseEnter={() => setIdx(me)}142                        onClick={() => go(item)}143                        className={cn(144                          "relative flex w-full items-center gap-3 rounded-[8px] px-3 py-2.5 text-left",145                        )}146                      >147                        {me === idx && <SlideMark id="palette-mark" className="absolute inset-0 rounded-[8px] bg-surface-2" />}148                        <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")}>149                          <Icon className="size-[18px]" size={18} />150                        </span>151                        <span className="relative min-w-0 flex-1">152                          <span className="block truncate text-[0.95rem] font-medium text-ink">{item.title}</span>153                          {item.meta && <span className="block truncate text-xs text-ink-3">{item.meta}</span>}154                        </span>155                        <span className="relative">{me === idx ? <CornerDownLeft className="size-4 text-ink-3" /> : <ArrowRight className="size-4 text-ink-3/50" />}</span>156                      </button>157                    );158                  })}159                </div>160              ))}161              {!flat.length && <div className="px-4 py-10 text-center text-sm text-ink-3">Aucun résultat.</div>}162            </div>163            </LayoutGroup>164          </motion.div>165        </div>166      )}167    </AnimatePresence>,168    document.body,169  );170}171
Files main
Menu

Theme