SPB Git

Repository Public

Content.tsx 13.7 KB 295 lines tsx

1// Description, caractéristiques et inclusions, bâtiment et terrain (détails2// publiés par la source, pièces, taxes et évaluation municipale).3// Les libellés de `details` varient d'une source à l'autre : ils sont rangés4// par famille sans être réécrits, et rien n'est supprimé.56import { motion } from "motion/react";7import { useMemo, useState } from "react";8import {9  AirVent, Bath, Car, Check, Dumbbell, Fence, Flame, Home, Mountain, Package, Refrigerator, Sofa, Sun, Trees, WashingMachine, Waves, Wifi, Zap,10} from "lucide-react";11import { condoFeesOf, municipalValueOf, taxesOf, typeOf, type Property, type Room } from "@/lib/api.propriete";12import { cn } from "@/lib/cn";13import { useMotionAllowed } from "@/lib/motion";14import { Disclosure, KV, money, MoreLink, Section } from "./kit";1516// --- Description ----------------------------------------------------------------17const clean = (t: string | null | undefined) =>18  (t || "")19    .replace(/<br\s*\/?>/gi, "\n")20    .replace(/<[^>]+>/g, "")21    .replace(/&nbsp;/g, " ")22    .replace(/&amp;/g, "&")23    .replace(/&#39;|&rsquo;/g, "'")24    .replace(/[ \t]+\n/g, "\n")25    .trim();2627export const descriptionOf = (p: Property) => clean(p.description);28const ownerNoteOf = (p: Property) => {29  const t = clean(typeof p.details?.remarques_proprio === "string" ? p.details.remarques_proprio : "");30  return t && t !== descriptionOf(p) ? t : "";31};32export const hasDescription = (p: Property) => !!(descriptionOf(p) || ownerNoteOf(p));3334function Paragraphs({ text }: { text: string }) {35  return (36    <>37      {text38        .split(/\n{2,}|\n(?=[A-ZÀ-Ý•\-–*])/)39        .map((s) => s.trim())40        .filter(Boolean)41        .map((s, i) => (42          <p key={i} className="whitespace-pre-line break-words">43            {s}44          </p>45        ))}46    </>47  );48}4950export function Description({ p }: { p: Property }) {51  const [open, setOpen] = useState(false);52  const ok = useMotionAllowed();53  const text = descriptionOf(p);54  const note = ownerNoteOf(p);55  if (!text && !note) return null;56  const long = text.length + note.length > 640;57  return (58    <Section id="description" title="Description">59      <motion.div60        className={cn("relative", long && "overflow-hidden")}61        initial={false}62        animate={{ height: long && !open ? 232 : "auto" }}63        transition={ok ? { duration: 0.36, ease: [0.6, 0, 0.16, 1] } : { duration: 0 }}64      >65        <div className="max-w-3xl space-y-4 text-[1rem] leading-[1.7] text-ink-2">66          {text && <Paragraphs text={text} />}67          {note && (68            <div className="border-l-2 border-line-2 pl-4">69              <h3 className="mb-1.5 text-[1.02rem] text-ink">Le mot du propriétaire</h3>70              <div className="space-y-3">71                <Paragraphs text={note} />72              </div>73            </div>74          )}75        </div>76        {/* voile de repli : simple fondu vers le fond de page, pas un décor */}77        <div aria-hidden className={cn("pointer-events-none absolute inset-x-0 bottom-0 h-14 bg-gradient-to-t from-bg to-transparent transition-opacity duration-300", long && !open ? "opacity-100" : "opacity-0")} />78      </motion.div>79      {long && (80        <MoreLink onClick={() => setOpen((o) => !o)}>81          <span aria-expanded={open}>{open ? "Réduire la description" : "Lire toute la description"}</span>82        </MoreLink>83      )}84    </Section>85  );86}8788// --- Caractéristiques et inclusions ---------------------------------------------------89type Lucide = typeof Check;90const norm = (s: string) => s.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/\s+/g, " ").trim();9192const ICONS: [RegExp, Lucide][] = [93  [/chauffage|foyer|poele|thermopompe/, Flame], [/climatis|air climatise|echangeur/, AirVent], [/piscine|spa|bord de l'eau|riverain|lac/, Waves],94  [/garage|stationnement|allee|abri d'auto/, Car], [/laveuse|secheuse|buanderie/, WashingMachine], [/lave-vaisselle|refrigerateur|cuisiniere|electromenager/, Refrigerator],95  [/meuble/, Sofa], [/balcon|terrasse|patio|veranda|solarium/, Sun], [/cloture|haie/, Fence], [/remise|rangement|cabanon|entrepos/, Package],96  [/gym|exercice/, Dumbbell], [/internet|fibre|wifi/, Wifi], [/electri|generatrice|borne/, Zap], [/salle de bain|douche|bain/, Bath],97  [/vue|montagne/, Mountain], [/parc|boise|arbres|paysag|jardin/, Trees], [/sous-sol|plain-pied|etage/, Home],98];99const iconFor = (label: string): Lucide => {100  const n = norm(label);101  for (const [re, I] of ICONS) if (re.test(n)) return I;102  return Check;103};104105/** Caractéristiques publiées, dédoublonnées ; écarte ce qui répète le type ou les pièces. */106export function featuresOf(p: Property): string[] {107  const seen = new Set<string>();108  const type = norm(typeOf(p) || "");109  return (p.features ?? [])110    .map((f) => (typeof f === "string" ? f.trim() : ""))111    .filter((f) => {112      const k = norm(f);113      if (!k || k.length > 90 || seen.has(k) || k === type) return false;114      if (/^\d+ (chambres?|salles? de bain)/.test(k) || /^\d+ pieds carres$/.test(k)) return false;115      seen.add(k);116      return true;117    });118}119120const textOf = (p: Property, keys: string[]) => {121  for (const k of keys) {122    const v = p.details?.[k];123    if (typeof v === "string" && v.trim() && !/^(aucune?|n\/a|-)$/i.test(v.trim())) return v.trim();124  }125  return "";126};127export const inclusionsOf = (p: Property) => textOf(p, ["Inclusions", "Éléments inclus lors de la vente", "Inclus"]);128export const exclusionsOf = (p: Property) => textOf(p, ["Exclusions", "Éléments exclus lors de la vente", "Exclus"]);129export const hasFeatures = (p: Property) => featuresOf(p).length > 0 || !!inclusionsOf(p) || !!exclusionsOf(p);130131export function Features({ p }: { p: Property }) {132  const [all, setAll] = useState(false);133  const items = useMemo(() => featuresOf(p), [p]);134  const inc = inclusionsOf(p);135  const exc = exclusionsOf(p);136  if (!items.length && !inc && !exc) return null;137  const LIMIT = 12;138  const shown = all ? items : items.slice(0, LIMIT);139  return (140    <Section id="caracteristiques" title="Caractéristiques et inclusions" text={items.length ? `${items.length} élément${items.length > 1 ? "s" : ""} publié${items.length > 1 ? "s" : ""} par la source.` : undefined}>141      {items.length > 0 && (142        <ul className="grid grid-cols-1 gap-x-8 sm:grid-cols-2 xl:grid-cols-3">143          {shown.map((t) => {144            const Icon = iconFor(t);145            return (146              <li key={t} className="flex min-h-11 items-center gap-3 border-b border-line py-2.5">147                <Icon className="size-[18px] shrink-0 text-ink-3" />148                <span className="min-w-0 flex-1 break-words text-[0.94rem] text-ink">{t}</span>149              </li>150            );151          })}152        </ul>153      )}154      {items.length > LIMIT && <MoreLink onClick={() => setAll((a) => !a)}>{all ? "Réduire" : `Voir les ${items.length} caractéristiques`}</MoreLink>}155      {(inc || exc) && (156        <dl className={cn("grid max-w-3xl gap-x-10 gap-y-5 text-[0.94rem] leading-relaxed", items.length > 0 && "mt-6", inc && exc && "sm:grid-cols-2")}>157          {inc && (158            <div className="min-w-0">159              <dt className="mb-1 text-[0.8rem] text-ink-3">Inclus dans la vente</dt>160              <dd className="break-words text-ink-2">{inc}</dd>161            </div>162          )}163          {exc && (164            <div className="min-w-0">165              <dt className="mb-1 text-[0.8rem] text-ink-3">Exclus de la vente</dt>166              <dd className="break-words text-ink-2">{exc}</dd>167            </div>168          )}169        </dl>170      )}171    </Section>172  );173}174175// --- Bâtiment et terrain ----------------------------------------------------------------176// clés techniques ou déjà montrées ailleurs (faits, courtier, inclusions, prix)177const HIDDEN = new Set([178  "pieces", "price_from", "cover_thumb", "photo_captions", "img_audited", "needs_image_review", "postal_code", "region", "transaction", "prix_pi2", "prix_m2",179  "listing_origin_url", "listed_at", "lot_sqft_source", "year_built_source", "remarques_proprio",180  "Type de propriété", "Année de construction", "Inclusions", "Exclusions", "Éléments inclus lors de la vente", "Éléments exclus lors de la vente", "Inclus", "Exclus",181  "Courtier inscripteur", "Titre du courtier", "Annonce originale", "Adresse", "Région", "À vendre par", "Type vendeur/locateur", "Chambres", "Salles de bain", "Salles de bains",182  "Chambres à coucher", "Salles d'eau", "Visite virtuelle", "Site du projet",183]);184const GROUPS: { key: string; title: string; test: RegExp }[] = [185  { key: "taxes", title: "Taxes et évaluation municipale", test: /tax|evaluation|frais de copropriete|frais communs|cout d'energie/ },186  {187    key: "terrain",188    title: "Terrain et services",189    test: /terrain|topograph|zonage|amenagement|vue|proximite|allee|piscine|stationnement|garage|eau|egout|services|cadastre|\blot\b|facade|profondeur|riverain|cloture|secteur/,190  },191  { key: "batiment", title: "Bâtiment", test: /./ },192];193194function detailGroups(p: Property) {195  const out: Record<string, [string, string][]> = { taxes: [], terrain: [], batiment: [] };196  for (const [k, v] of Object.entries(p.details ?? {})) {197    if (HIDDEN.has(k) || v == null) continue;198    const val = typeof v === "boolean" ? (v ? "Oui" : "") : typeof v === "string" || typeof v === "number" ? String(v).trim().replace(/,\s*$/, "") : "";199    if (!val || /^https?:\/\//.test(val) || val.length > 400) continue;200    const g = GROUPS.find((x) => x.test.test(norm(k)))!;201    out[g.key]!.push([k, val]);202  }203  return out;204}205206const roomsOf = (p: Property): Room[] => (Array.isArray(p.details?.pieces) ? p.details!.pieces!.filter((r) => r && (r.nom || r.dimensions)) : []);207208export function hasBuilding(p: Property) {209  const g = detailGroups(p);210  return g.batiment!.length + g.terrain!.length + g.taxes!.length > 0 || roomsOf(p).length > 0 || !!taxesOf(p) || !!municipalValueOf(p);211}212213function Table({ rows, cols2 }: { rows: [string, string][]; cols2?: boolean }) {214  return (215    <div className={cn("grid gap-x-10", cols2 && "md:grid-cols-2")}>216      {rows.map(([k, v]) => (217        <KV key={k} k={<span className="block max-w-[11rem] whitespace-normal sm:max-w-none">{k}</span>} v={<span className="num">{v}</span>} />218      ))}219    </div>220  );221}222223export function Building({ p }: { p: Property }) {224  const g = useMemo(() => detailGroups(p), [p]);225  const rooms = roomsOf(p);226  const taxes = taxesOf(p);227  const ev = municipalValueOf(p);228  const condo = condoFeesOf(p);229  const [all, setAll] = useState(false);230  if (!hasBuilding(p)) return null;231232  // résumé chiffré des taxes : lu avec tolérance, les libellés bruts restent dessous233  const summary: [string, string][] = [];234  if (taxes?.municipales != null) summary.push([`Taxes municipales${taxes.annee ? ` ${taxes.annee}` : ""}`, `${money(taxes.municipales)} par an`]);235  if (taxes?.scolaires != null) summary.push([`Taxes scolaires${taxes.annee ? ` ${taxes.annee}` : ""}`, `${money(taxes.scolaires)} par an`]);236  if (taxes && taxes.municipales == null && taxes.scolaires == null) summary.push(["Taxes annuelles", `${money(taxes.total)} par an`]);237  if (taxes && taxes.municipales != null && taxes.scolaires != null) summary.push(["Total des taxes", `${money(taxes.total)} par an, soit ${money(taxes.total / 12)} par mois`]);238  if (condo != null) summary.push(["Frais de copropriété", `${money(condo)} par mois`]);239  if (ev) summary.push([`Évaluation municipale${ev.annee ? ` ${ev.annee}` : ""}`, money(ev.total)]);240241  const LIMIT = 10;242  const bat = g.batiment!;243  const shownBat = all ? bat : bat.slice(0, LIMIT);244  return (245    <Section id="batiment" title="Bâtiment et terrain" text="Les renseignements publiés par la source, tels quels.">246      <div className="space-y-8">247        {bat.length > 0 && (248          <div>249            <h3 className="mb-1 text-[1.12rem]">Bâtiment</h3>250            <Table rows={shownBat} cols2 />251            {bat.length > LIMIT && <MoreLink onClick={() => setAll((a) => !a)}>{all ? "Réduire" : `Voir les ${bat.length} renseignements`}</MoreLink>}252          </div>253        )}254        {g.terrain!.length > 0 && (255          <div>256            <h3 className="mb-1 text-[1.12rem]">Terrain et services</h3>257            <Table rows={g.terrain!} cols2 />258          </div>259        )}260        {summary.length > 0 && (261          <div>262            <h3 className="mb-1 text-[1.12rem]">Taxes et évaluation municipale</h3>263            <Table rows={summary} cols2 />264            {ev?.origine === "role" && <p className="mt-2 text-[0.8rem] text-ink-3">Évaluation tirée du rôle apparié à l'adresse ; la source ne la publie pas.</p>}265          </div>266        )}267        {(rooms.length > 0 || g.taxes!.length > 0) && (268          <div className="border-y border-line">269            {rooms.length > 0 && (270              <Disclosure title="Pièces et dimensions" meta={`${rooms.length} pièce${rooms.length > 1 ? "s" : ""}`}>271                <ul className="grid gap-x-10 md:grid-cols-2">272                  {rooms.map((r, i) => (273                    <li key={i} className="flex items-baseline justify-between gap-4 border-b border-line py-2.5">274                      <span className="min-w-0">275                        <span className="block font-medium text-ink">{r.nom || "Pièce"}</span>276                        <span className="block text-[0.8rem] text-ink-3">{[r.niveau, r.revetement].filter(Boolean).join(" · ")}</span>277                      </span>278                      <span className="num shrink-0 text-right text-ink">{r.dimensions || "—"}</span>279                    </li>280                  ))}281                </ul>282              </Disclosure>283            )}284            {g.taxes!.length > 0 && (285              <Disclosure title="Taxes et évaluation, telles que publiées" meta={`${g.taxes!.length}`}>286                <Table rows={g.taxes!} cols2 />287              </Disclosure>288            )}289          </div>290        )}291      </div>292    </Section>293  );294}295
Files main
Menu

Theme