SPB Git

Repository Public

SearchBox.tsx 7.6 KB 209 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : src/components/SearchBox.tsx9 * Module           : components10 * Repository       : https://git.spboucher.ai/vrai-prix11 * Created          : 2026-08-0912 * Last Modified    : 2026-08-2513 *14 * Author           : Simon-Pierre Boucher15 * Position         : Professor of Finance16 * Institution      : Université du Québec en Outaouais (UQO)17 * Organization     : SP Boucher18 * Website          : https://spboucher.ai19 * Git              : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development      : dev@spboucher.ai23 * Support          : support@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142"use client";43import { useRef, useState } from "react";44import { useRouter } from "next/navigation";45import { useLang } from "./LangContext";4647export interface Suggestion {48  id: string;49  adresse: string | null;50  apt: string | null;51  municipalite: string | null;52  typeProp: string;53}5455export default function SearchBox({56  onPick,57  placeholder,58  variant = "default",59}: {60  /** Si fourni : appelé au choix d'une adresse (le champ se vide) au lieu de naviguer. */61  onPick?: (s: Suggestion) => void;62  placeholder?: string;63  /** « hero » : grand champ sur aplat encre (page d'accueil). */64  variant?: "default" | "hero";65}) {66  const { t, lang } = useLang();67  const fr = lang === "fr";68  const router = useRouter();69  const [q, setQ] = useState("");70  const [sugg, setSugg] = useState<Suggestion[]>([]);71  const [open, setOpen] = useState(false);72  const [searched, setSearched] = useState(false);73  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);74  const input = useRef<HTMLInputElement>(null);7576  const onChange = (value: string) => {77    setQ(value);78    if (timer.current) clearTimeout(timer.current);79    if (value.trim().length < 3) {80      setSugg([]);81      setSearched(false);82      return;83    }84    timer.current = setTimeout(async () => {85      const res = await fetch(`/api/search?q=${encodeURIComponent(value)}`);86      const data = (await res.json()) as { results: Suggestion[] };87      setSugg(data.results);88      setSearched(true);89      setOpen(true);90    }, 200);91  };9293  const pick = (s: Suggestion) => {94    if (onPick) {95      onPick(s);96      setQ("");97      setSugg([]);98      setSearched(false);99    } else {100      router.push(`/estimation/${s.id}`);101    }102  };103104  const hero = variant === "hero";105106  return (107    <div className="relative w-full">108      <div className={hero ? "flex items-stretch gap-0" : undefined}>109        <input110          id={variant === "hero" ? "vp-adresse" : undefined}111          ref={input}112          value={q}113          onChange={(e) => onChange(e.target.value)}114          onFocus={() => setOpen(true)}115          onBlur={() => setTimeout(() => setOpen(false), 200)}116          placeholder={117            placeholder ?? (hero ? (fr ? "ex. 861 route Elgin" : "e.g. 861 route Elgin") : t("searchPlaceholder"))118          }119          className={120            hero121              ? "min-h-[56px] w-full min-w-0 flex-1 border-0 border-b border-[rgba(245,243,238,0.45)] bg-transparent px-1 py-3 text-[16px] text-[var(--paper-on-ink)] outline-none transition-colors placeholder:text-[rgba(245,243,238,0.45)] focus:border-[var(--accent-bright)] sm:text-[19px]"122              : "vp-input text-base"123          }124          aria-label={placeholder ?? t("searchPlaceholder")}125        />126        {hero && (127          <button128            type="button"129            aria-label={fr ? "Estimer cette adresse" : "Estimate this address"}130            onMouseDown={(e) => {131              // mousedown : devance le blur de l'input (sinon le menu se ferme avant)132              e.preventDefault();133              if (sugg.length > 0) pick(sugg[0]);134              else input.current?.focus();135            }}136            className="vp-display -mb-px flex min-h-[56px] shrink-0 items-center gap-2 self-end bg-[var(--accent-bright)] px-4 text-[14px] font-bold text-ink transition-colors hover:bg-[#ff6b63] sm:px-7 sm:text-[15px]"137          >138            {fr ? "Estimer" : "Estimate"}139            <span aria-hidden="true">→</span>140          </button>141        )}142      </div>143      {open && sugg.length > 0 && (144        <ul145          className={`absolute z-[var(--z-dropdown,700)] mt-2 w-full overflow-hidden rounded-[2px] ${146            hero147              ? "border border-[rgba(245,243,238,0.25)] bg-[var(--ink-deep)] shadow-[0_14px_40px_rgba(0,0,0,0.5)]"148              : "border border-[var(--line-strong)] bg-surface shadow-[0_10px_30px_rgba(20,24,20,0.14)]"149          }`}150        >151          {sugg.map((s, i) => (152            <li153              key={s.id}154              className={155                hero156                  ? "border-b border-[rgba(245,243,238,0.1)] last:border-0"157                  : "border-b border-[rgba(20,24,20,0.08)] last:border-0"158              }159            >160              <button161                className={`flex w-full items-baseline justify-between gap-3 px-4 py-3 text-left transition-colors ${162                  hero ? "hover:bg-[rgba(245,243,238,0.08)]" : "hover:bg-surface-2"163                }`}164                onMouseDown={() => pick(s)}165              >166                <span className="flex min-w-0 items-baseline gap-2.5">167                  <span168                    className={`vp-mono shrink-0 text-[10px] ${169                      hero ? "text-[var(--accent-bright)]" : "text-accent"170                    }`}171                  >172                    {String(i + 1).padStart(2, "0")}173                  </span>174                  <span175                    className={`vp-display truncate font-bold ${176                      hero ? "text-[var(--paper-on-ink)]" : ""177                    }`}178                  >179                    {s.adresse}180                    {s.apt ? ` app. ${s.apt}` : ""}181                  </span>182                </span>183                <span184                  className={`vp-mono shrink-0 text-[10.5px] uppercase tracking-[0.05em] ${185                    hero ? "text-[rgba(245,243,238,0.55)]" : "text-ink-3"186                  }`}187                >188                  {s.municipalite}189                </span>190              </button>191            </li>192          ))}193        </ul>194      )}195      {open && searched && sugg.length === 0 && q.trim().length >= 3 && (196        <div197          className={`vp-mono absolute z-[var(--z-dropdown,700)] mt-2 w-full rounded-[2px] px-4 py-3 text-[12px] uppercase tracking-[0.04em] ${198            hero199              ? "border border-[rgba(245,243,238,0.25)] bg-[var(--ink-deep)] text-[rgba(245,243,238,0.7)]"200              : "border border-[var(--line-strong)] bg-surface text-ink-2"201          }`}202        >203          {t("searchNoResult")}204        </div>205      )}206    </div>207  );208}209
Files main
Menu

Theme