SPB Git

Repository Public

Inventory.tsx 5.1 KB 130 lines tsx

1// Propriétés à vendre d'une agence, d'une bannière ou d'une ville : grille de2// cartes, tri, « Afficher plus », lien vers la carte.34import { useMemo, useState, type ReactNode } from "react";5import { useInfiniteQuery } from "@tanstack/react-query";6import { Map as MapIcon } from "lucide-react";7import { fetchListingsPage, PAGE_SIZE, toCard, type ListingQuery, type ListingSort } from "@/lib/api.annuaires";8import { fmtInt, plural } from "@/lib/format";9import { Stagger } from "@/lib/motion";10import { BrandEmptyState } from "@/brand/compat";11import { ListingCard, ListingCardSkeleton } from "@/components/ListingCard";12import { buttonClass, ButtonLink } from "@/ui/primitives";13import { ErrorState, SectionHead, SortSelect } from "./shared";1415const SORTS: { value: ListingSort; label: string }[] = [16  { value: "recent", label: "Plus récentes" },17  { value: "price_asc", label: "Prix croissant" },18  { value: "price_desc", label: "Prix décroissant" },19];2021const GRID = "grid grid-cols-1 gap-x-5 gap-y-8 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4";2223/** Adresse de la recherche sur carte pour un filtre (mêmes noms de paramètres que l'API). */24export function mapHref(q: ListingQuery): string {25  const u = new URLSearchParams();26  if (q.source) u.set("source", q.source);27  if (q.agency) u.set("agency", q.agency);28  if (q.city) u.set("city", q.city);29  if (q.property_type) u.set("property_type", q.property_type);30  const s = u.toString();31  return s ? `/recherche?${s}` : "/recherche";32}3334export function Inventory({35  id = "proprietes-titre",36  title = "Propriétés à vendre",37  query,38  known,39  hideMap,40  filters,41  emptyTitle = "Aucune propriété affichée en ce moment",42  emptyText,43  emptyAction,44}: {45  id?: string;46  title?: string;47  query: ListingQuery;48  /** compte déjà connu : réserve le sous-titre avant la réponse */49  known?: number;50  /** la page offre déjà le lien vers la carte dans son en-tête */51  hideMap?: boolean;52  /** filtres propres à la page (parts d'inventaire, types de propriété) */53  filters?: ReactNode;54  emptyTitle?: string;55  emptyText: string;56  emptyAction?: ReactNode;57}) {58  const [sort, setSort] = useState<ListingSort>("recent");59  const key = [query.source ?? "", query.agency ?? "", query.city ?? "", query.property_type ?? ""].join("|");60  const q = useInfiniteQuery({61    queryKey: ["ik-inventaire", key, sort],62    queryFn: ({ pageParam, signal }) => fetchListingsPage({ ...query, sort }, pageParam, signal),63    initialPageParam: 0,64    getNextPageParam: (last) => (last.offset + last.listings.length < last.total && last.listings.length > 0 ? last.offset + PAGE_SIZE : undefined),65    staleTime: 12e4,66  });67  const listings = useMemo(() => {68    // une inscription peut glisser d'une page à l'autre entre deux requêtes69    const seen = new Set<string>();70    return (q.data?.pages.flatMap((p) => p.listings) ?? []).filter((l) => (seen.has(l.uid) ? false : (seen.add(l.uid), true)));71  }, [q.data]);72  const total = q.data?.pages[0]?.total ?? known;7374  return (75    <section aria-labelledby={id}>76      <SectionHead77        id={id}78        title={title}79        text={<span className="num">{total != null ? plural(total, "inscription active", "inscriptions actives") : " "}</span>}80        aside={81          <div className="flex w-full flex-wrap items-center gap-2 sm:w-auto">82            <SortSelect value={sort} onChange={setSort} options={SORTS} />83            {!hideMap && (84              <ButtonLink to={mapHref(query)} variant="outline" className="flex-1 sm:flex-none">85                <MapIcon className="size-4" /> Voir sur la carte86              </ButtonLink>87            )}88          </div>89        }90      />91      {filters && <div className="mt-5">{filters}</div>}9293      <div className="mt-6">94        {q.isError ? (95          <ErrorState onRetry={() => q.refetch()} />96        ) : q.isPending ? (97          <div className={GRID}>98            {Array.from({ length: 8 }, (_, i) => (99              <ListingCardSkeleton key={i} />100            ))}101          </div>102        ) : listings.length === 0 ? (103          <BrandEmptyState kind="closed" title={emptyTitle} text={emptyText} action={emptyAction} />104        ) : (105          <>106            <Stagger resetKey={`${key}|${sort}`} className={GRID}>107              {listings.map((l, i) => (108                <ListingCard key={l.uid} listing={toCard(l)} eager={i < 4} />109              ))}110              {q.isFetchingNextPage && Array.from({ length: 4 }, (_, i) => <ListingCardSkeleton key={`s${i}`} />)}111            </Stagger>112            {q.hasNextPage && (113              <div className="mt-9 flex flex-col items-center gap-2">114                <button type="button" onClick={() => q.fetchNextPage()} disabled={q.isFetchingNextPage} className={buttonClass("outline", "lg")}>115                  {q.isFetchingNextPage ? "Chargement…" : "Afficher plus de propriétés"}116                </button>117                {total != null && (118                  <span className="num text-[0.8rem] text-ink-3">119                    {fmtInt(listings.length)} sur {fmtInt(total)}120                  </span>121                )}122              </div>123            )}124          </>125        )}126      </div>127    </section>128  );129}130
Files main
Menu

Theme