Repository Public
1// Briques communes des écrans d'exploitation : pastille d'état, âge lisible, actualisation suspendue quand l'onglet est caché,2// courbe de tendance en SVG nu (nommée, décrite, jamais la couleur seule, tableau équivalent fourni par l'appelant).3import { useEffect, useId, useRef, type ReactNode } from "react"4import { compactDuration, lineLayout, statusChip, type CheckStatus, type Point } from "../../../admin/ops"5import { labelIndexes } from "../../../admin/charts"6import { addMessages, fmtNumber, getLang, t } from "../../../i18n"7import { enAdmInfra } from "../../../i18n/en.adm.infra"8import { enAdmOps } from "../../../i18n/en.adm.ops"9import { frAdmInfra } from "../../../i18n/fr.adm.infra"10import { frAdmOps } from "../../../i18n/fr.adm.ops"11import { Icon } from "../../kit"12import { dayLabel, useWidth } from "../infra/Charts"13import { DASH } from "../shared"14import "../infra/infra.css"15import "./ops.css"1617addMessages("fr", frAdmInfra)18addMessages("en", enAdmInfra)19addMessages("fr", frAdmOps)20addMessages("en", enAdmOps)2122/** État d'un contrôle : icône + mot (« En ordre », « À surveiller », « En panne », « Inconnu »), ton par jeton. */23export function StatusChip({ status, testId }: { status: CheckStatus; testId?: string }) {24 const c = statusChip(status)25 return (26 <span className={`badge ${c.tone} adm-ops-chip`} data-status={status} data-testid={testId}>27 <Icon name={c.icon} small />28 {t(c.label)}29 </span>30 )31}3233/** « il y a 12 min » (ou un tiret si la date manque). */34export function ago(iso: string | null | undefined, now = Date.now()): string {35 const at = iso ? Date.parse(iso) : NaN36 if (Number.isNaN(at)) return DASH37 return t("adm.ops.ago", { d: compactDuration(Math.max(0, now - at), getLang() === "fr" ? "j" : "d") })38}39export const duration = (ms: number): string => compactDuration(ms, getLang() === "fr" ? "j" : "d")4041/**42 * Actualisation périodique, suspendue tant que l'onglet est caché ; au retour sur l'onglet, une actualisation immédiate si la43 * période est écoulée. Jamais plus rapide que 15 s.44 */45export function useAutoRefresh(reload: () => void, everyMs: number, enabled: boolean) {46 const last = useRef(Date.now())47 const fn = useRef(reload)48 fn.current = reload49 useEffect(() => {50 if (!enabled) return51 const period = Math.max(15_000, everyMs)52 const run = () => {53 if (document.hidden) return54 last.current = Date.now()55 fn.current()56 }57 const id = window.setInterval(run, period)58 const onVisible = () => {59 if (!document.hidden && Date.now() - last.current >= period) run()60 }61 document.addEventListener("visibilitychange", onVisible)62 return () => {63 window.clearInterval(id)64 document.removeEventListener("visibilitychange", onVisible)65 }66 }, [enabled, everyMs])67}6869export interface TrendSeries {70 id: string71 label: string72 points: Point[]73}74const DASHES = ["", "6 4", "2 4"]7576function Marker({ index, x, y, children }: { index: number; x: number; y: number; children: ReactNode }) {77 if (index === 1) return <rect className={`adm-trend-dot s${index}`} x={x - 3} y={y - 3} width="6" height="6">{children}</rect>78 if (index === 2) return <path className={`adm-trend-dot s${index}`} d={`M${x},${y - 4}L${x + 4},${y + 3}L${x - 4},${y + 3}Z`}>{children}</path>79 return <circle className={`adm-trend-dot s${index}`} cx={x} cy={y} r="3">{children}</circle>80}8182/**83 * Courbe(s) dans le temps. Chaque série se distingue par son tracé (plein, tirets, pointillés) ET la forme de ses points ;84 * la projection éventuelle de la première série est un segment en tirets terminé par un point creux.85 */86export function TrendChart({ series, title, desc, format = fmtNumber, binary, projected, testId }: { series: readonly TrendSeries[]; title: string; desc: string; format?: (n: number) => string; binary?: boolean; projected?: { days: number; value: number } | null; testId?: string }) {87 const p = useId().replace(/:/g, "")88 const [ref, width] = useWidth<HTMLDivElement>(640)89 const height = 22090 const box = { width, height, top: 14, right: 14, bottom: 28, left: 64 }91 const all = series.flatMap((s) => s.points)92 // une seule échelle pour toutes les séries : la géométrie de chacune est calculée sur l'étendue commune93 const frame = lineLayout([...all].sort((a, b) => a.day.localeCompare(b.day)), box, { binary, projected })94 const days = [...new Set(all.map((x) => x.day))].sort()95 const span = frame.points.length ? { x0: frame.points[0].x, x1: frame.points[frame.points.length - 1].x } : { x0: box.left, x1: width - box.right }96 const base = height - box.bottom97 const xOf = (day: string) => frame.points.find((q) => q.day === day)?.x ?? span.x098 const yOf = (v: number) => Math.round((base - (frame.max > 0 ? (v / frame.max) * (base - box.top) : 0)) * 100) / 10099 // avec une projection, les relevés n'occupent qu'une partie de l'axe : seules les dates extrêmes y tiennent sans se chevaucher100 const labels = labelIndexes(days.length, frame.projection ? 2 : width < 480 ? 3 : 6)101 return (102 <div ref={ref} className="adm-chart" data-testid={testId}>103 <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} role="img" aria-labelledby={`${p}-t ${p}-d`}>104 <title id={`${p}-t`}>{title}</title>105 <desc id={`${p}-d`}>{desc}</desc>106 {frame.ticks.map((tk) => (107 <g key={tk.value}>108 <line className="adm-chart-grid" x1={box.left} x2={width - box.right} y1={tk.y} y2={tk.y} />109 <text className="adm-chart-tick" x={box.left - 6} y={tk.y + 4} textAnchor="end">110 {format(tk.value)}111 </text>112 </g>113 ))}114 {series.map((s, i) => {115 const pts = s.points.map((q) => ({ ...q, x: xOf(q.day), y: yOf(q.value) }))116 if (!pts.length) return null117 const d = `M${pts.map((q) => `${q.x},${q.y}`).join("L")}`118 return (119 <g key={s.id} data-series={s.id}>120 {i === 0 && pts.length > 1 ? <path className="adm-trend-area" d={`${d}L${pts[pts.length - 1].x},${base}L${pts[0].x},${base}Z`} /> : null}121 {pts.length > 1 ? <path className={`adm-trend-line s${i}`} d={d} strokeDasharray={DASHES[i] || undefined} /> : null}122 {pts.length <= 45 || i > 0123 ? pts.map((q) => (124 <Marker key={q.day} index={i} x={q.x} y={q.y}>125 <title>{`${dayLabel(q.day, true)} — ${s.label} : ${format(q.value)}`}</title>126 </Marker>127 ))128 : null}129 </g>130 )131 })}132 {frame.projection ? (133 <g data-testid="trend-projection">134 <line className="adm-trend-line s0 projection" x1={frame.projection.x1} y1={frame.projection.y1} x2={frame.projection.x2} y2={frame.projection.y2} strokeDasharray="3 5" />135 <circle className="adm-trend-dot hollow" cx={frame.projection.x2} cy={frame.projection.y2} r="4">136 <title>{`${t("adm.ops.trend.projection")} : ${format(projected?.value ?? 0)}`}</title>137 </circle>138 </g>139 ) : null}140 {days.map((day, i) =>141 labels.includes(i) ? (142 <text key={day} className="adm-chart-tick" x={xOf(day)} y={height - 9} textAnchor={i === 0 ? "start" : i === days.length - 1 && !frame.projection ? "end" : "middle"}>143 {dayLabel(day)}144 </text>145 ) : null,146 )}147 <line className="adm-chart-axis" x1={box.left} x2={width - box.right} y1={base} y2={base} />148 </svg>149 {series.length > 1 || frame.projection ? (150 <ul className="adm-chart-legend adm-trend-legend">151 {series.map((s, i) => (152 <li key={s.id}>153 <svg width="28" height="12" aria-hidden="true" focusable="false">154 <line className={`adm-trend-line s${i}`} x1="1" x2="27" y1="6" y2="6" strokeDasharray={DASHES[i] || undefined} />155 <Marker index={i} x={14} y={6}>156 {null}157 </Marker>158 </svg>159 <span>{s.label}</span>160 </li>161 ))}162 {frame.projection ? (163 <li>164 <svg width="28" height="12" aria-hidden="true" focusable="false">165 <line className="adm-trend-line s0 projection" x1="1" x2="20" y1="6" y2="6" strokeDasharray="3 5" />166 <circle className="adm-trend-dot hollow" cx="23" cy="6" r="3.5" />167 </svg>168 <span>{t("adm.ops.trend.projection")}</span>169 </li>170 ) : null}171 </ul>172 ) : null}173 </div>174 )175}176177/** Compteur d'en-tête (réutilise le style des compteurs de la console). */178export function Stat({ label, value, testId, tone }: { label: string; value: string; testId?: string; tone?: "danger" | "warn" | "ok" }) {179 return (180 <div className={`adm-stat${tone ? ` adm-ops-stat-${tone}` : ""}`}>181 <span className="adm-stat-value" data-testid={testId}>182 {value}183 </span>184 <span className="muted small">{label}</span>185 </div>186 )187}188