SPB Git

Repository Public

Favorites.tsx 20.6 KB 466 lines tsx

1// Favoris : tout reste sur l'appareil (aucun compte). Les propriétés enregistrées2// sont revérifiées en arrière-plan pour signaler un retrait ou une baisse de prix.34import { useMemo, useRef, useState } from "react";5import { Link } from "react-router";6import { useQueries } from "@tanstack/react-query";7import { ArrowRight, Download, Scale, Trash2, Upload, X } from "lucide-react";8import { fetchProperty, priceOk, propertyKey, propertyPlace, vraiPrixVerdict, type Property } from "@/lib/api.marche";9import { cn } from "@/lib/cn";10import { fmtAgo, fmtInt, fmtMoney, fmtPct, plural } from "@/lib/format";11import { useTitle } from "@/lib/hooks";12import { Stagger } from "@/lib/motion";13import {14  removeSearch,15  setFavoriteNote,16  toggleCompare,17  toggleFavorite,18  useCompare,19  useFavorites,20  useSavedSearches,21  useSeen,22  type SavedListing,23} from "@/lib/store";24import { BrandEmptyState, doorClick, getMotionPref, listingPath, preloadListing, setMotionPref } from "@/brand/compat";25import { SmartImage } from "@/components/SmartImage";26import { Chapter, PageHero } from "@/components/marche-ik/layout";27import { CardRow, PHOTO_TAG, PropertyCard, PropertyCardSkeleton, VERDICT_TEXT } from "@/components/marche-ik/PropertyCard";28import { sourceLabel, useSourceLabels } from "@/components/marche-ik/sources";29import { Button, ButtonLink, Segmented } from "@/ui/primitives";30import { toast } from "@/ui/toast";3132type Sort = "recent" | "prix" | "prix_desc";33type Live = { state: "loading" | "ok" | "gone" | "unknown"; listing?: Property };34type MotionPref = Parameters<typeof setMotionPref>[0];3536/** Type de propriété de l'instantané (le champ a changé de nom entre les versions du magasin). */37const savedType = (it: SavedListing): string => (it as SavedListing & { property_type?: string }).property_type || it.unit_type || "";3839const isGone = (e: unknown) => e instanceof Error && /\b(404|410)\b/.test(e.message);4041function FavoriteCard({ item, live }: { item: SavedListing; live: Live }) {42  const names = useSourceLabels();43  const inCompare = useCompare().includes(item.uid);44  const [editing, setEditing] = useState(false);45  const [draft, setDraft] = useState(item.note ?? "");46  const l = live.listing;47  const gone = live.state === "gone";48  const price = l && priceOk(l.price) ? l.price : item.price;49  const drop = l && priceOk(l.price) && priceOk(item.price) && l.price < item.price ? item.price - l.price : 0;50  const rise = l && priceOk(l.price) && priceOk(item.price) && l.price > item.price ? l.price - item.price : 0;51  const title = item.address || item.title || "Propriété à vendre";52  const place = propertyPlace(item);53  const image = l?.images?.[0] ?? item.image;54  const v = l && !gone ? vraiPrixVerdict(l.price, l.vraiprix?.value, l.vraiprix?.low, l.vraiprix?.high) : null;5556  const save = () => {57    setFavoriteNote(item.uid, draft.trim());58    setEditing(false);59  };6061  return (62    <div className="flex flex-col">63      <Link64        to={listingPath(item.uid)}65        onClick={(e) => doorClick(e, { uid: item.uid, image, context: "favorite" })}66        onMouseEnter={() => preloadListing(item.uid)}67        aria-label={`${priceOk(price) ? fmtMoney(price) + ", " : ""}${place || title}. Ouvrir la propriété.`}68        className="group block outline-none"69      >70        <div data-door-source className="relative aspect-[4/3] overflow-hidden rounded-xl bg-surface-2">71          <SmartImage src={image} alt="" className={cn("absolute inset-0 size-full", gone && "opacity-45 grayscale")} />72          <div className="absolute left-2.5 top-2.5 flex flex-wrap gap-1.5 pr-2.5">73            {gone ? (74              <span className={cn(PHOTO_TAG, "text-high")}>N'est plus en ligne</span>75            ) : (76              v &&77              v.verdict !== "marche" && (78                <span className={cn(PHOTO_TAG, VERDICT_TEXT[v.verdict].tone)}>79                  {VERDICT_TEXT[v.verdict].label} <span className="font-medium">{fmtPct(v.deviation)}</span>80                </span>81              )82            )}83            {drop > 0 && <span className={cn(PHOTO_TAG, "text-good")}>Baisse de prix de {fmtMoney(drop)}</span>}84          </div>85        </div>86        <div className="pt-3">87          <div className="flex items-baseline justify-between gap-3">88            <p className="num whitespace-nowrap text-[1.06rem] font-semibold leading-tight">89              {priceOk(price) ? fmtMoney(price) : <span className="text-[0.95rem] font-medium text-ink-2">Prix sur demande</span>}90            </p>91            {(drop > 0 || rise > 0) && priceOk(item.price) && (92              <span className="num truncate text-[0.78rem] text-ink-3">93                était <span className="line-through">{fmtMoney(item.price)}</span>94              </span>95            )}96          </div>97          <p className="mt-1 truncate text-[0.9rem] text-ink group-hover:text-brand">{[savedType(item), place || title].filter(Boolean).join(" · ")}</p>98          <p className="mt-0.5 truncate text-[0.82rem] text-ink-3">99            {sourceLabel(item.source, names)} · enregistrée {fmtAgo(item.savedAt / 1000)}100          </p>101        </div>102      </Link>103104      {editing ? (105        <div className="mt-2.5">106          <textarea107            autoFocus108            value={draft}109            onChange={(e) => setDraft(e.target.value)}110            onKeyDown={(e) => {111              if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) save();112              if (e.key === "Escape") setEditing(false);113            }}114            rows={3}115            maxLength={500}116            placeholder="Visite prévue, questions pour le courtier, impressions…"117            aria-label="Note personnelle"118            className="w-full resize-none rounded-[10px] border border-line-2 bg-surface p-3 text-[1rem] text-ink outline-none placeholder:text-ink-3 focus:border-brand sm:text-[0.88rem]"119          />120          <div className="mt-2 flex justify-end gap-2">121            <Button size="sm" variant="ghost" onClick={() => setEditing(false)}>122              Annuler123            </Button>124            <Button size="sm" variant="primary" onClick={save}>125              Enregistrer126            </Button>127          </div>128        </div>129      ) : (130        <button131          type="button"132          onClick={() => {133            setDraft(item.note ?? "");134            setEditing(true);135          }}136          className={cn(137            "mt-2.5 min-h-11 w-full border-l-2 py-1.5 pl-3 text-left text-[0.86rem] leading-relaxed transition-colors duration-150",138            item.note ? "border-brand text-ink-2 hover:text-ink" : "border-line-2 text-ink-3 hover:border-ink-3 hover:text-ink-2",139          )}140        >141          <span className="line-clamp-3 whitespace-pre-line">{item.note || "Ajouter une note"}</span>142        </button>143      )}144145      <div className="mt-1.5 flex items-center gap-1 text-[0.82rem]">146        <button147          type="button"148          aria-pressed={inCompare}149          disabled={gone}150          onClick={() => {151            const r = toggleCompare(item.uid);152            toast(r === "full" ? "Le comparateur contient déjà 4 propriétés" : r === "added" ? "Ajoutée au comparateur" : "Retirée du comparateur");153          }}154          className={cn(155            "-ml-2 inline-flex h-11 items-center gap-1.5 rounded-[8px] px-2 transition-colors duration-150 hover:bg-surface-2 disabled:opacity-40",156            inCompare ? "font-medium text-brand" : "text-ink-2",157          )}158        >159          <Scale className="size-4" />160          {inCompare ? "Dans le comparateur" : "Comparer"}161        </button>162        <button163          type="button"164          onClick={(e) => {165            const card = e.currentTarget.parentElement?.parentElement;166            const done = () => {167              toggleFavorite(item);168              toast("Retirée des favoris", { label: "Annuler", run: () => toggleFavorite(item) });169            };170            // retrait : la carte s'efface brièvement avant de disparaître171            const a = card?.animate?.([{ opacity: 1 }, { opacity: 0 }], { duration: 150, easing: "ease-out" });172            if (a) a.onfinish = done;173            else done();174          }}175          className="ml-auto inline-flex h-11 items-center gap-1.5 rounded-[8px] px-2 text-ink-3 transition-colors duration-150 hover:bg-surface-2 hover:text-bad"176        >177          <Trash2 className="size-4" />178          Retirer179        </button>180      </div>181    </div>182  );183}184185function SavedSearches() {186  const searches = useSavedSearches();187  return (188    <section className="container-x pt-14">189      <Chapter190        title="Recherches enregistrées"191        text={searches.length ? undefined : "Sur la carte, le signet à côté du tri garde vos filtres et votre zone. Vous retrouverez ici vos recherches, prêtes à relancer."}192        action={193          !searches.length && (194            <Link to="/recherche" className="group inline-flex min-h-11 items-center gap-1.5 text-[0.9rem] font-medium text-brand">195              Ouvrir la carte <ArrowRight className="size-4 transition-transform duration-150 group-hover:translate-x-0.5" />196            </Link>197          )198        }199      />200      {searches.length > 0 && (201        <ul className="mt-2 grid gap-x-12 sm:grid-cols-2">202          {searches.map((s) => (203            <li key={s.id} className="flex min-w-0 items-center gap-2 border-b border-line">204              <Link to={`/recherche?${s.query}`} className="group flex min-w-0 flex-1 flex-col gap-x-4 gap-y-0.5 py-3 sm:flex-row sm:items-baseline sm:justify-between sm:py-3.5">205                <span className="truncate text-[0.98rem] group-hover:text-brand">{s.label}</span>206                <span className="num truncate text-[0.82rem] text-ink-3 sm:shrink-0">207                  {s.lastTotal != null ? `${fmtInt(s.lastTotal)} propriétés · ` : ""}208                  {fmtAgo(s.savedAt / 1000)}209                </span>210              </Link>211              <button212                type="button"213                aria-label={`Supprimer la recherche ${s.label}`}214                onClick={() => removeSearch(s.id)}215                className="grid size-11 shrink-0 place-items-center rounded-full text-ink-3 transition-colors duration-150 hover:bg-surface-2 hover:text-ink"216              >217                <X className="size-4" />218              </button>219            </li>220          ))}221        </ul>222      )}223    </section>224  );225}226227/** Les dernières propriétés ouvertes (mémoire locale « vus »), hors favoris : 8 au plus. */228function RecentlySeen({ exclude }: { exclude: Record<string, unknown> }) {229  const seen = useSeen();230  const names = useSourceLabels();231  const uids = useMemo(232    () =>233      Object.entries(seen)234        .filter(([uid]) => !exclude[uid])235        .sort((a, b) => b[1] - a[1])236        .slice(0, 8)237        .map(([uid]) => uid),238    [seen, exclude],239  );240  const queries = useQueries({241    queries: uids.map((uid) => ({ queryKey: propertyKey(uid), queryFn: () => fetchProperty(uid), staleTime: 5 * 60_000, retry: false })),242  });243  const rows = uids.map((uid, i) => ({ uid, q: queries[i] })).filter((r) => r.q && (r.q.isPending || r.q.data));244  if (!rows.length) return null;245  return (246    <section className="container-x pt-14">247      <Chapter title="Récemment consultées" text="Les dernières propriétés que vous avez ouvertes sur cet appareil." />248      <CardRow className="mt-6">249        {rows.map(({ uid, q }) => {250          const p = q?.data;251          if (!p) return <PropertyCardSkeleton key={uid} />;252          const v = vraiPrixVerdict(p.price, p.vraiprix?.value, p.vraiprix?.low, p.vraiprix?.high);253          return (254            <PropertyCard255              key={uid}256              uid={uid}257              image={p.images[0]}258              price={p.price}259              verdict={v?.verdict}260              deviation={v?.deviation}261              context="favorite"262              line={[p.property_type, propertyPlace(p) || p.address].filter(Boolean).join(" · ")}263              meta={[p.bedrooms ? `${p.bedrooms} ch.` : null, p.bathrooms ? `${p.bathrooms} sdb` : null, sourceLabel(p.source, names)].filter(Boolean).join(" · ")}264            />265          );266        })}267      </CardRow>268    </section>269  );270}271272const MOTION: { value: MotionPref; label: string }[] = [273  { value: "auto", label: "Automatique" },274  { value: "compact", label: "Discrètes" },275  { value: "none", label: "Aucune" },276];277278function Settings({ onExport, onImport, canExport }: { onExport: () => void; onImport: () => void; canExport: boolean }) {279  const [pref, setPref] = useState<MotionPref>(getMotionPref());280  const current = MOTION.some((m) => m.value === pref) ? pref : "auto";281  return (282    <section className="container-x pt-14">283      <Chapter title="Sur cet appareil" />284      <div className="mt-2 grid gap-x-12 lg:grid-cols-2">285        <div className="border-b border-line py-5">286          <h3 className="font-sans text-[0.95rem] font-medium tracking-normal">Animations d'ouverture</h3>287          <p className="mt-1 text-[0.86rem] leading-relaxed text-ink-3">288            La porte qui s'ouvre quand vous choisissez une propriété. En automatique, elle raccourcit à mesure que vous consultez des inscriptions.289          </p>290          <Segmented291            className="mt-3"292            value={current}293            onChange={(v) => {294              setMotionPref(v);295              setPref(v);296            }}297            label="Animations d'ouverture"298            options={MOTION}299          />300        </div>301        <div className="border-b border-line py-5">302          <h3 className="font-sans text-[0.95rem] font-medium tracking-normal">Sauvegarde</h3>303          <p className="mt-1 text-[0.86rem] leading-relaxed text-ink-3">304            Rien ne quitte votre appareil : favoris, notes et recherches sont gardés dans ce navigateur, sans compte. Exportez-les pour les retrouver ailleurs.305          </p>306          <div className="mt-3 flex flex-wrap gap-2.5">307            <Button variant="outline" onClick={onExport} disabled={!canExport}>308              <Download className="size-4" /> Exporter309            </Button>310            <Button variant="outline" onClick={onImport}>311              <Upload className="size-4" /> Importer312            </Button>313          </div>314        </div>315      </div>316    </section>317  );318}319320export default function Favorites() {321  useTitle("Mes favoris");322  const favorites = useFavorites();323  const [sort, setSort] = useState<Sort>("recent");324  const file = useRef<HTMLInputElement>(null);325  const items = useMemo(() => Object.values(favorites), [favorites]);326327  // revérification en arrière-plan de chaque favori328  const queries = useQueries({329    queries: items.map((it) => ({ queryKey: propertyKey(it.uid), queryFn: () => fetchProperty(it.uid), staleTime: 5 * 60_000, retry: false })),330  });331  const stamp = queries.map((q) => q.status + (q.dataUpdatedAt ?? 0)).join("|");332  const live = useMemo(() => {333    const m: Record<string, Live> = {};334    items.forEach((it, i) => {335      const q = queries[i];336      if (!q || q.isPending) m[it.uid] = { state: "loading" };337      else if (q.data) m[it.uid] = { state: q.data.active === 0 ? "gone" : "ok", listing: q.data };338      else m[it.uid] = { state: isGone(q.error) ? "gone" : "unknown" };339    });340    return m;341    // les résultats changent d'identité à chaque rendu : on suit leurs états342    // eslint-disable-next-line react-hooks/exhaustive-deps343  }, [items, stamp]);344345  const sorted = useMemo(() => {346    const cur = (it: SavedListing) => {347      const p = live[it.uid]?.listing?.price ?? it.price;348      return priceOk(p) ? p : null;349    };350    const arr = [...items];351    if (sort === "recent") arr.sort((a, b) => b.savedAt - a.savedAt);352    else arr.sort((a, b) => (sort === "prix" ? (cur(a) ?? Infinity) - (cur(b) ?? Infinity) : (cur(b) ?? -Infinity) - (cur(a) ?? -Infinity)));353    return arr;354  }, [items, sort, live]);355356  const gone = items.filter((it) => live[it.uid]?.state === "gone").length;357  const drops = items.filter((it) => {358    const l = live[it.uid]?.listing;359    return l && priceOk(l.price) && priceOk(it.price) && l.price < it.price;360  }).length;361  const checking = items.some((it) => live[it.uid]?.state === "loading");362363  const exportJson = () => {364    const blob = new Blob([JSON.stringify({ app: "immo-ka", version: 2, exportedAt: new Date().toISOString(), favoris: items }, null, 2)], { type: "application/json" });365    const a = document.createElement("a");366    a.href = URL.createObjectURL(blob);367    a.download = `immo-ka-favoris-${new Date().toISOString().slice(0, 10)}.json`;368    a.click();369    URL.revokeObjectURL(a.href);370  };371372  const importJson = async (f: File | undefined) => {373    if (!f) return;374    try {375      const data = JSON.parse(await f.text()) as { favoris?: unknown };376      const list = Array.isArray(data) ? data : Array.isArray(data.favoris) ? data.favoris : null;377      if (!list) throw new Error("format");378      let n = 0;379      for (const raw of list as (Partial<SavedListing> & { property_type?: string })[]) {380        if (!raw || typeof raw.uid !== "string" || favorites[raw.uid]) continue;381        const item = {382          uid: raw.uid,383          title: String(raw.title ?? ""),384          address: String(raw.address ?? ""),385          city: String(raw.city ?? ""),386          sector: String(raw.sector ?? ""),387          unit_type: String(raw.unit_type ?? raw.property_type ?? ""),388          property_type: String(raw.property_type ?? raw.unit_type ?? ""),389          price: typeof raw.price === "number" ? raw.price : null,390          image: typeof raw.image === "string" ? raw.image : null,391          source: String(raw.source ?? raw.uid.split(":")[0] ?? ""),392          savedAt: typeof raw.savedAt === "number" ? raw.savedAt : Date.now(),393        } as SavedListing;394        toggleFavorite(item);395        if (typeof raw.note === "string" && raw.note) setFavoriteNote(item.uid, raw.note.slice(0, 500));396        n += 1;397      }398      toast(n ? plural(n, "favori importé", "favoris importés") : "Aucun nouveau favori dans ce fichier");399    } catch {400      toast("Ce fichier n'est pas une sauvegarde de favoris Immo-Ka");401    } finally {402      if (file.current) file.current.value = "";403    }404  };405406  return (407    <>408      <PageHero409        eyebrow="Mes favoris"410        title={items.length ? `${plural(items.length, "propriété mise", "propriétés mises")} de côté` : "Vos propriétés mises de côté"}411        text="Gardées sur cet appareil, sans compte. Chaque favori est revérifié pour signaler une baisse de prix ou un retrait."412      />413      <input ref={file} type="file" accept="application/json,.json" className="hidden" onChange={(e) => importJson(e.target.files?.[0])} />414415      <section className="container-x">416        {items.length === 0 ? (417          <div className="border-y border-line">418            <BrandEmptyState419              kind="heart"420              title="Aucun favori pour l'instant"421              text="Touchez le cœur sur une propriété pour la garder ici. Vous pourrez y ajouter une note, la comparer à d'autres et voir si son prix baisse."422              action={423                <ButtonLink to="/recherche" variant="primary">424                  Explorer la carte425                </ButtonLink>426              }427            />428          </div>429        ) : (430          <>431            <div className="flex flex-wrap items-center justify-between gap-3 border-t border-line pt-5">432              <p className="num min-h-6 text-[0.88rem] text-ink-3" aria-live="polite">433                {drops > 0 && <span className="font-medium text-good">{plural(drops, "baisse de prix", "baisses de prix")}</span>}434                {drops > 0 && gone > 0 && " · "}435                {gone > 0 && <span className="text-high">{plural(gone, "inscription retirée", "inscriptions retirées")}</span>}436                {!drops && !gone && (checking ? "Vérification des inscriptions…" : "Aucun changement depuis l'enregistrement.")}437              </p>438              <div className="no-scrollbar -mx-1 max-w-full overflow-x-auto px-1">439                <Segmented440                  value={sort}441                  onChange={setSort}442                  label="Trier les favoris"443                  options={[444                    { value: "recent", label: "Récents" },445                    { value: "prix", label: "Prix croissant" },446                    { value: "prix_desc", label: "Prix décroissant" },447                  ]}448                />449              </div>450            </div>451            <Stagger resetKey={sort} className="mt-6 grid grid-cols-1 gap-x-5 gap-y-9 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">452              {sorted.map((it) => (453                <FavoriteCard key={it.uid} item={it} live={live[it.uid] ?? { state: "loading" }} />454              ))}455            </Stagger>456          </>457        )}458      </section>459460      <SavedSearches />461      <RecentlySeen exclude={favorites} />462      <Settings onExport={exportJson} onImport={() => file.current?.click()} canExport={items.length > 0} />463    </>464  );465}466
Files main
Menu

Theme