SPB Git

Repository Public

Compare.tsx 16.3 KB 353 lines tsx

1// Comparateur : jusqu'à quatre logements côte à côte, meilleure valeur de chaque2// ligne mise en évidence. La sélection reste sur l'appareil.34import { type ReactNode } from "react";5import { Link } from "react-router";6import { useQueries } from "@tanstack/react-query";7import { Check, ExternalLink, Plus, Trash2, X } from "lucide-react";8import { hasParking, priceOk, fetchListing, scoreGlobal, type Listing } from "@/lib/api";9import { cn } from "@/lib/cn";10import { cleanCity, fmtAvailability, fmtInt, fmtMoney, fmtPct } from "@/lib/format";11import { prettySource, useSourceNames, useTitle } from "@/lib/hooks";12import { clearCompare, COMPARE_MAX, toggleCompare, useCompare } from "@/lib/store";13import { SCORE_AXES, scoreColor } from "@/components/Score";14import { SmartImage } from "@/components/SmartImage";15import { VerdictPill } from "@/components/Verdict";16import { LoukaEmptyState } from "@/brand/EmptyState";17import { doorClick } from "@/brand/transition";18import { PageHero } from "@/components/marche/PageHero";19import { Button, ButtonLink, Skeleton } from "@/ui/primitives";2021const INCLUSIONS: [string, string][] = [22  ["heating", "Chauffage"],23  ["electricity", "Électricité"],24  ["hot_water", "Eau chaude"],25  ["internet", "Internet"],26];2728interface Row {29  label: string;30  group?: string;31  /** valeur numérique servant à désigner le meilleur ; null = hors concours */32  rank?: (l: Listing) => number | null;33  best?: "min" | "max";34  cell: (l: Listing) => ReactNode;35}3637const dash = <span className="text-ink-3">—</span>;38const yes = <span className="text-ink">Oui</span>;39const no = <span className="text-ink-3">Non</span>;4041const pi2 = (l: Listing) => (priceOk(l.price) && l.area_sqft && l.area_sqft > 100 ? l.price / l.area_sqft : null);42const axis = (l: Listing, k: string) => (l.kascores as unknown as Record<string, number | null> | null | undefined)?.[k] ?? null;43const globalScore = (l: Listing) => (l.kascores ? scoreGlobal(l.kascores) : null);4445function ScoreCell({ v }: { v: number | null }) {46  if (v == null) return dash;47  return (48    <span className="flex items-center gap-2.5">49      <span className="num w-7 font-medium">{Math.round(v)}</span>50      <span className="h-1 flex-1 overflow-hidden rounded-full bg-surface-3">51        <span className="block h-full rounded-full" style={{ width: `${v}%`, background: scoreColor(v) }} />52      </span>53    </span>54  );55}5657const ROWS: Row[] = [58  {59    group: "Prix",60    label: "Loyer mensuel",61    best: "min",62    rank: (l) => (priceOk(l.price) ? l.price : null),63    cell: (l) => (priceOk(l.price) ? <span className="num text-[1.06rem] font-semibold">{fmtMoney(l.price)}</span> : <span className="text-ink-3">Sur demande</span>),64  },65  { label: "Verdict", cell: (l) => (l.fv_verdict ? <VerdictPill verdict={l.fv_verdict} size="md" /> : <span className="text-sm text-ink-3">Pas de verdict</span>) },66  {67    label: "Valeur estimée",68    cell: (l) =>69      l.fv ? (70        <span className="num">71          <span className="font-medium">{fmtMoney(l.fv)}</span>72          {l.fv_low && l.fv_high ? <span className="block text-xs text-ink-3">{fmtInt(l.fv_low)} à {fmtMoney(l.fv_high)}</span> : null}73        </span>74      ) : (75        dash76      ),77  },78  {79    label: "Écart au marché",80    best: "min",81    rank: (l) => (l.fv_verdict ? (l.fv_deviation ?? null) : null),82    cell: (l) => (l.fv_deviation != null && l.fv_verdict ? <span className="num font-medium">{fmtPct(l.fv_deviation)}</span> : dash),83  },84  {85    label: "Prix au pi²",86    best: "min",87    rank: pi2,88    cell: (l) => {89      const v = pi2(l);90      return v == null ? dash : <span className="num font-medium">{v.toLocaleString("fr-CA", { minimumFractionDigits: 2, maximumFractionDigits: 2 })} $</span>;91    },92  },93  { group: "Logement", label: "Grandeur", cell: (l) => (l.unit_type ? <span className="font-medium">{l.unit_type}</span> : dash) },94  {95    label: "Superficie",96    best: "max",97    rank: (l) => (l.area_sqft && l.area_sqft > 100 ? l.area_sqft : null),98    cell: (l) => (l.area_sqft ? <span className="num font-medium">{fmtInt(l.area_sqft)} pi²</span> : dash),99  },100  { label: "Disponibilité", cell: (l) => fmtAvailability(l.availability_date, true) ?? dash },101  { label: "Animaux", cell: (l) => (l.pets === "oui" ? yes : l.pets === "conditions" ? <span className="text-ink">Sous conditions</span> : l.pets === "non" ? no : dash) },102  { label: "Meublé", cell: (l) => (l.furnished == null ? dash : l.furnished ? yes : no) },103  {104    label: "Inclus dans le loyer",105    best: "max",106    rank: (l) => {107      const n = INCLUSIONS.filter(([k]) => l.details?.inclusions?.[k]).length;108      return l.details?.inclusions ? n : null;109    },110    cell: (l) => {111      const got = INCLUSIONS.filter(([k]) => l.details?.inclusions?.[k]);112      if (!l.details?.inclusions) return dash;113      if (!got.length) return <span className="text-ink-3">Rien de mentionné</span>;114      return (115        <span className="text-ink">{got.map(([, label]) => label).join(", ")}</span>116      );117    },118  },119  { label: "Stationnement", cell: (l) => (l.details?.parking == null ? dash : hasParking(l.details) ? yes : no) },120  {121    group: "Quartier",122    label: "Score global",123    best: "max",124    rank: globalScore,125    cell: (l) => {126      const g = globalScore(l);127      return g == null ? dash : <span className="num text-[1.06rem] font-semibold">{Math.round(g)}</span>;128    },129  },130  ...SCORE_AXES.map(131    (a): Row => ({132      label: a.label,133      best: "max",134      rank: (l) => axis(l, a.key),135      cell: (l) => <ScoreCell v={axis(l, a.key)} />,136    }),137  ),138];139140function bestIndex(row: Row, listings: (Listing | undefined)[]): number | null {141  if (!row.rank || !row.best) return null;142  const vals = listings.map((l) => (l ? row.rank!(l) : null));143  const known = vals.filter((v): v is number => v != null);144  if (known.length < 2) return null;145  const target = row.best === "min" ? Math.min(...known) : Math.max(...known);146  if (known.every((v) => v === target)) return null;147  return vals.indexOf(target);148}149150export default function Compare() {151  useTitle("Comparateur de logements");152  const uids = useCompare();153  const names = useSourceNames();154  const queries = useQueries({155    queries: uids.map((uid) => ({ queryKey: ["listing", uid], queryFn: () => fetchListing(uid), staleTime: 5 * 60_000, retry: false })),156  });157  const listings = queries.map((q) => q.data);158  const cols = uids.length;159160  return (161    <>162      <PageHero163        eyebrow="Comparateur"164        title="Vos logements, côte à côte"165        text={`Jusqu'à ${COMPARE_MAX} logements comparés ligne par ligne. La meilleure valeur de chaque ligne est marquée.`}166      >167        {cols > 0 && (168          <div className="flex flex-wrap gap-2.5">169            <ButtonLink to="/recherche" variant="outline">170              <Plus className="size-4" /> Ajouter un logement171            </ButtonLink>172            <Button variant="ghost" onClick={clearCompare}>173              <Trash2 className="size-4" /> Tout retirer174            </Button>175          </div>176        )}177      </PageHero>178179      {cols === 0 ? (180        <section className="container-x">181          <div className="grid gap-x-12 border-y border-line lg:grid-cols-[1fr_1.1fr] lg:items-center">182            <LoukaEmptyState183              kind="many"184              title="Votre comparateur est vide"185              text="Ajoutez deux à quatre logements pour voir lequel coûte le moins cher au pied carré, lequel est le mieux situé et ce que chaque loyer inclut."186              action={187                <div className="flex flex-wrap justify-center gap-2.5">188                  <ButtonLink to="/recherche" variant="primary">189                    Explorer la carte190                  </ButtonLink>191                  <ButtonLink to="/favoris" variant="outline">192                    Partir de mes favoris193                  </ButtonLink>194                </div>195              }196            />197            <ol className="pb-10 lg:py-10">198              {[199                ["Repérez l'icône de balance", "Sur chaque annonce (au survol de la photo sur ordinateur) et sur chaque fiche de logement."],200                ["Ajoutez jusqu'à quatre logements", "Un bouton « Comparer » apparaît en bas de l'écran avec le nombre de logements choisis."],201                ["Lisez ligne par ligne", "Prix, juste valeur, superficie, inclusions et scores de quartier, dans le même ordre pour tous."],202              ].map(([t, d], i) => (203                <li key={t} className="grid grid-cols-[2rem_1fr] gap-x-3 border-t border-line py-4 first:border-0">204                  <span className="num pt-0.5 text-[0.86rem] text-ink-3">{i + 1}</span>205                  <span>206                    <span className="block text-[0.95rem] font-medium">{t}</span>207                    <span className="block text-[0.88rem] leading-relaxed text-ink-3">{d}</span>208                  </span>209                </li>210              ))}211            </ol>212          </div>213        </section>214      ) : (215        <section>216          <div className="mx-auto max-w-[1280px] lg:px-10">217          <div className="overflow-x-auto overscroll-x-contain pb-4 lg:overflow-visible">218            <table className="w-full table-fixed border-separate border-spacing-0 text-left text-[0.92rem]" style={{ minWidth: 112 + cols * 184 }}>219              <colgroup>220                <col className="w-28 lg:w-44" />221                {uids.map((uid) => (222                  <col key={uid} />223                ))}224              </colgroup>225              <thead>226                <tr>227                  <th className="sticky left-0 z-20 bg-bg p-0 align-bottom">228                    <span className="block px-4 pb-4 text-xs font-medium text-ink-3">{cols} sur {COMPARE_MAX}</span>229                  </th>230                  {uids.map((uid, i) => {231                    const l = listings[i];232                    const q = queries[i]!;233                    const href = `/logement/${encodeURIComponent(uid)}`;234                    return (235                      <th key={uid} scope="col" className="bg-bg p-2.5 align-top font-normal">236                        <div className="relative">237                          <button238                            type="button"239                            aria-label="Retirer du comparateur"240                            onClick={() => toggleCompare(uid)}241                            className="absolute right-2 top-2 z-10 grid size-9 place-items-center rounded-full bg-white/92 text-[#181c1a] shadow-[0_1px_3px_rgb(0_0_0/0.18)]"242                          >243                            <X className="size-4" />244                          </button>245                          {q.isPending ? (246                            <div>247                              <Skeleton className="aspect-[4/3] w-full rounded-xl" />248                              <Skeleton className="mt-3 h-4 w-3/4" />249                            </div>250                          ) : !l ? (251                            <div className="grid aspect-[4/3] place-items-center rounded-xl bg-surface-2 p-4 text-center text-[0.86rem] text-ink-3">Cette annonce n'est plus en ligne.</div>252                          ) : (253                            <Link to={href} onClick={(e) => doorClick(e, { uid, image: l.images?.[0] ?? null, context: "favorite" })} className="group block">254                              <span data-door-source className="block overflow-hidden rounded-xl bg-surface-2">255                                <SmartImage src={l.images?.[0]} alt="" className="aspect-[4/3] w-full" />256                              </span>257                              <span className="block pt-2.5 lg:hidden">258                                <span className="block truncate text-[0.92rem] font-medium text-ink group-hover:text-brand">{l.title || l.address || "Logement"}</span>259                                <span className="block truncate text-[0.8rem] text-ink-3">260                                  {[l.sector && l.sector !== l.city ? l.sector : null, cleanCity(l.city)].filter(Boolean).join(", ") || l.address}261                                </span>262                              </span>263                            </Link>264                          )}265                        </div>266                      </th>267                    );268                  })}269                </tr>270              </thead>271              <tbody>272                {/* rappel collant (grand écran) : qui est dans quelle colonne */}273                <tr className="hidden lg:table-row">274                  <th className="sticky top-16 z-30 border-b border-line-2 bg-bg" />275                  {uids.map((uid, i) => {276                    const l = listings[i];277                    return (278                      <th key={uid} className="sticky top-16 z-30 border-b border-line-2 bg-bg px-2.5 py-2.5 font-normal">279                        <span className="block truncate text-[0.84rem] font-medium text-ink">{l ? l.title || l.address || "Logement" : "…"}</span>280                        <span className="num block text-xs text-ink-3">{l && priceOk(l.price) ? `${fmtMoney(l.price)} / mois` : " "}</span>281                      </th>282                    );283                  })}284                </tr>285                {ROWS.map((row) => {286                  const best = bestIndex(row, listings);287                  return [288                    row.group && (289                      <tr key={`g-${row.group}`}>290                        <th colSpan={cols + 1} scope="colgroup" className="sticky left-0 bg-bg px-4 pb-2 pt-7 text-left">291                          <span className="eyebrow">{row.group}</span>292                        </th>293                      </tr>294                    ),295                    <tr key={row.label} className="group/row">296                      <th scope="row" className="sticky left-0 z-10 border-t border-line bg-bg px-4 py-3.5 text-[0.84rem] font-medium text-ink-2">297                        {row.label}298                      </th>299                      {uids.map((uid, i) => {300                        const l = listings[i];301                        const win = best === i;302                        return (303                          <td key={uid} className="border-t border-line px-2.5 py-1 align-middle">304                            <div className={cn("flex min-h-10 items-center justify-between gap-2 py-1.5", win && "font-medium text-brand")}>305                              <span className="min-w-0 flex-1">{l ? row.cell(l) : queries[i]?.isPending ? <Skeleton className="h-4 w-20" /> : dash}</span>306                              {win && <Check className="size-4 shrink-0 text-brand" aria-label="Meilleure valeur" />}307                            </div>308                          </td>309                        );310                      })}311                    </tr>,312                  ];313                })}314                <tr>315                  <th scope="row" className="sticky left-0 z-10 border-t border-line bg-bg px-4 py-4 text-[0.84rem] font-medium text-ink-2">316                    Source317                  </th>318                  {uids.map((uid, i) => {319                    const l = listings[i];320                    return (321                      <td key={uid} className="border-t border-line px-2.5 py-4 align-middle">322                        {l ? (323                          <span className="block">324                            <Link to={`/g/${l.source}`} className="block truncate hover:text-brand">325                              {prettySource(l.source, names)}326                            </Link>327                            <a href={l.url} target="_blank" rel="noopener noreferrer nofollow" className="mt-1 inline-flex items-center gap-1.5 text-[0.8rem] text-brand hover:underline">328                              Annonce originale <ExternalLink className="size-3.5" />329                            </a>330                          </span>331                        ) : (332                          dash333                        )}334                      </td>335                    );336                  })}337                </tr>338              </tbody>339            </table>340          </div>341          <p className="mt-4 px-4 text-[0.8rem] text-ink-3 lg:px-0">342            Un tiret signifie que l'annonce ne précise pas l'information. La meilleure valeur de chaque ligne est cochée. Le score global tient compte de vos pondérations personnelles.{" "}343            <Link to="/scores" className="text-brand underline underline-offset-[3px]">344              Régler mes priorités345            </Link>346          </p>347          </div>348        </section>349      )}350    </>351  );352}353
Files main
Menu

Theme