Repository Public
1// Briques communes aux annuaires d'Immo-Ka (courtiers et agences, inspecteurs,2// déménageurs, sources, villes). Index typographiques : des lignes à filet,3// denses et lisibles, plutôt que des murs de cartes.45import { useEffect, useRef, useState, type ReactNode } from "react";6import { Link } from "react-router";7import { ArrowRight, RotateCw, Search, Star, X } from "lucide-react";8import { useQuery } from "@tanstack/react-query";9import { cn } from "@/lib/cn";10import { fmtMoney } from "@/lib/format";11import { useInView } from "@/lib/hooks";12import { Stagger } from "@/lib/motion";13import { BrandEmptyState } from "@/brand/compat";14import { Button } from "@/ui/primitives";15import { directoryQuery, fetchMedian, probeAgencyFilter, type DirEntry, type ListingQuery } from "@/lib/api.annuaires";1617export { norm } from "@/lib/api.annuaires";1819/** Adresse web lisible : « https://www.remax-quebec.com/fr » → « remax-quebec.com ». */20export function prettyHost(url: string | null | undefined): string {21 if (!url) return "";22 try {23 return new URL(url).hostname.replace(/^www\./, "");24 } catch {25 return url.replace(/^https?:\/\/(www\.)?/, "").split("/")[0] ?? url;26 }27}2829/** Numéro composable pour un lien tel: (numéros nord-américains à 10 chiffres). */30export function telHref(phone: string): string {31 const d = phone.replace(/\D/g, "");32 return `tel:${d.length === 10 ? `+1${d}` : d.length === 11 && d.startsWith("1") ? `+${d}` : d}`;33}3435/** « Laval, Montréal et 3 autres » */36export function listSome(items: string[], max = 3): string {37 if (items.length <= max) return items.join(", ");38 return `${items.slice(0, max).join(", ")} et ${items.length - max} autres`;39}4041// --- En-tête de page -----------------------------------------------------------42export function BackLink({ to, children }: { to: string; children: ReactNode }) {43 return (44 <Link to={to} className="mb-3 inline-flex min-h-11 items-center gap-1.5 text-[0.88rem] text-ink-3 transition-colors duration-150 hover:text-ink">45 <ArrowRight className="size-4 rotate-180" /> {children}46 </Link>47 );48}4950export interface Fact {51 value: ReactNode;52 label: string;53}5455/** Faits réels en ligne discrète : valeur tabulaire, libellé en pierre. */56export function Facts({ items, className }: { items: Fact[]; className?: string }) {57 return (58 <dl className={cn("grid grid-cols-2", items.length > 2 ? "min-h-[7.75rem]" : "min-h-[4rem]", " content-start gap-x-6 gap-y-2.5 border-t border-line pt-4 sm:flex sm:min-h-[2.6rem] sm:flex-wrap sm:gap-x-9", className)}>59 {items.map((it) => (60 <div key={it.label} className="flex min-w-0 flex-col sm:flex-row sm:items-baseline sm:gap-2">61 <dd className="num truncate text-[1.05rem] font-semibold text-ink">{it.value}</dd>62 <dt className="text-[0.84rem] leading-snug text-ink-3">{it.label}</dt>63 </div>64 ))}65 </dl>66 );67}6869/** Même encombrement que `Facts`, pendant le chargement : rien ne bouge à l'arrivée des chiffres. */70export function FactsPlaceholder({ className }: { className?: string }) {71 return (72 <div aria-hidden className={cn("grid min-h-[7.75rem] grid-cols-2 content-start gap-x-6 gap-y-2.5 border-t border-line pt-4 sm:flex sm:min-h-[2.6rem] sm:gap-x-9", className)}>73 {[5, 7, 6, 4].map((w, i) => (74 <div key={i} className="flex flex-col gap-1.5 sm:flex-row sm:items-center sm:gap-2">75 <span className="skeleton h-5" style={{ width: `${w * 0.55}rem` }} />76 <span className="skeleton h-3.5" style={{ width: `${w + 2}rem` }} />77 </div>78 ))}79 </div>80 );81}8283/** En-tête sobre : sur-titre, titre serif, une phrase, puis les faits en ligne. */84export function PageHead({85 eyebrow,86 title,87 text,88 facts,89 aside,90 back,91}: {92 eyebrow?: ReactNode;93 title: ReactNode;94 text?: ReactNode;95 /** chiffres clés ; `null` ou `false` pendant le chargement : la place est réservée */96 facts?: Fact[] | null | false;97 aside?: ReactNode;98 back?: { to: string; label: string };99}) {100 return (101 <header className="container-x pb-6 pt-5 lg:pb-7 lg:pt-10">102 {back && <BackLink to={back.to}>{back.label}</BackLink>}103 <div className="flex flex-wrap items-end justify-between gap-x-10 gap-y-5">104 <div className="min-w-0 max-w-2xl">105 {eyebrow && <div className="eyebrow">{eyebrow}</div>}106 <h1 className={cn("text-[1.85rem] leading-[1.08] sm:text-[2.5rem]", !!eyebrow && "mt-2.5")}>{title}</h1>107 {text && <p className="mt-2.5 text-[0.95rem] leading-relaxed text-ink-2 sm:text-[1rem]">{text}</p>}108 </div>109 {aside}110 </div>111 {facts ? <Facts items={facts} className="mt-5" /> : facts === undefined ? null : <FactsPlaceholder className="mt-5" />}112 </header>113 );114}115116/** En-tête de section : filet, titre serif, une phrase, action à droite. */117export function SectionHead({118 id,119 title,120 text,121 to,122 cta,123 aside,124}: {125 id?: string;126 title: ReactNode;127 text?: ReactNode;128 to?: string;129 cta?: string;130 aside?: ReactNode;131}) {132 return (133 <div className="flex flex-wrap items-end justify-between gap-x-8 gap-y-3 border-t border-line pt-7">134 <div className="min-w-0">135 <h2 id={id} className="scroll-mt-24 text-[1.5rem] sm:text-[1.75rem]">136 {title}137 </h2>138 {text && <p className="mt-1 max-w-xl text-[0.94rem] text-ink-3">{text}</p>}139 </div>140 {to && cta && (141 <Link to={to} className="group inline-flex min-h-11 items-center gap-1.5 text-[0.9rem] font-medium text-brand">142 {cta} <ArrowRight className="size-4 transition-transform duration-150 group-hover:translate-x-0.5" />143 </Link>144 )}145 {aside}146 </div>147 );148}149150// --- Recherche, tri, filtres ------------------------------------------------------151export function SearchField({ value, onChange, placeholder, className }: { value: string; onChange: (v: string) => void; placeholder: string; className?: string }) {152 return (153 <div className={cn("relative", className)}>154 <Search className="pointer-events-none absolute left-3.5 top-1/2 size-[18px] -translate-y-1/2 text-ink-3" />155 <input156 type="search"157 value={value}158 onChange={(e) => onChange(e.target.value)}159 placeholder={placeholder}160 aria-label={placeholder}161 autoComplete="off"162 className="field !pl-10 !pr-10 text-[0.95rem] [&::-webkit-search-cancel-button]:hidden"163 />164 {value && (165 <button166 type="button"167 aria-label="Effacer la recherche"168 onClick={() => onChange("")}169 className="absolute right-0 top-1/2 grid size-11 -translate-y-1/2 place-items-center rounded-full text-ink-3 hover:text-ink"170 >171 <X className="size-4" />172 </button>173 )}174 </div>175 );176}177178/** Menu de tri natif (roue iOS, liste Android), habillé. */179export function SortSelect<T extends string>({180 value,181 onChange,182 options,183 label = "Trier",184}: {185 value: T;186 onChange: (v: T) => void;187 options: { value: T; label: string }[];188 label?: string;189}) {190 return (191 <label className="relative inline-flex h-11 min-w-0 shrink-0 items-center gap-1.5 rounded-[10px] border border-line-2 bg-surface pl-3.5 pr-9 text-[0.88rem] text-ink">192 <span className="text-ink-3">{label}</span>193 <span className="truncate font-medium">{options.find((o) => o.value === value)?.label}</span>194 <select value={value} onChange={(e) => onChange(e.target.value as T)} aria-label={label} className="absolute inset-0 cursor-pointer appearance-none opacity-0">195 {options.map((o) => (196 <option key={o.value} value={o.value}>197 {o.label}198 </option>199 ))}200 </select>201 <svg viewBox="0 0 24 24" className="pointer-events-none absolute right-3 size-4 text-ink-3" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>202 <path d="m6 9 6 6 6-6" strokeLinecap="round" strokeLinejoin="round" />203 </svg>204 </label>205 );206}207208/** Rangée de filtres : défilable horizontalement sur mobile, à la ligne sur grand écran. */209export function ChipRow({ children, className, label }: { children: ReactNode; className?: string; label?: string }) {210 return (211 <div className="-mx-[clamp(1rem,4vw,2.5rem)] lg:mx-0" role="group" aria-label={label}>212 <div className={cn("no-scrollbar flex gap-1.5 overflow-x-auto px-[clamp(1rem,4vw,2.5rem)] lg:flex-wrap lg:px-0", className)}>{children}</div>213 </div>214 );215}216217const tabClass = (active: boolean) =>218 cn(219 "inline-flex h-11 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-[8px] border px-3 text-[0.86rem] transition-colors duration-150 lg:h-9",220 active ? "border-ink bg-ink font-medium text-bg" : "border-line-2 bg-surface text-ink-2 hover:border-ink-3 hover:text-ink",221 );222223/** Filtre à bascule, net, avec compte optionnel. */224export function FilterTab({ active, onClick, children, count }: { active: boolean; onClick: () => void; children: ReactNode; count?: number | string }) {225 return (226 <button type="button" aria-pressed={active} onClick={onClick} className={tabClass(active)}>227 {children}228 {count != null && <span className={cn("num text-[0.78rem]", active ? "opacity-70" : "text-ink-3")}>{count}</span>}229 </button>230 );231}232233/** Même apparence, mais c'est un lien (pages de ville par type). */234export function TabLink({ to, active, children, count }: { to: string; active: boolean; children: ReactNode; count?: number | string }) {235 return (236 <Link to={to} aria-current={active ? "page" : undefined} className={tabClass(active)} preventScrollReset>237 {children}238 {count != null && <span className={cn("num text-[0.78rem]", active ? "opacity-70" : "text-ink-3")}>{count}</span>}239 </Link>240 );241}242243/** Barre d'outils (recherche + filtres), collante sous l'en-tête du site sur grand écran. */244export function Toolbar({ children }: { children: ReactNode }) {245 return (246 <div className="z-30 border-y border-line bg-bg lg:sticky lg:top-16">247 <div className="container-x space-y-2.5 py-3">{children}</div>248 </div>249 );250}251252// --- Note ------------------------------------------------------------------------253/** Note Google : une étoile, la valeur, le nombre d'avis. Factuel, sans rangée d'étoiles dorées. */254export function Rating({ value, reviews, className }: { value: number | null | undefined; reviews?: number | null; className?: string }) {255 if (value == null) return null;256 const txt = value.toFixed(1).replace(".", ",");257 return (258 <span259 className={cn("num inline-flex items-center gap-1 whitespace-nowrap text-[0.86rem]", className)}260 role="img"261 aria-label={`Note ${txt} sur 5${reviews != null ? `, ${reviews} avis` : ""}`}262 >263 <Star className="size-3.5 text-ink-3" fill="currentColor" strokeWidth={0} />264 <span className="font-medium text-ink">{txt}</span>265 {reviews != null && <span className="text-ink-3">({reviews})</span>}266 </span>267 );268}269270// --- Listes ----------------------------------------------------------------------271/** Renvoie le nombre d'éléments à afficher et la sentinelle à placer en bas de272 * liste : la tranche suivante s'ajoute à l'approche du bas. */273export function useProgressive(total: number, resetKey: string, step = 60) {274 const [count, setCount] = useState(step);275 const ref = useRef<HTMLDivElement>(null);276 useEffect(() => setCount(step), [resetKey, step]);277 useEffect(() => {278 const el = ref.current;279 if (!el || count >= total) return;280 const io = new IntersectionObserver((entries) => entries.some((e) => e.isIntersecting) && setCount((c) => Math.min(total, c + step)), { rootMargin: "900px" });281 io.observe(el);282 return () => io.disconnect();283 }, [count, total, step]);284 return { count: Math.min(count, total), sentinel: <div ref={ref} className="h-px" aria-hidden /> };285}286287/**288 * Liste à filets : cascade au premier affichage, réentrée brève quand `resetKey`289 * change (tri, filtre). Les enfants sont des `Row` (rôle listitem).290 */291export function Rows({ children, resetKey, className }: { children: ReactNode; resetKey?: string; className?: string }) {292 return (293 <div role="list">294 <Stagger resetKey={resetKey} className={className}>295 {children}296 </Stagger>297 </div>298 );299}300301export const rowClass = "group block border-b border-line py-3.5 transition-colors duration-150 hover:border-ink-3 lg:py-3";302303/** Lignes fantômes pendant un chargement réel. */304export function RowsSkeleton({ rows = 10, tall }: { rows?: number; tall?: boolean }) {305 return (306 <ul aria-hidden>307 {Array.from({ length: rows }, (_, i) => (308 <li key={i} className={cn("flex items-center justify-between gap-6 border-b border-line", tall ? "py-[1.125rem]" : "py-4")}>309 <div className="min-w-0 flex-1 space-y-2">310 <div className="skeleton h-5" style={{ width: `${28 + ((i * 17) % 30)}%` }} />311 {tall && <div className="skeleton h-3.5" style={{ width: `${18 + ((i * 11) % 22)}%` }} />}312 </div>313 <div className="skeleton h-4 w-20 shrink-0" />314 </li>315 ))}316 </ul>317 );318}319320// --- États ----------------------------------------------------------------------321export function ErrorState({ onRetry, text }: { onRetry?: () => void; text?: string }) {322 return (323 <BrandEmptyState324 kind="closed"325 title="Chargement impossible"326 text={text ?? "Les données n'ont pas pu être récupérées. Vérifiez votre connexion, puis réessayez."}327 action={328 onRetry && (329 <Button variant="outline" onClick={onRetry}>330 <RotateCw className="size-4" /> Réessayer331 </Button>332 )333 }334 />335 );336}337338// --- Prix médian paresseux -----------------------------------------------------339/** Prix médian d'un filtre, demandé seulement si `enabled` (ligne visible, filtre pris en charge). */340export function useMedian(q: ListingQuery | null, n: number | undefined, enabled = true) {341 return useQuery({342 queryKey: ["ik-mediane", q?.source ?? "", q?.agency ?? "", q?.city ?? "", q?.property_type ?? ""],343 queryFn: ({ signal }) => fetchMedian(q!, n, signal),344 enabled: enabled && !!q && (n == null || n > 0),345 staleTime: 36e5,346 gcTime: 36e5,347 retry: 1,348 });349}350351/**352 * Prix médian d'une ligne d'annuaire, chargé quand la ligne entre dans la fenêtre.353 * La largeur est fixée par la colonne : rien ne bouge à l'arrivée du chiffre.354 */355export function MedianValue({ q, n, known, className, prefix }: { q: ListingQuery | null; n?: number; known?: number | null; className?: string; prefix?: string }) {356 const [ref, seen] = useInView<HTMLSpanElement>("300px");357 // `known` : valeur déjà fournie par le serveur (v2), aucun calcul358 const m = useMedian(q, n, seen && known === undefined);359 return (360 <span ref={ref} className={cn("num", className)}>361 {known !== undefined ? (362 known != null ? (363 <span>364 {prefix}365 {fmtMoney(known)}366 </span>367 ) : (368 <span className="text-ink-3">—</span>369 )370 ) : !q || (n != null && n < 1) ? (371 <span className="text-ink-3">—</span>372 ) : m.data != null ? (373 <span>374 {prefix}375 {fmtMoney(m.data)}376 </span>377 ) : m.isPending ? (378 <span className="skeleton inline-block h-3.5 w-16 align-middle" aria-label="Calcul du prix médian" />379 ) : (380 <span className="text-ink-3">—</span>381 )}382 </span>383 );384}385386// --- Annuaire des agences : aides partagées par l'index et les fiches ------------387388/** L'annuaire unifié (bannières, agences, vente directe, plateformes). */389export const useDirectory = () => useQuery(directoryQuery);390391/**392 * Le serveur sait-il filtrer les inscriptions par bureau (`agency`) ? Sondé une393 * fois par session ; `undefined` tant que la réponse n'est pas connue.394 */395export function useAgencyFilter(): boolean | undefined {396 const dir = useDirectory();397 const source = dir.data?.entries.find((e) => e.inventory.some((p) => !p.agency && p.count > 0))?.inventory[0]?.source;398 const q = useQuery({399 queryKey: ["ik-filtre-agence", source ?? ""],400 queryFn: () => probeAgencyFilter(source!),401 enabled: !!source,402 staleTime: Infinity,403 gcTime: Infinity,404 });405 return q.data;406}407408/**409 * Filtre qui décrit tout l'inventaire d'une entrée, quand un seul appel suffit :410 * un connecteur (ou un connecteur qui porte au moins 80 % des inscriptions), ou un411 * bureau si le serveur sait filtrer par `agency`. Sinon `null` (médiane inconnue).412 */413export function entryQuery(e: DirEntry, agencyOk: boolean | undefined): ListingQuery | null {414 const parts = e.inventory.filter((p) => p.count > 0);415 if (!parts.length) return null;416 const top = parts.reduce((a, b) => (b.count > a.count ? b : a));417 if (top.count < 0.8 * e.listings) return null;418 if (top.agency) return agencyOk ? { source: top.source, agency: top.agency } : null;419 return { source: top.source };420}421422/** « Toute la province — ~5 000 courtiers… » → « Toute la province » */423export const coverageShort = (c: string) => c.split(" — ")[0]!.split(" (")[0]!.trim();424