SPB Git

Repository Public

ProDirectory.tsx 9.1 KB 221 lines tsx

1// Annuaire de professionnels (inspecteurs en bâtiment, déménageurs) : même2// structure de données, même index à filets.34import { memo, useMemo, useState, type ReactNode } from "react";5import { useQuery } from "@tanstack/react-query";6import { ExternalLink, Phone } from "lucide-react";7import type { Pro, ProDoc } from "@/lib/api.annuaires";8import { cn } from "@/lib/cn";9import { fmtInt, plural } from "@/lib/format";10import { useDebounced, useTitle } from "@/lib/hooks";11import { BrandEmptyState } from "@/brand/compat";12import { Button } from "@/ui/primitives";13import { ChipRow, ErrorState, FilterTab, norm, PageHead, prettyHost, Rating, Rows, RowsSkeleton, SearchField, SortSelect, telHref, Toolbar, useProgressive } from "./shared";1415type Sort = "note" | "avis" | "nom" | "ville";16const SORTS: { value: Sort; label: string }[] = [17  { value: "note", label: "Meilleure note" },18  { value: "avis", label: "Nombre d'avis" },19  { value: "nom", label: "Nom" },20  { value: "ville", label: "Ville" },21];2223/** Note pondérée par le nombre d'avis : un 5,0 sur 2 avis ne devance pas un 4,8 sur 300. */24const weighted = (m: Pro) => (m.rating == null ? -1 : (m.rating * (m.reviews ?? 0) + 4.2 * 15) / ((m.reviews ?? 0) + 15));2526// colonnes (grand écran) : entreprise · note · téléphone · site27const COLS = "lg:grid lg:grid-cols-[minmax(0,1fr)_7rem_10.5rem_11rem] lg:items-center lg:gap-x-6";28const action =29  "inline-flex min-h-11 max-w-full items-center gap-2 rounded-[10px] border border-line-2 px-3.5 text-[0.9rem] transition-colors duration-150 hover:border-ink-3 lg:min-h-9 lg:border-0 lg:px-0 lg:hover:text-brand";3031const ProRow = memo(function ProRow({ m, genericCategory }: { m: Pro; genericCategory: string }) {32  // la catégorie n'est dite que si elle précise quelque chose33  const category = m.category && norm(m.category) !== norm(genericCategory) ? m.category : "";34  // « (Québec) G2A 1E7 » → « Québec » ; la région n'est pas répétée quand elle porte le nom de la ville35  const city = m.city.replace(/[A-Z]\d[A-Z] ?\d[A-Z]\d/g, "").replace(/[()]/g, "").trim();36  const where = [city, m.region !== city ? m.region : null].filter(Boolean).join(" · ");37  return (38    <div role="listitem" className={cn("border-b border-line py-3.5 lg:py-3", COLS)}>39      <div className="min-w-0">40        <div className="flex items-baseline justify-between gap-4">41          <h3 className="truncate text-[1.12rem] leading-snug">{m.name}</h3>42          <span className="shrink-0 lg:hidden">{m.rating != null && <Rating value={m.rating} reviews={m.reviews} />}</span>43        </div>44        <p className="mt-0.5 truncate text-[0.84rem] text-ink-3">45          {where}46          {category && ` · ${category}`}47          {m.address && <span className="max-lg:hidden"> · {m.address}</span>}48        </p>49      </div>50      <div className="hidden text-right lg:block">51        {m.rating != null ? <Rating value={m.rating} reviews={m.reviews} /> : <span className="text-[0.82rem] text-ink-3">Pas d'avis</span>}52      </div>53      <div className="max-lg:mt-2.5 max-lg:flex max-lg:gap-2 lg:contents">54        <div className="shrink-0 lg:text-right">55          {m.phone ? (56            <a href={telHref(m.phone)} aria-label={`Appeler ${m.name}`} className={cn(action, "num text-ink")}>57              <Phone className="size-4 text-ink-3" /> {m.phone}58            </a>59          ) : (60            <span className="hidden text-ink-3 lg:inline">—</span>61          )}62        </div>63        <div className="min-w-0 lg:text-right">64          {m.website ? (65            <a href={m.website} target="_blank" rel="noopener noreferrer nofollow" aria-label={`Site web de ${m.name} (nouvel onglet)`} className={cn(action, "!gap-1.5 text-[0.88rem] text-ink-2 hover:text-ink")}>66              <span className="truncate">{prettyHost(m.website)}</span>67              <ExternalLink className="size-3.5 shrink-0 text-ink-3" />68            </a>69          ) : (70            <span className="hidden text-ink-3 lg:inline">—</span>71          )}72        </div>73      </div>74    </div>75  );76});7778export function ProDirectory({79  queryKey,80  fetcher,81  pageTitle,82  title,83  text,84  one,85  many,86  searchLabel,87  genericCategory,88  emptyTitle,89  advice,90}: {91  queryKey: string;92  fetcher: () => Promise<ProDoc>;93  pageTitle: string;94  title: string;95  text: string;96  one: string;97  many: string;98  searchLabel: string;99  genericCategory: string;100  emptyTitle: string;101  /** conseil de prudence, sous la liste */102  advice: ReactNode;103}) {104  useTitle(pageTitle);105  const q = useQuery({ queryKey: [queryKey], queryFn: fetcher, staleTime: 36e5 });106  const [input, setInput] = useState("");107  const [region, setRegion] = useState<string | null>(null);108  const [sort, setSort] = useState<Sort>("note");109  const needle = norm(useDebounced(input, 120).trim());110111  const index = useMemo(() => (q.data?.movers ?? []).map((m) => ({ m, hay: norm(`${m.name} ${m.city} ${m.region} ${m.category}`) })), [q.data]);112113  const rows = useMemo(() => {114    const r = index.filter((x) => (!needle || x.hay.includes(needle)) && (!region || x.m.region === region)).map((x) => x.m);115    if (sort === "nom") r.sort((a, b) => a.name.localeCompare(b.name, "fr"));116    else if (sort === "ville") r.sort((a, b) => (a.city || "~").localeCompare(b.city || "~", "fr") || a.name.localeCompare(b.name, "fr"));117    else if (sort === "avis") r.sort((a, b) => (b.reviews ?? -1) - (a.reviews ?? -1));118    else r.sort((a, b) => weighted(b) - weighted(a) || a.name.localeCompare(b.name, "fr"));119    return r;120  }, [index, needle, region, sort]);121122  const { count, sentinel } = useProgressive(rows.length, `${needle}|${region}|${sort}`);123  const stats = useMemo(() => {124    let rated = 0;125    let phone = 0;126    for (const { m } of index) {127      if (m.rating != null) rated += 1;128      if (m.phone) phone += 1;129    }130    return { rated, phone };131  }, [index]);132  const filtered = !!needle || !!region;133  const generated = q.data?.generated ? new Date(q.data.generated + "T12:00:00").toLocaleDateString("fr-CA", { day: "numeric", month: "long", year: "numeric" }) : null;134135  return (136    <>137      <PageHead138        eyebrow="Annuaire"139        title={title}140        text={text}141        facts={142          !!q.data && [143            { value: fmtInt(q.data.total), label: many },144            { value: fmtInt(q.data.regions.length), label: "régions administratives" },145            { value: fmtInt(stats.rated), label: "avec une note Google" },146            { value: fmtInt(stats.phone), label: "avec un téléphone" },147          ]148        }149      />150151      <Toolbar>152        <div className="flex flex-wrap items-center gap-2">153          <SearchField value={input} onChange={setInput} placeholder={searchLabel} className="min-w-0 flex-1 basis-64" />154          <SortSelect value={sort} onChange={setSort} options={SORTS} />155        </div>156        <ChipRow label="Région">157          <FilterTab active={!region} onClick={() => setRegion(null)}>158            Toutes les régions159          </FilterTab>160          {(q.data?.regions ?? []).map((r) => (161            <FilterTab key={r.region} active={region === r.region} onClick={() => setRegion(region === r.region ? null : r.region)} count={r.n}>162              {r.region}163            </FilterTab>164          ))}165        </ChipRow>166      </Toolbar>167168      <div className="container-x pt-6">169        {q.isError ? (170          <ErrorState onRetry={() => q.refetch()} />171        ) : q.isPending ? (172          <RowsSkeleton rows={12} tall />173        ) : rows.length === 0 ? (174          <BrandEmptyState175            kind="closed"176            title={emptyTitle}177            text="Essayez une ville voisine, une autre région ou un autre nom."178            action={179              filtered && (180                <Button181                  variant="outline"182                  onClick={() => {183                    setInput("");184                    setRegion(null);185                  }}186                >187                  Effacer les filtres188                </Button>189              )190            }191          />192        ) : (193          <>194            <p className="num mb-4 text-[0.86rem] text-ink-3" aria-live="polite">195              {plural(rows.length, one, many)}196              {region ? ` · ${region}` : ""}197              {needle ? ` · « ${input.trim()} »` : ""}198            </p>199            <div className={cn("hidden border-b border-line-2 pb-2 text-[0.76rem] text-ink-3", COLS)} aria-hidden>200              <span>Entreprise</span>201              <span className="text-right">Note Google</span>202              <span className="text-right">Téléphone</span>203              <span className="text-right">Site web</span>204            </div>205            <Rows resetKey={`${region}|${sort}`}>206              {rows.slice(0, count).map((m) => (207                <ProRow key={m.id} m={m} genericCategory={genericCategory} />208              ))}209            </Rows>210            {sentinel}211            <p className="mt-10 max-w-2xl text-[0.82rem] leading-relaxed text-ink-3">212              Coordonnées et notes tirées de fiches publiques Google{generated ? `, relevées le ${generated}` : ""}. {advice} Immo-Ka n'a aucun lien d'affaires avec les213              entreprises listées et ne reçoit aucune commission.214            </p>215          </>216        )}217      </div>218    </>219  );220}221
Files main
Menu

Theme