SPB Git

Repository Public

shared.tsx 11.3 KB 305 lines tsx

1// Briques communes aux pages d'annuaire (gestionnaires, villes, sources, déménageurs).2// Index typographiques : des lignes à filet, denses et lisibles, plutôt que des murs de cartes.34import { useEffect, useRef, useState, type ReactNode } from "react";5import { Link } from "react-router";6import { ArrowRight, RotateCw, Search, Star, X } from "lucide-react";7import { cn } from "@/lib/cn";8import { slugify } from "@/lib/format";9import { LoukaEmptyState } from "@/brand/EmptyState";10import { Button } from "@/ui/primitives";1112/** Texte normalisé pour la recherche (sans accents ni ponctuation). */13export const norm = (s: string | null | undefined) => slugify(s ?? "").replace(/-/g, " ");1415/** Région principale d'un libellé composite (« Montérégie (Granby) », « Laurentides / Lanaudière »). */16export function regionKey(region: string | null | undefined): string {17  const r = (region ?? "").split("/")[0]!.split("(")[0]!.split("—")[0]!.trim();18  if (!r) return "Autres";19  if (r === "Province") return "Tout le Québec";20  if (r === "Grand Montréal") return "Montréal";21  if (r === "Québec") return "Capitale-Nationale";22  return r;23}2425/** Adresse web lisible : « https://www.cogir.net/fr » → « cogir.net ». */26export function prettyHost(url: string | null | undefined): string {27  if (!url) return "";28  try {29    return new URL(url).hostname.replace(/^www\./, "");30  } catch {31    return url.replace(/^https?:\/\/(www\.)?/, "").split("/")[0] ?? url;32  }33}3435/** Numéro composable pour un lien tel: */36export const telHref = (phone: string) => `tel:${phone.replace(/[^\d+]/g, "")}`;3738// --- En-tête de page -----------------------------------------------------------39/** En-tête sobre : sur-titre, titre serif, une phrase, puis les faits en ligne. */40export function PageHead({41  eyebrow,42  title,43  text,44  facts,45  aside,46  back,47  children,48}: {49  eyebrow?: ReactNode;50  title: ReactNode;51  text?: ReactNode;52  /** chiffres clés ; `null` ou `false` pendant le chargement : la place est réservée */53  facts?: { value: ReactNode; label: string }[] | null | false;54  aside?: ReactNode;55  back?: { to: string; label: string };56  children?: ReactNode;57}) {58  return (59    <header className="container-x pb-6 pt-5 lg:pb-7 lg:pt-10">60      {back && (61        <Link to={back.to} className="mb-3 inline-flex min-h-11 items-center gap-1.5 text-[0.88rem] text-ink-3 transition-colors duration-150 hover:text-ink">62          <ArrowRight className="size-4 rotate-180" /> {back.label}63        </Link>64      )}65      <div className="flex flex-wrap items-end justify-between gap-x-10 gap-y-5">66        <div className="min-w-0 max-w-2xl">67          {eyebrow && <div className="eyebrow">{eyebrow}</div>}68          <h1 className={cn("text-[1.85rem] leading-[1.08] sm:text-[2.5rem]", !!eyebrow && "mt-2.5")}>{title}</h1>69          {text && <p className="mt-2.5 text-[0.95rem] leading-relaxed text-ink-2 sm:text-[1rem]">{text}</p>}70        </div>71        {aside}72      </div>73      {facts ? <Facts items={facts} className="mt-5" /> : facts === undefined ? null : <div aria-hidden className="mt-5 min-h-[7.75rem] border-t border-line pt-4 sm:min-h-[2.6rem]" />}74      {children}75    </header>76  );77}7879/** Faits réels en ligne discrète : valeur tabulaire, libellé en pierre. */80export function Facts({ items, className }: { items: { value: ReactNode; label: string }[]; className?: string }) {81  return (82    <dl className={cn("grid min-h-[7.75rem] grid-cols-2 content-start gap-x-6 gap-y-2.5 border-t border-line pt-4 sm:flex sm:min-h-0 sm:flex-wrap sm:gap-x-9", className)}>83      {items.map((it) => (84        <div key={it.label} className="flex min-w-0 flex-col sm:flex-row sm:items-baseline sm:gap-2">85          <dd className="num text-[1.05rem] font-semibold text-ink">{it.value}</dd>86          <dt className="text-[0.84rem] leading-snug text-ink-3">{it.label}</dt>87        </div>88      ))}89    </dl>90  );91}9293/** En-tête de section (même motif que l'accueil). */94export function SectionHead({95  id,96  title,97  text,98  to,99  cta,100  aside,101}: {102  id?: string;103  title: ReactNode;104  text?: ReactNode;105  to?: string;106  cta?: string;107  aside?: ReactNode;108}) {109  return (110    <div className="flex flex-wrap items-end justify-between gap-x-8 gap-y-3 border-t border-line pt-7">111      <div className="min-w-0">112        <h2 id={id} className="scroll-mt-24 text-[1.5rem] sm:text-[1.75rem]">113          {title}114        </h2>115        {text && <p className="mt-1 max-w-xl text-[0.94rem] text-ink-3">{text}</p>}116      </div>117      {to && cta && (118        <Link to={to} className="group inline-flex min-h-11 items-center gap-1.5 text-[0.9rem] font-medium text-brand">119          {cta} <ArrowRight className="size-4 transition-transform duration-150 group-hover:translate-x-0.5" />120        </Link>121      )}122      {aside}123    </div>124  );125}126127// --- Champ de recherche ---------------------------------------------------------128export function SearchField({129  value,130  onChange,131  placeholder,132  className,133}: {134  value: string;135  onChange: (v: string) => void;136  placeholder: string;137  className?: string;138}) {139  return (140    <div className={cn("relative", className)}>141      <Search className="pointer-events-none absolute left-3.5 top-1/2 size-[18px] -translate-y-1/2 text-ink-3" />142      <input143        type="search"144        value={value}145        onChange={(e) => onChange(e.target.value)}146        placeholder={placeholder}147        aria-label={placeholder}148        autoComplete="off"149        className="field !pl-10 !pr-10 text-[0.95rem] [&::-webkit-search-cancel-button]:hidden"150      />151      {value && (152        <button153          type="button"154          aria-label="Effacer la recherche"155          onClick={() => onChange("")}156          className="absolute right-0 top-1/2 grid size-11 -translate-y-1/2 place-items-center rounded-full text-ink-3 hover:text-ink"157        >158          <X className="size-4" />159        </button>160      )}161    </div>162  );163}164165/** Menu de tri natif. */166export function SortSelect<T extends string>({167  value,168  onChange,169  options,170  label = "Trier",171}: {172  value: T;173  onChange: (v: T) => void;174  options: { value: T; label: string }[];175  label?: string;176}) {177  return (178    <label className="relative inline-flex h-11 shrink-0 items-center gap-1.5 rounded-[10px] border border-line-2 bg-surface pl-3.5 pr-9 text-[0.88rem] text-ink">179      <span className="text-ink-3">{label}</span>180      <span className="font-medium">{options.find((o) => o.value === value)?.label}</span>181      <select182        value={value}183        onChange={(e) => onChange(e.target.value as T)}184        aria-label={label}185        className="absolute inset-0 cursor-pointer appearance-none opacity-0"186      >187        {options.map((o) => (188          <option key={o.value} value={o.value}>189            {o.label}190          </option>191        ))}192      </select>193      <svg viewBox="0 0 24 24" className="pointer-events-none absolute right-3 size-4 text-ink-3" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>194        <path d="m6 9 6 6 6-6" strokeLinecap="round" strokeLinejoin="round" />195      </svg>196    </label>197  );198}199200/** Rangée de filtres : défilable horizontalement sur mobile, à la ligne sur grand écran. */201export function ChipRow({ children, className, label }: { children: ReactNode; className?: string; label?: string }) {202  return (203    <div className="-mx-[clamp(1rem,4vw,2.5rem)] lg:mx-0" role="group" aria-label={label}>204      <div className={cn("no-scrollbar flex gap-1.5 overflow-x-auto px-[clamp(1rem,4vw,2.5rem)] lg:flex-wrap lg:px-0", className)}>{children}</div>205    </div>206  );207}208209/** Filtre à bascule, net, avec compte optionnel. */210export function FilterTab({ active, onClick, children, count }: { active: boolean; onClick: () => void; children: ReactNode; count?: number }) {211  return (212    <button213      type="button"214      aria-pressed={active}215      onClick={onClick}216      className={cn(217        "inline-flex h-11 shrink-0 items-center gap-1.5 rounded-[8px] border px-3 text-[0.86rem] transition-colors duration-150 lg:h-9",218        active ? "border-ink bg-ink font-medium text-bg" : "border-line-2 bg-surface text-ink-2 hover:border-ink-3 hover:text-ink",219      )}220    >221      {children}222      {count != null && <span className={cn("num text-[0.78rem]", active ? "opacity-70" : "text-ink-3")}>{count}</span>}223    </button>224  );225}226227// --- Note ------------------------------------------------------------------------228/** Note Google : une étoile, la valeur, le nombre d'avis. Factuel, sans rangée d'étoiles dorées. */229export function Rating({ value, reviews, className }: { value: number | null | undefined; reviews?: number | null; className?: string }) {230  if (value == null) return null;231  const txt = value.toFixed(1).replace(".", ",");232  return (233    <span234      className={cn("num inline-flex items-center gap-1 whitespace-nowrap text-[0.86rem]", className)}235      role="img"236      aria-label={`Note ${txt} sur 5${reviews != null ? `, ${reviews} avis` : ""}`}237    >238      <Star className="size-3.5 text-ink-3" fill="currentColor" strokeWidth={0} />239      <span className="font-medium text-ink">{txt}</span>240      {reviews != null && <span className="text-ink-3">({reviews})</span>}241    </span>242  );243}244245// --- Rendu progressif d'une longue liste ----------------------------------------246/** Renvoie le nombre d'éléments à afficher et la sentinelle à placer en bas de247 *  liste : la tranche suivante s'ajoute à l'approche du bas. */248export function useProgressive(total: number, resetKey: string, step = 60) {249  const [count, setCount] = useState(step);250  const ref = useRef<HTMLDivElement>(null);251  useEffect(() => setCount(step), [resetKey, step]);252  useEffect(() => {253    const el = ref.current;254    if (!el || count >= total) return;255    const io = new IntersectionObserver(256      (entries) => entries.some((e) => e.isIntersecting) && setCount((c) => Math.min(total, c + step)),257      { rootMargin: "900px" },258    );259    io.observe(el);260    return () => io.disconnect();261  }, [count, total, step]);262  return { count: Math.min(count, total), sentinel: <div ref={ref} className="h-px" aria-hidden /> };263}264265// --- États ----------------------------------------------------------------------266export function ErrorState({ onRetry, text }: { onRetry?: () => void; text?: string }) {267  return (268    <LoukaEmptyState269      kind="closed"270      title="Chargement impossible"271      text={text ?? "Les données n'ont pas pu être récupérées. Vérifiez votre connexion, puis réessayez."}272      action={273        onRetry && (274          <Button variant="outline" onClick={onRetry}>275            <RotateCw className="size-4" /> Réessayer276          </Button>277        )278      }279    />280  );281}282283/** Lignes fantômes pendant un chargement réel. */284export function RowsSkeleton({ rows = 10 }: { rows?: number }) {285  return (286    <ul aria-hidden>287      {Array.from({ length: rows }, (_, i) => (288        <li key={i} className="flex items-center justify-between gap-6 border-b border-line py-4">289          <div className="skeleton h-5" style={{ width: `${28 + ((i * 17) % 30)}%` }} />290          <div className="skeleton h-4 w-24" />291        </li>292      ))}293    </ul>294  );295}296297/** Barre d'outils (recherche + filtres), collante sous l'en-tête du site sur grand écran. */298export function Toolbar({ children }: { children: ReactNode }) {299  return (300    <div className="z-30 border-y border-line bg-bg lg:sticky lg:top-16">301      <div className="container-x space-y-2.5 py-3">{children}</div>302    </div>303  );304}305
Files main
Menu

Theme