SPB Git

Repository Public

kit.tsx 10.1 KB 153 lines tsx

1"use client";2import { useId, type ReactNode } from "react";3import { Icon } from "@/components/ui/Icon";45export type Tone = "active" | "ok" | "warn" | "bad" | "dim";6export interface FlowNode { id: string; x: number; y: number; w?: number; h?: number; label: string; sub?: string; shape?: "rect" | "diamond" | "pill" }7export interface FlowEdge { from: string; to: string; label?: string; dashed?: boolean; /** Vertical offset of the label. */ dy?: number }89const NODE_W = 132, NODE_H = 50;10const box = (n: FlowNode) => ({ w: n.w ?? NODE_W, h: n.h ?? NODE_H });1112/** Point where the segment from the centre of `a` towards `b` leaves the rectangle of `a`. */13function edgePoint(a: FlowNode, b: FlowNode): [number, number] {14  const { w, h } = box(a), dx = b.x - a.x, dy = b.y - a.y;15  if (dx === 0 && dy === 0) return [a.x, a.y];16  const pad = 3, sx = (w / 2 + pad) / Math.abs(dx || 1e-9), sy = (h / 2 + pad) / Math.abs(dy || 1e-9), s = Math.min(sx, sy);17  return [a.x + dx * s, a.y + dy * s];18}1920const TONE_CLASS: Record<Tone, string> = { active: "dg-node-active", ok: "dg-node-ok", warn: "dg-node-warn", bad: "dg-node-bad", dim: "dg-node-dim" };2122/**23 * A node-and-arrow diagram. Purely presentational: which nodes and edges are highlighted comes from the24 * caller’s model. The drawing is hidden from assistive technology; the caller provides the same25 * information as text (step narration and text equivalent).26 */27export function Flow({ width, height, nodes, edges, nodeTone = {}, edgeTone = {}, boundary, children }: {28  width: number; height: number; nodes: FlowNode[]; edges: FlowEdge[];29  nodeTone?: Record<string, Tone | undefined>; edgeTone?: Record<string, "active" | "bad" | "dim" | undefined>;30  /** A dashed trust boundary: vertical line at x, or a rectangle. */31  boundary?: { x: number; label: string } | { rect: [number, number, number, number]; label: string };32  children?: ReactNode;33}) {34  const uid = useId().replace(/:/g, "");35  const byId = new Map(nodes.map((n) => [n.id, n]));36  return (37    <div className="overflow-x-auto rounded-xl border border-line bg-bg" tabIndex={0} role="group" aria-label="Schéma (faites défiler horizontalement si nécessaire ; la description textuelle suit)">38      <svg viewBox={`0 0 ${width} ${height}`} style={{ minWidth: Math.min(width, 640) }} className="block h-auto w-full" aria-hidden="true">39        <defs>40          {(["line-strong", "blue", "coral"] as const).map((c) => (41            <marker key={c} id={`${uid}-${c}`} viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0 10 5 0 10z" fill={`var(--${c})`} /></marker>42          ))}43        </defs>44        {boundary && ("x" in boundary ? (45          <g><line x1={boundary.x} y1={8} x2={boundary.x} y2={height - 8} className="dg-boundary" /><text x={boundary.x + 6} y={20} className="dg-sub" style={{ fill: "var(--coral)", fontWeight: 600 }}>{boundary.label}</text></g>46        ) : (47          <g><rect x={boundary.rect[0]} y={boundary.rect[1]} width={boundary.rect[2]} height={boundary.rect[3]} rx={14} className="dg-boundary" /><text x={boundary.rect[0] + 10} y={boundary.rect[1] + 16} className="dg-sub" style={{ fill: "var(--coral)", fontWeight: 600 }}>{boundary.label}</text></g>48        ))}49        {edges.map((e) => {50          const a = byId.get(e.from)!, b = byId.get(e.to)!, [x1, y1] = edgePoint(a, b), [x2, y2] = edgePoint(b, a);51          const tone = edgeTone[`${e.from}>${e.to}`], color = tone === "active" ? "blue" : tone === "bad" ? "coral" : "line-strong";52          return (53            <g key={`${e.from}>${e.to}`} opacity={tone === "dim" ? 0.3 : 1}>54              <line x1={x1} y1={y1} x2={x2} y2={y2} className={tone === "active" ? "dg-edge-active" : tone === "bad" ? "dg-edge-bad" : "dg-edge"} strokeDasharray={e.dashed ? "5 4" : undefined} markerEnd={`url(#${uid}-${color})`} />55              {e.label && <text x={(x1 + x2) / 2} y={(y1 + y2) / 2 + (e.dy ?? -6)} textAnchor="middle" className="dg-sub" style={{ paintOrder: "stroke", stroke: "var(--bg)", strokeWidth: 4 }}>{e.label}</text>}56            </g>57          );58        })}59        {nodes.map((n) => {60          const { w, h } = box(n), tone = nodeTone[n.id], cls = tone ? TONE_CLASS[tone] : "dg-node";61          return (62            <g key={n.id} opacity={tone === "dim" ? 0.55 : 1}>63              {n.shape === "diamond"64                ? <path d={`M${n.x} ${n.y - h / 2 - 6} L${n.x + w / 2 + 6} ${n.y} L${n.x} ${n.y + h / 2 + 6} L${n.x - w / 2 - 6} ${n.y}Z`} className={cls} />65                : <rect x={n.x - w / 2} y={n.y - h / 2} width={w} height={h} rx={n.shape === "pill" ? h / 2 : 10} className={cls} />}66              <text x={n.x} y={n.y + (n.sub ? -3 : 4)} textAnchor="middle" className="dg-label">{n.label}</text>67              {n.sub && <text x={n.x} y={n.y + 13} textAnchor="middle" className="dg-sub">{n.sub}</text>}68            </g>69          );70        })}71        {children}72      </svg>73    </div>74  );75}7677/** Previous / next / restart controls with the narration of the current step announced politely. */78export function Stepper({ index, count, onChange, title, children }: { index: number; count: number; onChange: (i: number) => void; title: string; children: ReactNode }) {79  return (80    <div className="rounded-xl border border-line bg-surface p-4" data-testid="stepper">81      <div className="flex flex-wrap items-center gap-2">82        <button type="button" className="btn btn-ghost btn-sm" onClick={() => onChange(index - 1)} disabled={index === 0}><Icon name="back" size={16} />Étape précédente</button>83        <button type="button" className="btn btn-primary btn-sm" onClick={() => onChange(index + 1)} disabled={index >= count - 1} data-testid="step-next">Étape suivante<Icon name="arrow" size={16} /></button>84        <button type="button" className="btn btn-quiet btn-sm" onClick={() => onChange(0)} disabled={index === 0}><Icon name="retry" size={16} />Recommencer</button>85        <span className="ml-auto font-mono text-sm text-faint">Étape {index + 1} sur {count}</span>86      </div>87      <div className="mt-3" aria-live="polite" data-testid="step-text">88        <p className="font-display text-[1.15rem]">{title}</p>89        <div className="mt-1 space-y-2 text-[0.97rem] text-muted">{children}</div>90      </div>91    </div>92  );93}9495export function Field({ label, children, hint }: { label: string; children: ReactNode; hint?: string }) {96  return <label className="grid gap-1 text-sm font-medium">{label}{children}{hint && <span className="text-xs font-normal text-faint">{hint}</span>}</label>;97}9899/** A labelled range slider that announces its value with its unit. */100export function Slider({ label, value, min, max, step = 1, unit = "", onChange, testid }: { label: string; value: number; min: number; max: number; step?: number; unit?: string; onChange: (v: number) => void; testid?: string }) {101  const fmt = (v: number) => `${String(v).replace(".", ",")}${unit ? ` ${unit}` : ""}`;102  return (103    <label className="grid gap-1 text-sm">104      <span className="flex justify-between gap-3"><span className="font-medium">{label}</span><span className="font-mono text-muted">{fmt(value)}</span></span>105      <input type="range" min={min} max={max} step={step} value={value} onChange={(e) => onChange(Number(e.target.value))} aria-valuetext={fmt(value)} className="h-6 w-full accent-(--blue)" data-testid={testid} />106    </label>107  );108}109110/** Pressed-state buttons for choosing one option among a few (radio semantics). */111export function Choice<T extends string>({ label, value, options, onChange }: { label: string; value: T; options: { id: T; label: string }[]; onChange: (v: T) => void }) {112  const name = useId();113  return (114    <fieldset>115      <legend className="text-sm font-medium">{label}</legend>116      <div className="mt-1.5 flex flex-wrap gap-1.5">117        {options.map((o) => (118          <label key={o.id} className="inline-flex min-h-10 cursor-pointer items-center gap-2 rounded-full border-[1.5px] border-line px-3 text-[0.92rem] has-checked:border-blue has-checked:bg-blue-soft has-checked:font-medium has-focus-visible:outline-3 has-focus-visible:outline-blue">119            <input type="radio" className="sr-only" name={name} checked={value === o.id} onChange={() => onChange(o.id)} />{o.label}120          </label>121        ))}122      </div>123    </fieldset>124  );125}126127export function Toggle({ label, checked, onChange, hint, testid }: { label: string; checked: boolean; onChange: (v: boolean) => void; hint?: string; testid?: string }) {128  return (129    <label className="flex cursor-pointer items-start gap-3 rounded-xl border border-line p-3 has-checked:border-blue has-checked:bg-blue-soft">130      <input type="checkbox" className="mt-0.5 size-[1.15rem] shrink-0 accent-(--blue)" checked={checked} onChange={(e) => onChange(e.target.checked)} data-testid={testid} />131      <span className="text-[0.95rem]"><span className="font-medium">{label}</span>{hint && <span className="block text-sm text-muted">{hint}</span>}</span>132    </label>133  );134}135136export function Verdict({ tone, children }: { tone: "ok" | "warn" | "bad" | "info"; children: ReactNode }) {137  const c = { ok: "border-teal bg-teal-soft", warn: "border-amber bg-amber-soft", bad: "border-coral bg-coral-soft", info: "border-blue bg-blue-soft" }[tone];138  const label = { ok: "Résultat", warn: "Attention", bad: "Problème", info: "À retenir" }[tone];139  return <div className={`rounded-xl border-l-4 p-3.5 text-[0.97rem] ${c}`} aria-live="polite" data-testid="verdict" data-tone={tone}><span className="font-semibold">{label} : </span>{children}</div>;140}141142export const num = (v: number, digits = 2) => new Intl.NumberFormat("fr-CA", { maximumFractionDigits: digits, minimumFractionDigits: digits }).format(v);143144/** The same information as the drawing, as text. Open by default for nobody, available to everybody. */145export function TextEquivalent({ children }: { children: ReactNode }) {146  return (147    <details className="rounded-xl border border-line bg-surface p-4" data-testid="text-equivalent">148      <summary className="font-medium">Équivalent textuel du schéma</summary>149      <div className="mt-3 space-y-2 text-[0.97rem] text-muted [&_ol]:list-decimal [&_ol]:pl-5 [&_ul]:list-disc [&_ul]:pl-5 [&_li]:mt-1">{children}</div>150    </details>151  );152}153
Files main
Menu

Theme