SPB Git

Repository Public

charts.js 11.9 KB 277 lines javascript

1// Graphiques SVG sans dépendance : courbe / aire / barres (temporel) et sparkline.2// Un seul axe Y par graphique, repère au survol (souris, tactile, clavier), états vides explicites.3// Les valeurs nulles sont des trous (jamais interpolées, jamais inventées).45import { h, s } from "./dom.js";6import { DASH, has, num } from "./format.js";78function niceMax(max, integer = false) {9  // 4 intervalles : le pas est « rond » (1, 2, 2,5, 5 × 10^k), entier pour les compteurs10  if (!(max > 0)) return integer ? 4 : 1;11  const raw = max / 4;12  const base = 10 ** Math.floor(Math.log10(raw));13  let step = 10 * base;14  for (const m of integer ? [1, 2, 5, 10] : [1, 2, 2.5, 5, 10]) if (raw <= m * base * (1 + 1e-9)) { step = m * base; break; }15  if (integer) step = Math.max(1, Math.round(step));16  return step * 4;17}1819/** Sparkline : tracé des valeurs successives (les null coupent le trait). */20export function sparkline(values, { color = "var(--c1)", label = "" } = {}) {21  const pts = values.filter(has);22  if (pts.length < 2) return h("div", { class: "spark-empty" }, pts.length ? "Collecte en cours…" : DASH);23  const W = 120;24  const H = 34;25  const max = Math.max(...pts);26  const min = Math.min(0, ...pts);27  const span = max - min || 1;28  const x = (i) => (values.length === 1 ? W : (i / (values.length - 1)) * W);29  const y = (v) => H - 3 - ((v - min) / span) * (H - 7);30  let d = "";31  let area = "";32  let pen = false;33  let segStart = 0;34  let last = null;35  values.forEach((v, i) => {36    if (!has(v)) {37      if (pen) area += `L${x(i - 1).toFixed(1)} ${H}L${x(segStart).toFixed(1)} ${H}Z`;38      pen = false;39      return;40    }41    if (!pen) { segStart = i; area += `M${x(i).toFixed(1)} ${y(v).toFixed(1)}`; } else area += `L${x(i).toFixed(1)} ${y(v).toFixed(1)}`;42    d += `${pen ? "L" : "M"}${x(i).toFixed(1)} ${y(v).toFixed(1)}`;43    pen = true;44    last = i;45  });46  if (pen) area += `L${x(values.length - 1).toFixed(1)} ${H}L${x(segStart).toFixed(1)} ${H}Z`;47  const svg = s("svg", { viewBox: `0 0 ${W} ${H}`, preserveAspectRatio: "none", role: "img", "aria-label": label || "Évolution récente" },48    s("path", { class: "spark-area", d: area }), s("path", { class: "spark-line", d }));49  svg.style.setProperty("--sc", color);50  const wrap = h("div", { style: { position: "relative" } }, svg);51  if (last !== null) {52    // point final en HTML : le SVG est étiré (preserveAspectRatio none), un cercle SVG serait déformé53    const dot = h("i", { style: { position: "absolute", width: "7px", height: "7px", "border-radius": "50%", background: color,54      "box-shadow": "0 0 0 2px var(--surface)", left: `calc(${(x(last) / W) * 100}% - 3.5px)`, top: `${y(values[last]) - 3.5}px` } });55    wrap.append(dot);56  }57  return wrap;58}5960/**61 * Graphique temporel.62 * cfg = { xs: number[] (epoch s), series: [{ name, color, values }], type: "line" | "area" | "bar", stacked,63 *         fmtY(v) (axe), fmtValue(v) (infobulle), fmtX(ts) (axe), fmtTip(ts) (infobulle), height, label, emptyText }64 * Retourne { destroy() }.65 */66export function timeChart(host, cfg) {67  const {68    xs, series, type = "line", stacked = false, integer = false, height = 220, label = "Graphique",69    fmtY = (v) => num(v), fmtValue = fmtY, fmtX = String, fmtTip = fmtX,70    emptyText = "Aucune donnée sur cette période.",71  } = cfg;72  host.replaceChildren();73  host.classList.add("chart");74  const hasData = xs.length > 0 && series.some((sr) => sr.values.some(has));75  if (!hasData) {76    host.removeAttribute("tabindex");77    host.append(h("div", { class: "empty", style: { "min-height": `${height}px` } }, h("b", null, "Pas encore de données"), h("span", null, emptyText)));78    return { destroy() {} };79  }8081  const n = xs.length;82  const isBar = type === "bar";83  if (series.length > 1) {84    host.append(h("div", { class: "chart-legend" }, series.map((sr) => h("span", null, h("i", { class: "sw", style: { "--sc": sr.color } }), sr.name))));85  }86  const svgHost = h("div");87  const tip = h("div", { class: "chart-tip", "aria-hidden": "true" });88  const live = h("div", { class: "sr-only", "aria-live": "polite" });89  host.append(svgHost, tip, live);90  host.tabIndex = 0;91  host.setAttribute("role", "group");92  host.setAttribute("aria-label", `${label}. Flèches gauche et droite pour parcourir les valeurs.`);9394  let yMax = 0;95  for (let i = 0; i < n; i += 1) {96    if (stacked) yMax = Math.max(yMax, series.reduce((a, sr) => a + (sr.values[i] || 0), 0));97    else for (const sr of series) if (has(sr.values[i])) yMax = Math.max(yMax, sr.values[i]);98  }99  yMax = cfg.max > 0 && cfg.max >= yMax ? cfg.max : niceMax(yMax, integer);100101  const M = { l: 8, r: 10, t: 8, b: 22 };102  let geo = null;103  let active = -1;104  let cursor = null;105106  function draw() {107    const W = Math.max(240, Math.floor(svgHost.clientWidth || host.clientWidth || 600));108    const H = height;109    const ticks = [0, 0.25, 0.5, 0.75, 1].map((f) => f * yMax);110    const labels = ticks.map((t) => fmtY(t));111    const left = M.l + Math.min(64, Math.max(...labels.map((t) => t.length)) * 6.4 + 6);112    const pw = W - left - M.r;113    const ph = H - M.t - M.b;114    const band = pw / n;115    const xAt = (i) => (isBar ? left + band * (i + 0.5) : n === 1 ? left + pw / 2 : left + (i / (n - 1)) * pw);116    const yAt = (v) => M.t + ph - (v / yMax) * ph;117    geo = { W, H, left, pw, ph, band, xAt, yAt };118119    const svg = s("svg", { viewBox: `0 0 ${W} ${H}`, height: H, "aria-hidden": "true" });120    ticks.forEach((t, i) => {121      const y = Math.round(yAt(t)) + 0.5;122      svg.append(s("line", { class: "ch-grid", x1: left, x2: W - M.r, y1: y, y2: y }),123        s("text", { class: "ch-axis", x: left - 6, y: y + 3.5, "text-anchor": "end" }, labels[i]));124    });125    const every = Math.max(1, Math.ceil(n / Math.max(2, Math.floor(pw / 84))));126    let lastLabel = null;127    for (let i = n - 1; i >= 0; i -= every) {128      const x = xAt(i);129      const anchor = x > W - M.r - 30 ? "end" : x < left + 30 ? "start" : "middle";130      const text = fmtX(xs[i]);131      if (text === lastLabel) continue; // pas deux graduations identiques (ex. même jour en pas horaire)132      lastLabel = text;133      svg.append(s("text", { class: "ch-axis", x, y: H - 5, "text-anchor": anchor }, text));134    }135136    cursor = s("g", { style: "display:none" });137    if (isBar) {138      const bw = Math.max(1, Math.min(28, band - (band > 5 ? 2 : band > 2.5 ? 1 : 0)));139      cursor.append(s("rect", { class: "ch-band", y: M.t, height: ph, width: Math.max(band, 2), rx: 3 }));140      svg.append(cursor);141      for (let i = 0; i < n; i += 1) {142        let base = 0;143        series.forEach((sr, k) => {144          const v = sr.values[i];145          if (!has(v) || v <= 0) return;146          const x = stacked || series.length === 1 ? xAt(i) - bw / 2 : xAt(i) - bw / 2 + (bw / series.length) * k;147          const w = stacked || series.length === 1 ? bw : Math.max(1, bw / series.length - 1);148          const y0 = yAt(stacked ? base : 0);149          const y1 = yAt((stacked ? base : 0) + v);150          const gap = stacked && base > 0 && y0 - y1 > 3 ? 1.5 : 0;151          const r = Math.min(3, w / 2, (y0 - y1) / 2);152          const rect = s("rect", { class: "ch-bar", x: x.toFixed(2), y: y1.toFixed(2), width: w.toFixed(2), height: Math.max(1, y0 - y1 - gap).toFixed(2), rx: r.toFixed(1) });153          rect.style.setProperty("--sc", sr.color);154          svg.append(rect);155          if (stacked) base += v;156        });157      }158    } else {159      for (const sr of series) {160        // suites continues de valeurs (les null coupent le trait)161        const runs = [];162        let start = -1;163        for (let i = 0; i <= n; i += 1) {164          const ok = i < n && has(sr.values[i]);165          if (ok && start < 0) start = i;166          if (!ok && start >= 0) { runs.push([start, i - 1]); start = -1; }167        }168        let d = "";169        let area = "";170        const singles = [];171        const y0 = yAt(0).toFixed(1);172        for (const [a, b] of runs) {173          if (a === b) { singles.push(a); continue; }174          let pts = "";175          for (let i = a; i <= b; i += 1) pts += `${i === a ? "" : "L"}${xAt(i).toFixed(1)} ${yAt(sr.values[i]).toFixed(1)}`;176          d += `M${pts}`;177          area += `M${xAt(a).toFixed(1)} ${y0}L${pts}L${xAt(b).toFixed(1)} ${y0}Z`;178        }179        const g = s("g");180        g.style.setProperty("--sc", sr.color);181        if (type === "area" && series.length === 1 && area) g.append(s("path", { class: "ch-area", d: area }));182        if (d) g.append(s("path", { class: "ch-line", d }));183        for (const i of singles) g.append(s("circle", { class: "ch-pt", cx: xAt(i), cy: yAt(sr.values[i]), r: 3.5 }));184        svg.append(g);185      }186      cursor.append(s("line", { class: "ch-cross", y1: M.t, y2: M.t + ph }));187      for (const sr of series) {188        const c = s("circle", { class: "ch-pt", r: 4.5 });189        c.style.setProperty("--sc", sr.color);190        cursor.append(c);191      }192      svg.append(cursor);193    }194    svgHost.replaceChildren(svg);195    if (active >= 0) show(active, false);196  }197198  function show(i, announce) {199    if (!geo) return;200    active = Math.max(0, Math.min(n - 1, i));201    const x = geo.xAt(active);202    cursor.style.display = "";203    if (isBar) {204      const r = cursor.firstChild;205      r.setAttribute("x", x - Math.max(geo.band, 2) / 2);206    } else {207      const [line, ...dots] = cursor.childNodes;208      line.setAttribute("x1", Math.round(x) + 0.5);209      line.setAttribute("x2", Math.round(x) + 0.5);210      dots.forEach((dot, k) => {211        const v = series[k].values[active];212        dot.style.display = has(v) ? "" : "none";213        if (has(v)) { dot.setAttribute("cx", x); dot.setAttribute("cy", geo.yAt(v)); }214      });215    }216    const rows = series.map((sr) => h("div", { class: "r" }, h("i", { class: "sw", style: { "--sc": sr.color } }), sr.name,217      h("b", null, has(sr.values[active]) ? fmtValue(sr.values[active]) : DASH)));218    tip.replaceChildren(h("div", { class: "t" }, fmtTip(xs[active])), ...rows);219    tip.classList.add("on");220    const top = svgHost.offsetTop;221    const tw = tip.offsetWidth;222    let tx = x + 12;223    if (tx + tw > geo.W - 4) tx = x - tw - 12;224    tx = Math.max(0, Math.min(geo.W - tw, tx));225    tip.style.transform = `translate(${Math.round(tx)}px, ${top + M.t + 4}px)`;226    if (announce) {227      live.textContent = `${fmtTip(xs[active])} : ${series.map((sr) => `${sr.name} ${has(sr.values[active]) ? fmtValue(sr.values[active]) : "aucune valeur"}`).join(", ")}`;228    }229  }230231  function hide() {232    active = -1;233    if (cursor) cursor.style.display = "none";234    tip.classList.remove("on");235  }236237  function indexAt(clientX) {238    const rect = svgHost.getBoundingClientRect();239    const x = clientX - rect.left - geo.left;240    return isBar ? Math.floor(x / geo.band) : Math.round((x / geo.pw) * (n - 1));241  }242243  const onMove = (e) => { if (geo) show(indexAt(e.clientX), false); };244  const onLeave = (e) => { if (e.pointerType !== "touch") hide(); };245  const onKey = (e) => {246    const step = { ArrowLeft: -1, ArrowRight: 1 }[e.key];247    if (step) { e.preventDefault(); show(active < 0 ? n - 1 : active + step, true); }248    else if (e.key === "Home") { e.preventDefault(); show(0, true); }249    else if (e.key === "End") { e.preventDefault(); show(n - 1, true); }250    else if (e.key === "Escape" && active >= 0) { e.stopPropagation(); hide(); }251  };252  const onBlur = () => hide();253  svgHost.addEventListener("pointermove", onMove);254  svgHost.addEventListener("pointerdown", onMove);255  svgHost.addEventListener("pointerleave", onLeave);256  host.addEventListener("keydown", onKey);257  host.addEventListener("blur", onBlur);258259  const ro = new ResizeObserver(() => {260    const w = Math.floor(svgHost.clientWidth);261    if (!geo || Math.abs(w - geo.W) > 1) draw();262  });263  ro.observe(svgHost);264  draw();265266  return {267    destroy() {268      ro.disconnect();269      svgHost.removeEventListener("pointermove", onMove);270      svgHost.removeEventListener("pointerdown", onMove);271      svgHost.removeEventListener("pointerleave", onLeave);272      host.removeEventListener("keydown", onKey);273      host.removeEventListener("blur", onBlur);274    },275  };276}277
Files main
Menu

Theme