@vitavision/charts 0.8.3 → 0.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { useCallback, useState } from "react";
1
+ import { useCallback, useId, useMemo, useRef, useState } from "react";
2
2
  import { cn, toneColor } from "@vitavision/ui";
3
3
  import { jsx, jsxs } from "react/jsx-runtime";
4
4
  //#region src/Frame.tsx
@@ -93,7 +93,7 @@ const AXIS = "currentColor";
93
93
  * Renders a `<figure>` holding an SVG with `role="img"` named by `label`, and the `footer`
94
94
  * as its `<figcaption>`. `children` are drawn in viewBox units over the grid.
95
95
  */
96
- function Frame({ xScale, yScale, xLabel, yLabel, xTicks = 5, yTicks = 4, children, label, footer, variant = "panel", className, size, figureRef }) {
96
+ function Frame({ xScale, yScale, xLabel, yLabel, xTicks = 5, yTicks = 4, xFormat, children, label, footer, variant = "panel", className, size, figureRef, interactive = false }) {
97
97
  const horizontal = xScale.ticks(xTicks);
98
98
  const vertical = yScale.ticks(yTicks);
99
99
  const plotArea = areaFor(variant, size);
@@ -105,7 +105,7 @@ function Frame({ xScale, yScale, xLabel, yLabel, xTicks = 5, yTicks = 4, childre
105
105
  ref: figureRef,
106
106
  className: cn("flex flex-col gap-1 text-fg-muted", className),
107
107
  children: [/* @__PURE__ */ jsxs("svg", {
108
- role: "img",
108
+ role: interactive ? "group" : "img",
109
109
  "aria-label": label,
110
110
  viewBox: `0 0 ${PLOT.width} ${PLOT.height}`,
111
111
  className: "w-full",
@@ -145,7 +145,7 @@ function Frame({ xScale, yScale, xLabel, yLabel, xTicks = 5, yTicks = 4, childre
145
145
  textAnchor: "middle",
146
146
  fontSize: 10,
147
147
  fill: AXIS,
148
- children: tick.label
148
+ children: xFormat ? xFormat(tick.value) : tick.label
149
149
  })] }, `x-${tick.value}`);
150
150
  }),
151
151
  /* @__PURE__ */ jsx("line", {
@@ -202,14 +202,32 @@ function Legend({ items, className }) {
202
202
  className: cn("flex flex-wrap items-center gap-x-4 gap-y-1", className),
203
203
  children: items.map((item) => /* @__PURE__ */ jsxs("li", {
204
204
  className: "flex items-center gap-1.5",
205
- children: [/* @__PURE__ */ jsx("span", {
206
- "aria-hidden": true,
207
- className: "inline-block h-0.5 w-4 rounded-full",
208
- style: { backgroundColor: item.colour }
209
- }), /* @__PURE__ */ jsx("span", {
210
- className: "font-mono text-xs",
211
- children: item.label
212
- })]
205
+ children: [
206
+ item.band === void 0 ? /* @__PURE__ */ jsx("span", {
207
+ "aria-hidden": true,
208
+ className: "inline-block h-0.5 w-4 rounded-full",
209
+ style: { backgroundColor: item.colour }
210
+ }) : /* @__PURE__ */ jsxs("span", {
211
+ "aria-hidden": true,
212
+ "data-band-swatch": "",
213
+ className: "relative inline-block h-2.5 w-4",
214
+ children: [/* @__PURE__ */ jsx("span", {
215
+ className: "absolute inset-0 rounded-sm opacity-20",
216
+ style: { backgroundColor: item.colour }
217
+ }), /* @__PURE__ */ jsx("span", {
218
+ className: "absolute inset-x-0 top-1/2 h-0.5 -translate-y-1/2 rounded-full",
219
+ style: { backgroundColor: item.colour }
220
+ })]
221
+ }),
222
+ /* @__PURE__ */ jsx("span", {
223
+ className: "font-mono text-xs",
224
+ children: item.label
225
+ }),
226
+ item.band !== void 0 && /* @__PURE__ */ jsx("span", {
227
+ className: "font-mono text-xs text-fg-subtle",
228
+ children: item.band
229
+ })
230
+ ]
213
231
  }, item.label))
214
232
  });
215
233
  }
@@ -433,6 +451,114 @@ function histogram(values, domain, count) {
433
451
  return bins;
434
452
  }
435
453
  //#endregion
454
+ //#region src/interpolate.ts
455
+ /** Reading a series between its points. */
456
+ /**
457
+ * A series' value at `x`, linearly interpolated between the points either side, or `null`
458
+ * outside its range or across a gap.
459
+ *
460
+ * @param points - The series, in ascending `x`.
461
+ * @param x - Where.
462
+ * @returns The interpolated value, or `null`.
463
+ */
464
+ function seriesValueAt(points, x) {
465
+ if (points.length === 0) return null;
466
+ if (points.length === 1) return points[0].x === x ? points[0].y : null;
467
+ let lo = 0;
468
+ let hi = points.length - 1;
469
+ if (x < points[lo].x || x > points[hi].x) return null;
470
+ while (hi - lo > 1) {
471
+ const mid = lo + hi >> 1;
472
+ if (points[mid].x <= x) lo = mid;
473
+ else hi = mid;
474
+ }
475
+ const a = points[lo];
476
+ const b = points[hi];
477
+ if (!Number.isFinite(a.y) || !Number.isFinite(b.y)) return null;
478
+ if (b.x === a.x) return a.y;
479
+ return a.y + (x - a.x) / (b.x - a.x) * (b.y - a.y);
480
+ }
481
+ //#endregion
482
+ //#region src/band.ts
483
+ /**
484
+ * The arithmetic of a series' error band: the ribbon between a lower and an upper value at every
485
+ * point of a series, its outline, and its value at an x between two points. Pure, so the geometry
486
+ * is testable apart from the SVG.
487
+ */
488
+ /** The band's edges at point `index`, ordered low to high, or `null` where either is missing or non-finite. */
489
+ function bandBoundsAt(band, index) {
490
+ const a = band.lower[index];
491
+ const b = band.upper[index];
492
+ if (a === void 0 || b === void 0 || !Number.isFinite(a) || !Number.isFinite(b)) return null;
493
+ return a <= b ? [a, b] : [b, a];
494
+ }
495
+ /**
496
+ * The outline of a band as an SVG path `d`: the upper edge left to right and the lower edge back,
497
+ * closed, once for every run of points whose x and both edges are finite. A run of one point has
498
+ * no area and draws nothing; a gap ends the run, so the band is not bridged across missing data.
499
+ *
500
+ * @param points - The series' points, in draw order.
501
+ * @param band - The edges, by point index. Missing entries count as gaps.
502
+ * @param xScale - The horizontal scale.
503
+ * @param yScale - The vertical scale.
504
+ * @returns The path, or `""` when there is nothing to fill.
505
+ */
506
+ function bandPath(points, band, xScale, yScale) {
507
+ const runs = [];
508
+ let run = [];
509
+ const close = () => {
510
+ if (run.length > 1) runs.push(run);
511
+ run = [];
512
+ };
513
+ points.forEach((point, index) => {
514
+ const bounds = bandBoundsAt(band, index);
515
+ if (!Number.isFinite(point.x) || bounds === null) {
516
+ close();
517
+ return;
518
+ }
519
+ run.push({
520
+ x: xScale.project(point.x),
521
+ lo: yScale.project(bounds[0]),
522
+ hi: yScale.project(bounds[1])
523
+ });
524
+ });
525
+ close();
526
+ const f = (n) => n.toFixed(2);
527
+ return runs.map((r) => {
528
+ const top = r.map((p, i) => `${i === 0 ? "M" : "L"}${f(p.x)} ${f(p.hi)}`);
529
+ const bottom = r.map((p) => `L${f(p.x)} ${f(p.lo)}`).reverse();
530
+ return `${[...top, ...bottom].join(" ")} Z`;
531
+ }).join(" ");
532
+ }
533
+ /** Every finite edge of a band, for the chart's y extent. */
534
+ function bandValues(band) {
535
+ return [...band.lower, ...band.upper].filter(Number.isFinite);
536
+ }
537
+ /** A series' band at `x`, interpolated like {@link seriesValueAt}: `[lower, upper]`, or `null` outside the series or across a gap. */
538
+ function bandValueAt(points, band, x) {
539
+ const edge = (pick) => seriesValueAt(points.map((point, index) => ({
540
+ x: point.x,
541
+ y: bandBoundsAt(band, index)?.[pick] ?? NaN
542
+ })), x);
543
+ const lo = edge(0);
544
+ const hi = edge(1);
545
+ return lo === null || hi === null ? null : [lo, hi];
546
+ }
547
+ /**
548
+ * A value with its band as text: `3.2 ± 0.4` when the band is symmetric about the value, else
549
+ * `3.2 [2.8, 3.9]`.
550
+ *
551
+ * @param value - The series' value.
552
+ * @param bounds - The band's `[lower, upper]` there.
553
+ * @param format - Formats one number.
554
+ */
555
+ function formatWithBand(value, bounds, format) {
556
+ const [lo, hi] = bounds;
557
+ const up = hi - value;
558
+ const down = value - lo;
559
+ return Math.abs(up - down) <= 1e-6 * Math.max(Math.abs(up), Math.abs(down), Number.MIN_VALUE) ? `${format(value)} ± ${format(up)}` : `${format(value)} [${format(lo)}, ${format(hi)}]`;
560
+ }
561
+ //#endregion
436
562
  //#region src/interaction.tsx
437
563
  /**
438
564
  * What `LineChart` and `LineProfile` share beyond the frame:
@@ -485,11 +611,15 @@ function Markers({ markers, xScale, area }) {
485
611
  })
486
612
  });
487
613
  }
614
+ /** The default readout format: whole numbers from 100 up, three significant digits below. */
615
+ function defaultFormat$1(value) {
616
+ return Math.abs(value) >= 100 ? value.toFixed(0) : value.toPrecision(3);
617
+ }
488
618
  /**
489
619
  * The pointer layer over the plot area: a crosshair and a value readout while hovering, the
490
620
  * external `cursor` otherwise, and clicks as picks.
491
621
  */
492
- function PlotInteraction({ xScale, yScale, area, series, cursor, onHover, onPick, format = (value) => Math.abs(value) >= 100 ? value.toFixed(0) : value.toPrecision(3) }) {
622
+ function PlotInteraction({ xScale, yScale, area, series, cursor, onHover, onPick, format = defaultFormat$1, xFormat }) {
493
623
  const [hover, setHover] = useState(null);
494
624
  const interactive = onHover !== void 0 || onPick !== void 0;
495
625
  const xAt = (event) => {
@@ -509,10 +639,13 @@ function PlotInteraction({ xScale, yScale, area, series, cursor, onHover, onPick
509
639
  const x = shown === null ? null : xScale.project(shown);
510
640
  const readout = hover === null ? [] : series.flatMap((entry) => {
511
641
  const y = seriesValueAt(entry.points, hover);
512
- return y === null ? [] : [{
642
+ if (y === null) return [];
643
+ const bounds = entry.band ? bandValueAt(entry.points, entry.band, hover) : null;
644
+ return [{
513
645
  name: entry.name,
514
646
  colour: entry.colour,
515
- y
647
+ y,
648
+ bounds
516
649
  }];
517
650
  });
518
651
  return /* @__PURE__ */ jsxs("g", {
@@ -543,7 +676,7 @@ function PlotInteraction({ xScale, yScale, area, series, cursor, onHover, onPick
543
676
  textAnchor: x > (area.x0 + area.x1) / 2 ? "end" : "start",
544
677
  fontSize: 10,
545
678
  fill: "currentColor",
546
- children: [format(hover), ...readout.map((entry) => `${entry.name} ${format(entry.y)}`)].join(" · ")
679
+ children: [(xFormat ?? format)(hover), ...readout.map((entry) => `${entry.name} ${entry.bounds ? formatWithBand(entry.y, entry.bounds, format) : format(entry.y)}`)].join(" · ")
547
680
  }),
548
681
  interactive && /* @__PURE__ */ jsx("rect", {
549
682
  "data-plot-target": "",
@@ -567,31 +700,6 @@ function PlotInteraction({ xScale, yScale, area, series, cursor, onHover, onPick
567
700
  ]
568
701
  });
569
702
  }
570
- /**
571
- * A series' value at `x`, linearly interpolated between the points either side, or `null`
572
- * outside its range or across a gap.
573
- *
574
- * @param points - The series, in ascending `x`.
575
- * @param x - Where.
576
- * @returns The interpolated value, or `null`.
577
- */
578
- function seriesValueAt(points, x) {
579
- if (points.length === 0) return null;
580
- if (points.length === 1) return points[0].x === x ? points[0].y : null;
581
- let lo = 0;
582
- let hi = points.length - 1;
583
- if (x < points[lo].x || x > points[hi].x) return null;
584
- while (hi - lo > 1) {
585
- const mid = lo + hi >> 1;
586
- if (points[mid].x <= x) lo = mid;
587
- else hi = mid;
588
- }
589
- const a = points[lo];
590
- const b = points[hi];
591
- if (!Number.isFinite(a.y) || !Number.isFinite(b.y)) return null;
592
- if (b.x === a.x) return a.y;
593
- return a.y + (x - a.x) / (b.x - a.x) * (b.y - a.y);
594
- }
595
703
  function clamp(value, low, high) {
596
704
  return Math.min(high, Math.max(low, value));
597
705
  }
@@ -604,11 +712,12 @@ function clamp(value, low, high) {
604
712
  * An SVG `role="img"` named by `label`, with the legend as real text under it. Series are
605
713
  * told apart by the legend's names, never by colour alone. `bands` and `markers` mark x
606
714
  * ranges and positions; `onHover` adds a crosshair and a value readout, `onPick` makes a
607
- * click report its x, and `cursor` draws an x chosen elsewhere.
715
+ * click report its x, and `cursor` draws an x chosen elsewhere. A series' `band` adds an error
716
+ * band, and `xFormat` writes the x labels.
608
717
  */
609
- function LineChart({ series, label, xLabel, yLabel, logY = false, xDomain, yDomain, underlay, footer, showLegend = true, variant = "panel", className, height = 200, bands, markers, cursor, onHover, onPick }) {
718
+ function LineChart({ series, label, xLabel, yLabel, logY = false, xDomain, yDomain, xFormat, underlay, footer, showLegend = true, variant = "panel", className, height = 200, bands, markers, cursor, onHover, onPick }) {
610
719
  const allX = series.flatMap((entry) => entry.points.map((point) => point.x));
611
- const allY = series.flatMap((entry) => entry.points.map((point) => point.y));
720
+ const allY = series.flatMap((entry) => [...entry.points.map((point) => point.y), ...entry.band ? bandValues(entry.band) : []]);
612
721
  const [fluidRef, fluidSize] = useFluidSize(height);
613
722
  const size = variant === "fluid" ? fluidSize : void 0;
614
723
  const plotArea = areaFor(variant, size);
@@ -628,11 +737,13 @@ function LineChart({ series, label, xLabel, yLabel, logY = false, xDomain, yDoma
628
737
  className,
629
738
  size,
630
739
  figureRef: variant === "fluid" ? fluidRef : void 0,
740
+ xFormat,
631
741
  footer: /* @__PURE__ */ jsxs("div", {
632
742
  className: "flex flex-col gap-1",
633
743
  children: [showLegend && /* @__PURE__ */ jsx(Legend, { items: coloured.map((entry) => ({
634
744
  label: entry.name,
635
- colour: entry.colour
745
+ colour: entry.colour,
746
+ ...entry.band ? { band: entry.band.label ?? "± band" } : {}
636
747
  })) }), footer]
637
748
  }),
638
749
  children: [
@@ -641,6 +752,14 @@ function LineChart({ series, label, xLabel, yLabel, logY = false, xDomain, yDoma
641
752
  xScale,
642
753
  area: plotArea
643
754
  }),
755
+ coloured.map((entry) => entry.band && /* @__PURE__ */ jsx("path", {
756
+ "data-series-band": entry.name,
757
+ "aria-hidden": true,
758
+ d: bandPath(entry.points, entry.band, xScale, yScale),
759
+ fill: entry.colour,
760
+ fillOpacity: .16,
761
+ stroke: "none"
762
+ }, `band-${entry.name}`)),
644
763
  underlay?.(xScale, yScale),
645
764
  coloured.map((entry) => entry.points.length === 1 ? /* @__PURE__ */ jsx("circle", {
646
765
  cx: xScale.project(entry.points[0]?.x ?? 0),
@@ -667,189 +786,1271 @@ function LineChart({ series, label, xLabel, yLabel, logY = false, xDomain, yDoma
667
786
  series: coloured,
668
787
  cursor,
669
788
  onHover,
670
- onPick
789
+ onPick,
790
+ xFormat
671
791
  })
672
792
  ]
673
793
  });
674
794
  }
675
795
  //#endregion
676
- //#region src/BarChart.tsx
677
- /**
678
- * Horizontal stacked bars — a per-category breakdown.
679
- *
680
- * Horizontal because the categories are free text — a defect type, a part family — and a
681
- * vertical axis would either truncate them or turn them sideways. Stacked because the
682
- * usual question is "of this category, how many landed in each outcome", which is a
683
- * proportion of a known total rather than independent counts.
684
- */
685
- /**
686
- * Horizontal stacked bars, one row per category, all on one shared scale (the widest row's
687
- * total).
688
- *
689
- * @remarks
690
- * Exposed as an ARIA `table`: each row has a `rowheader` (the category) and a text cell that
691
- * spells every non-zero segment out as `"<value> <name>"`, so nothing depends on colour or
692
- * on bar width. A row with no non-zero segment shows its total.
693
- */
694
- function StackedBars({ rows, label, className }) {
695
- const widest = Math.max(1, ...rows.map((row) => row.segments.reduce((total, segment) => total + segment.value, 0)));
696
- return /* @__PURE__ */ jsx("div", {
697
- className: cn("flex flex-col gap-2", className),
698
- role: "table",
699
- "aria-label": label,
700
- children: rows.map((row) => {
701
- const total = row.segments.reduce((sum, segment) => sum + segment.value, 0);
702
- return /* @__PURE__ */ jsxs("div", {
703
- className: "flex items-center gap-3 text-xs",
704
- role: "row",
705
- children: [
706
- /* @__PURE__ */ jsx("span", {
707
- className: "w-28 shrink-0 truncate font-mono",
708
- role: "rowheader",
709
- title: row.label,
710
- children: row.label
711
- }),
712
- /* @__PURE__ */ jsx("div", {
713
- className: "flex h-4 flex-1 overflow-hidden rounded-control bg-raised",
714
- role: "cell",
715
- children: row.segments.map((segment) => segment.value === 0 ? null : /* @__PURE__ */ jsx("div", {
716
- className: "h-full",
717
- style: {
718
- width: `${segment.value / widest * 100}%`,
719
- backgroundColor: segment.colour
720
- },
721
- title: `${segment.name}: ${segment.value}`
722
- }, segment.name))
723
- }),
724
- /* @__PURE__ */ jsx("span", {
725
- className: "w-24 shrink-0 text-right font-mono text-fg-muted",
726
- role: "cell",
727
- children: row.segments.filter((segment) => segment.value > 0).map((segment) => `${segment.value} ${segment.name}`).join(" · ") || `${total}`
728
- })
729
- ]
730
- }, row.label);
731
- })
732
- });
733
- }
734
- /** A finite, ordered, non-degenerate domain; `[0, 1]` when `domain` is unusable. */
735
- function usableDomain(low, high) {
736
- return padDomain(Math.min(low, high), Math.max(low, high));
737
- }
738
- /**
739
- * Bin raw values into `bins` equal-width buckets.
740
- *
741
- * @param values - The samples. Non-finite values are ignored, and so are values outside an
742
- * explicit `domain` (the upper edge itself belongs to the last bin).
743
- * @param bins - Bucket count; a non-finite or sub-1 request falls back to 1, and `undefined`
744
- * to {@link DEFAULT_BINS}.
745
- * @param domain - The x range. Omitted: the data's extent. A single distinct value is
746
- * widened so it lands in a middle bin rather than on an edge.
747
- * @returns The counts and the domain they span.
748
- */
749
- function binValues(values, bins, domain) {
750
- const count = bins === void 0 ? 32 : Number.isFinite(bins) ? Math.max(1, Math.floor(bins)) : 1;
751
- const finite = [];
752
- for (let index = 0; index < values.length; index += 1) {
753
- const value = values[index];
754
- if (value !== void 0 && Number.isFinite(value)) finite.push(value);
755
- }
756
- const [low, high] = domain ? usableDomain(domain[0], domain[1]) : usableDomain(...extent(finite));
757
- const counts = new Array(count).fill(0);
758
- const span = high - low;
759
- for (const value of finite) {
760
- if (value < low || value > high) continue;
761
- const index = Math.min(count - 1, Math.floor((value - low) / span * count));
762
- counts[index] = (counts[index] ?? 0) + 1;
763
- }
764
- return {
765
- counts,
766
- domain: [low, high]
767
- };
768
- }
769
- /**
770
- * Take pre-binned counts as given, with the junk removed.
771
- *
772
- * @param counts - One count per bin, left to right.
773
- * @param domain - The x range the bins span.
774
- * @returns The counts with every non-finite or negative entry set to 0, and a usable domain.
775
- */
776
- function cleanCounts(counts, domain) {
777
- return {
778
- counts: Array.from(counts, (value) => Number.isFinite(value) && value > 0 ? value : 0),
779
- domain: usableDomain(domain[0], domain[1])
780
- };
781
- }
782
- /**
783
- * The bin containing `x`, or `null` when `x` is not finite, outside `domain`, or there are
784
- * no bins. The domain's upper edge belongs to the last bin.
785
- */
786
- function binAt(binCount, domain, x) {
787
- if (x === null || x === void 0 || !Number.isFinite(x) || binCount < 1) return null;
788
- const [low, high] = domain;
789
- if (x < low || x > high) return null;
790
- return Math.min(binCount - 1, Math.floor((x - low) / (high - low) * binCount));
791
- }
792
- /**
793
- * One SVG path `d` drawing every non-empty bar as a rectangle from the baseline.
794
- *
795
- * @param counts - The bins' counts.
796
- * @param yScale - Maps a count to a pixel `y`.
797
- * @param area - The plot area; the bins fill `x0`…`x1` and stand on `y0`.
798
- * @param select - `{ skip: null }` (the default) draws every bar; `{ only: i }` draws just
799
- * bin `i`; `{ skip: i }` draws all but bin `i` — so a highlighted bin is its own path.
800
- */
801
- function barsPath(counts, yScale, area, select = { skip: null }) {
802
- const width = (area.x1 - area.x0) / Math.max(1, counts.length);
803
- const barWidth = Math.max(.5, width > 3 ? width - .5 : width);
804
- const parts = [];
805
- counts.forEach((count, index) => {
806
- if (count <= 0) return;
807
- if ("only" in select ? index !== select.only : index === select.skip) return;
808
- const x = area.x0 + index * width;
809
- const y = yScale.project(count);
810
- if (!Number.isFinite(y)) return;
811
- parts.push(`M${x.toFixed(2)} ${area.y0}V${y.toFixed(2)}h${barWidth.toFixed(2)}V${area.y0}z`);
812
- });
813
- return parts.join("");
814
- }
815
- /** The largest count, at least 1, so an empty or all-zero histogram still has a y axis. */
816
- function tallest(...series) {
817
- let max = 1;
818
- for (const counts of series) for (const count of counts) if (count > max) max = count;
819
- return max;
820
- }
821
- //#endregion
822
- //#region src/ThresholdRule.tsx
823
- /** A dashed vertical rule at `value`; nothing when it is missing or not finite. */
824
- function ThresholdRule({ value, xScale, area }) {
825
- if (value === void 0 || !Number.isFinite(value)) return null;
826
- const x = xScale.project(value);
827
- return /* @__PURE__ */ jsx("line", {
828
- "data-threshold": "",
829
- x1: x,
830
- x2: x,
831
- y1: area.y0,
832
- y2: area.y1,
833
- stroke: "currentColor",
834
- strokeWidth: 1.25,
835
- strokeDasharray: "3 2"
836
- });
837
- }
838
- //#endregion
839
- //#region src/Histogram.tsx
840
- /**
841
- * One distribution as a bar chart over equal-width bins.
842
- *
843
- * @remarks
844
- * An SVG `role="img"` named by `label`. `threshold` draws a dashed decision rule, `markers`
845
- * tick the x axis, `bands` shade x ranges, `onHover` adds a crosshair and the x under it,
846
- * `onPick` reports the x of a click, and `cursor` draws the bin containing an x chosen
847
- * elsewhere in the selection colour (`--signal`) — no highlight when it lies outside the
848
- * domain. Empty data draws an empty frame. For two classes sharing a threshold use
796
+ //#region src/colormap.ts
797
+ const ANCHORS = {
798
+ viridis: [
799
+ [
800
+ 68,
801
+ 1,
802
+ 84
803
+ ],
804
+ [
805
+ 71,
806
+ 44,
807
+ 122
808
+ ],
809
+ [
810
+ 59,
811
+ 81,
812
+ 139
813
+ ],
814
+ [
815
+ 44,
816
+ 113,
817
+ 142
818
+ ],
819
+ [
820
+ 33,
821
+ 144,
822
+ 141
823
+ ],
824
+ [
825
+ 39,
826
+ 173,
827
+ 129
828
+ ],
829
+ [
830
+ 92,
831
+ 200,
832
+ 99
833
+ ],
834
+ [
835
+ 170,
836
+ 220,
837
+ 50
838
+ ],
839
+ [
840
+ 253,
841
+ 231,
842
+ 37
843
+ ]
844
+ ],
845
+ magma: [
846
+ [
847
+ 0,
848
+ 0,
849
+ 4
850
+ ],
851
+ [
852
+ 29,
853
+ 17,
854
+ 71
855
+ ],
856
+ [
857
+ 81,
858
+ 18,
859
+ 124
860
+ ],
861
+ [
862
+ 131,
863
+ 38,
864
+ 129
865
+ ],
866
+ [
867
+ 183,
868
+ 55,
869
+ 121
870
+ ],
871
+ [
872
+ 231,
873
+ 82,
874
+ 99
875
+ ],
876
+ [
877
+ 252,
878
+ 137,
879
+ 97
880
+ ],
881
+ [
882
+ 254,
883
+ 196,
884
+ 136
885
+ ],
886
+ [
887
+ 252,
888
+ 253,
889
+ 191
890
+ ]
891
+ ],
892
+ inferno: [
893
+ [
894
+ 0,
895
+ 0,
896
+ 4
897
+ ],
898
+ [
899
+ 33,
900
+ 12,
901
+ 74
902
+ ],
903
+ [
904
+ 87,
905
+ 16,
906
+ 110
907
+ ],
908
+ [
909
+ 138,
910
+ 34,
911
+ 106
912
+ ],
913
+ [
914
+ 188,
915
+ 55,
916
+ 84
917
+ ],
918
+ [
919
+ 228,
920
+ 90,
921
+ 49
922
+ ],
923
+ [
924
+ 249,
925
+ 142,
926
+ 9
927
+ ],
928
+ [
929
+ 249,
930
+ 203,
931
+ 53
932
+ ],
933
+ [
934
+ 252,
935
+ 255,
936
+ 164
937
+ ]
938
+ ],
939
+ blueOrange: [
940
+ [
941
+ 0,
942
+ 70,
943
+ 140
944
+ ],
945
+ [
946
+ 33,
947
+ 90,
948
+ 158
949
+ ],
950
+ [
951
+ 64,
952
+ 112,
953
+ 172
954
+ ],
955
+ [
956
+ 92,
957
+ 133,
958
+ 185
959
+ ],
960
+ [
961
+ 121,
962
+ 155,
963
+ 198
964
+ ],
965
+ [
966
+ 150,
967
+ 176,
968
+ 211
969
+ ],
970
+ [
971
+ 179,
972
+ 198,
973
+ 222
974
+ ],
975
+ [
976
+ 209,
977
+ 220,
978
+ 233
979
+ ],
980
+ [
981
+ 242,
982
+ 242,
983
+ 242
984
+ ],
985
+ [
986
+ 230,
987
+ 216,
988
+ 207
989
+ ],
990
+ [
991
+ 216,
992
+ 190,
993
+ 175
994
+ ],
995
+ [
996
+ 201,
997
+ 165,
998
+ 144
999
+ ],
1000
+ [
1001
+ 186,
1002
+ 140,
1003
+ 113
1004
+ ],
1005
+ [
1006
+ 170,
1007
+ 116,
1008
+ 83
1009
+ ],
1010
+ [
1011
+ 153,
1012
+ 91,
1013
+ 52
1014
+ ],
1015
+ [
1016
+ 136,
1017
+ 67,
1018
+ 13
1019
+ ],
1020
+ [
1021
+ 113,
1022
+ 52,
1023
+ 0
1024
+ ]
1025
+ ],
1026
+ cividis: [
1027
+ [
1028
+ 0,
1029
+ 34,
1030
+ 78
1031
+ ],
1032
+ [
1033
+ 18,
1034
+ 53,
1035
+ 112
1036
+ ],
1037
+ [
1038
+ 59,
1039
+ 73,
1040
+ 108
1041
+ ],
1042
+ [
1043
+ 87,
1044
+ 93,
1045
+ 109
1046
+ ],
1047
+ [
1048
+ 112,
1049
+ 113,
1050
+ 115
1051
+ ],
1052
+ [
1053
+ 138,
1054
+ 135,
1055
+ 121
1056
+ ],
1057
+ [
1058
+ 165,
1059
+ 157,
1060
+ 116
1061
+ ],
1062
+ [
1063
+ 196,
1064
+ 182,
1065
+ 101
1066
+ ],
1067
+ [
1068
+ 254,
1069
+ 232,
1070
+ 56
1071
+ ]
1072
+ ]
1073
+ };
1074
+ /** The names of the shipped maps. */
1075
+ const COLORMAPS = [
1076
+ "viridis",
1077
+ "cividis",
1078
+ "magma",
1079
+ "inferno",
1080
+ "blueOrange"
1081
+ ];
1082
+ /** The maps that run through a neutral middle, for a signed value: use them over a domain centred on zero. */
1083
+ const DIVERGING_COLORMAPS = ["blueOrange"];
1084
+ /**
1085
+ * Whether a map is diverging.
1086
+ *
1087
+ * @param name - The map.
1088
+ * @returns `true` for a map meant for a signed value around zero.
1089
+ */
1090
+ function isDivergingColormap(name) {
1091
+ return DIVERGING_COLORMAPS.includes(name);
1092
+ }
1093
+ /**
1094
+ * A domain centred on zero that holds a given one: `[-m, m]` with `m` the largest absolute end.
1095
+ * Feed it a diverging map so the middle colour means zero.
1096
+ *
1097
+ * @param domain - `[low, high]`, or the values to cover.
1098
+ * @returns `[-m, m]`; `[-1, 1]` when no end is finite and non-zero.
1099
+ */
1100
+ function symmetricDomain(domain) {
1101
+ let m = 0;
1102
+ for (const v of domain) if (Number.isFinite(v) && Math.abs(v) > m) m = Math.abs(v);
1103
+ return m > 0 ? [-m, m] : [-1, 1];
1104
+ }
1105
+ /**
1106
+ * The colour of `t` on a map.
1107
+ *
1108
+ * @param name - The map.
1109
+ * @param t - Position in `[0, 1]`; clamped. A non-finite `t` gives the map's low end.
1110
+ * @returns A CSS `rgb(r g b)` colour.
1111
+ */
1112
+ function colormap(name, t) {
1113
+ const [r, g, b] = colormapRgb(name, t);
1114
+ return `rgb(${r} ${g} ${b})`;
1115
+ }
1116
+ /**
1117
+ * The colour of `t` on a map, as integer channels.
1118
+ *
1119
+ * @param name - The map.
1120
+ * @param t - Position in `[0, 1]`; clamped.
1121
+ * @returns `[r, g, b]`, each 0–255.
1122
+ */
1123
+ function colormapRgb(name, t) {
1124
+ const anchors = ANCHORS[name];
1125
+ const scaled = (Number.isFinite(t) ? Math.min(1, Math.max(0, t)) : 0) * (anchors.length - 1);
1126
+ const i = Math.min(anchors.length - 2, Math.floor(scaled));
1127
+ const f = scaled - i;
1128
+ const a = anchors[i];
1129
+ const b = anchors[i + 1];
1130
+ return [
1131
+ Math.round(a[0] + f * (b[0] - a[0])),
1132
+ Math.round(a[1] + f * (b[1] - a[1])),
1133
+ Math.round(a[2] + f * (b[2] - a[2]))
1134
+ ];
1135
+ }
1136
+ /**
1137
+ * A value's colour on a map, over a domain.
1138
+ *
1139
+ * @param name - The map.
1140
+ * @param value - The value.
1141
+ * @param domain - `[low, high]`: low maps to the map's start. A reversed domain reverses the map.
1142
+ * For a diverging map pass a domain centred on zero (`symmetricDomain`).
1143
+ * @returns A CSS colour.
1144
+ */
1145
+ function colormapValue(name, value, domain) {
1146
+ const [low, high] = domain;
1147
+ const span = high - low;
1148
+ return colormap(name, span === 0 ? 0 : (value - low) / span);
1149
+ }
1150
+ /**
1151
+ * A CSS `linear-gradient` of a map, for a legend bar.
1152
+ *
1153
+ * @param name - The map.
1154
+ * @param direction - The gradient's direction. Defaults to `to right`.
1155
+ * @returns A CSS `background-image` value.
1156
+ */
1157
+ function colormapGradient(name, direction = "to right") {
1158
+ const anchors = ANCHORS[name];
1159
+ return `linear-gradient(${direction}, ${anchors.map(([r, g, b], i) => `rgb(${r} ${g} ${b}) ${(i / (anchors.length - 1) * 100).toFixed(1)}%`).join(", ")})`;
1160
+ }
1161
+ //#endregion
1162
+ //#region src/ColormapLegend.tsx
1163
+ /**
1164
+ * The scale of a colour map, shown beside the map: every chart or map shows its scale, with units.
1165
+ */
1166
+ const defaultFormat = (value) => String(Number(value.toPrecision(3)));
1167
+ /** The tick values: a given list inside the domain, or round values, or the default for the layout. */
1168
+ function tickValues(ticks, domain, symmetric) {
1169
+ const [low, high] = domain;
1170
+ const inside = (v) => Number.isFinite(v) && v >= Math.min(low, high) - 1e-12 && v <= Math.max(low, high) + 1e-12;
1171
+ if (typeof ticks === "number") {
1172
+ const span = Math.abs(high - low);
1173
+ return [
1174
+ low,
1175
+ ...linearScale([low, high], 0, 1).ticks(ticks).map((tick) => tick.value).filter((v) => inside(v) && Math.abs(v - low) > .08 * span && Math.abs(v - high) > .08 * span),
1176
+ high
1177
+ ];
1178
+ }
1179
+ if (ticks !== void 0) return ticks.filter(inside);
1180
+ return symmetric ? [
1181
+ low,
1182
+ 0,
1183
+ high
1184
+ ] : [low, high];
1185
+ }
1186
+ /** `marker` as a list of `{ value, label }`, in domain, in the order given. */
1187
+ function markerList(marker, low, high) {
1188
+ if (marker === void 0) return [];
1189
+ const list = typeof marker === "number" || !Array.isArray(marker) ? [marker] : [...marker];
1190
+ const lo = Math.min(low, high) - 1e-12;
1191
+ const hi = Math.max(low, high) + 1e-12;
1192
+ return list.map((entry) => typeof entry === "number" ? { value: entry } : entry).filter((entry) => Number.isFinite(entry.value) && entry.value >= lo && entry.value <= hi);
1193
+ }
1194
+ /** The cap on a clipped end: an arrow in the map's end colour, pointing outward. */
1195
+ function EndCap({ map, end, orientation }) {
1196
+ const horizontal = orientation === "horizontal";
1197
+ const clip = horizontal ? end === "high" ? "polygon(0 0, 100% 50%, 0 100%)" : "polygon(100% 0, 0 50%, 100% 100%)" : end === "high" ? "polygon(50% 0, 100% 100%, 0 100%)" : "polygon(0 0, 100% 0, 50% 100%)";
1198
+ return /* @__PURE__ */ jsx("span", {
1199
+ "aria-hidden": true,
1200
+ "data-cap": end,
1201
+ className: `absolute ${horizontal ? end === "high" ? "left-full top-0.5 ml-px h-2 w-1.5" : "right-full top-0.5 mr-px h-2 w-1.5" : end === "high" ? "bottom-full left-0 mb-px h-1.5 w-2.5" : "top-full left-0 mt-px h-1.5 w-2.5"}`,
1202
+ style: {
1203
+ backgroundColor: colormap(map, end === "high" ? 1 : 0),
1204
+ clipPath: clip
1205
+ }
1206
+ });
1207
+ }
1208
+ /**
1209
+ * A gradient bar with its values and unit.
1210
+ *
1211
+ * - **Horizontal**: one line, "Edge error 0 [bar] 2.5 px". With `ticks` or `symmetric` the values
1212
+ * sit under the bar at their position instead.
1213
+ * - **Vertical**: the label above a column bar, the high end at the top, the values beside the
1214
+ * bar at their position, and the unit after the label.
1215
+ *
1216
+ * `marker` ticks values on the bar (a threshold, the value under a cursor) and `clipped` says
1217
+ * the scale saturates at an end, with a cap and `≥` / `≤` on its value.
1218
+ *
1219
+ * The bar is decorative; the label, the values and the markers' text carry the meaning.
1220
+ */
1221
+ function ColormapLegend({ map, domain, unit, label, format = defaultFormat, orientation = "horizontal", ticks, symmetric = false, marker, clipped, length = 160, className }) {
1222
+ const [low, high] = symmetric ? symmetricDomain(domain) : domain;
1223
+ const span = high - low;
1224
+ const end = (value) => unit ? `${format(value)} ${unit}` : format(value);
1225
+ const fraction = (value) => span === 0 ? 0 : (value - low) / span;
1226
+ const markers = markerList(marker, low, high);
1227
+ const capLow = clipped === "low" || clipped === "both";
1228
+ const capHigh = clipped === "high" || clipped === "both";
1229
+ const text = (value, isLow, isHigh) => `${isHigh && capHigh ? "≥ " : isLow && capLow ? "≤ " : ""}${format(value)}`;
1230
+ const markerText = (entry) => entry.label ?? end(entry.value);
1231
+ if (orientation === "horizontal" && ticks === void 0 && !symmetric && markers.length === 0) return /* @__PURE__ */ jsxs("div", {
1232
+ className: cn("flex items-center gap-2 text-xs text-fg-muted", className),
1233
+ "data-colormap": map,
1234
+ children: [
1235
+ /* @__PURE__ */ jsx("span", { children: label }),
1236
+ /* @__PURE__ */ jsx("span", {
1237
+ className: "font-mono tabular-nums",
1238
+ children: capLow ? `≤ ${end(low)}` : end(low)
1239
+ }),
1240
+ /* @__PURE__ */ jsxs("span", {
1241
+ "aria-hidden": true,
1242
+ className: "relative h-2 w-24 rounded-full",
1243
+ style: { backgroundImage: colormapGradient(map) },
1244
+ children: [capLow && /* @__PURE__ */ jsx(EndCap, {
1245
+ map,
1246
+ end: "low",
1247
+ orientation: "horizontal"
1248
+ }), capHigh && /* @__PURE__ */ jsx(EndCap, {
1249
+ map,
1250
+ end: "high",
1251
+ orientation: "horizontal"
1252
+ })]
1253
+ }),
1254
+ /* @__PURE__ */ jsx("span", {
1255
+ className: "font-mono tabular-nums",
1256
+ children: capHigh ? `≥ ${end(high)}` : end(high)
1257
+ })
1258
+ ]
1259
+ });
1260
+ const values = tickValues(ticks, [low, high], symmetric);
1261
+ if (capLow && !values.includes(low)) values.unshift(low);
1262
+ if (capHigh && !values.includes(high)) values.push(high);
1263
+ const tickText = (value) => text(value, value === low, value === high);
1264
+ if (orientation === "horizontal") return /* @__PURE__ */ jsxs("div", {
1265
+ className: cn("flex items-start gap-2 text-xs text-fg-muted", className),
1266
+ "data-colormap": map,
1267
+ children: [
1268
+ /* @__PURE__ */ jsx("span", {
1269
+ className: markers.length > 0 ? "pt-4" : void 0,
1270
+ children: label
1271
+ }),
1272
+ /* @__PURE__ */ jsxs("div", {
1273
+ className: cn("relative w-32 pb-4", markers.length > 0 && "pt-4", (capLow || capHigh) && "mx-2"),
1274
+ children: [
1275
+ /* @__PURE__ */ jsxs("div", {
1276
+ className: "relative mt-0.5 h-2",
1277
+ children: [
1278
+ /* @__PURE__ */ jsx("div", {
1279
+ "aria-hidden": true,
1280
+ className: "absolute inset-0 rounded-full",
1281
+ style: { backgroundImage: colormapGradient(map) }
1282
+ }),
1283
+ capLow && /* @__PURE__ */ jsx(EndCap, {
1284
+ map,
1285
+ end: "low",
1286
+ orientation: "horizontal"
1287
+ }),
1288
+ capHigh && /* @__PURE__ */ jsx(EndCap, {
1289
+ map,
1290
+ end: "high",
1291
+ orientation: "horizontal"
1292
+ }),
1293
+ markers.map((entry) => /* @__PURE__ */ jsx("span", {
1294
+ "aria-hidden": true,
1295
+ "data-marker-tick": "",
1296
+ className: "absolute -top-0.5 h-3 w-0.5 -translate-x-1/2 rounded-full bg-fg ring-1 ring-surface",
1297
+ style: { left: `${(fraction(entry.value) * 100).toFixed(2)}%` }
1298
+ }, `m-${entry.value}-${entry.label ?? ""}`))
1299
+ ]
1300
+ }),
1301
+ markers.map((entry) => /* @__PURE__ */ jsx("span", {
1302
+ "data-marker": "",
1303
+ className: "absolute top-0 -translate-x-1/2 whitespace-nowrap font-mono text-[10px] leading-none tabular-nums text-fg",
1304
+ style: { left: `${(fraction(entry.value) * 100).toFixed(2)}%` },
1305
+ children: markerText(entry)
1306
+ }, `mt-${entry.value}-${entry.label ?? ""}`)),
1307
+ values.map((value) => /* @__PURE__ */ jsx("span", {
1308
+ "data-tick": "",
1309
+ className: cn("absolute -translate-x-1/2 font-mono text-[10px] tabular-nums", markers.length > 0 ? "top-7" : "top-3"),
1310
+ style: { left: `${(fraction(value) * 100).toFixed(2)}%` },
1311
+ children: tickText(value)
1312
+ }, value))
1313
+ ]
1314
+ }),
1315
+ unit && /* @__PURE__ */ jsx("span", {
1316
+ className: cn("text-fg-subtle", markers.length > 0 && "pt-4"),
1317
+ children: unit
1318
+ })
1319
+ ]
1320
+ });
1321
+ return /* @__PURE__ */ jsxs("div", {
1322
+ className: cn("inline-flex flex-col gap-1.5 text-xs text-fg-muted", className),
1323
+ "data-colormap": map,
1324
+ "data-orientation": "vertical",
1325
+ children: [/* @__PURE__ */ jsxs("span", { children: [label, unit && /* @__PURE__ */ jsx("span", {
1326
+ className: "ml-1 text-fg-subtle",
1327
+ children: unit
1328
+ })] }), /* @__PURE__ */ jsxs("div", {
1329
+ className: "relative my-1.5 flex",
1330
+ style: { height: length },
1331
+ children: [
1332
+ /* @__PURE__ */ jsxs("div", {
1333
+ className: "relative w-2.5",
1334
+ children: [
1335
+ /* @__PURE__ */ jsx("div", {
1336
+ "aria-hidden": true,
1337
+ className: "absolute inset-0 rounded-full",
1338
+ style: { backgroundImage: colormapGradient(map, "to top") }
1339
+ }),
1340
+ capLow && /* @__PURE__ */ jsx(EndCap, {
1341
+ map,
1342
+ end: "low",
1343
+ orientation: "vertical"
1344
+ }),
1345
+ capHigh && /* @__PURE__ */ jsx(EndCap, {
1346
+ map,
1347
+ end: "high",
1348
+ orientation: "vertical"
1349
+ }),
1350
+ markers.map((entry) => /* @__PURE__ */ jsx("span", {
1351
+ "aria-hidden": true,
1352
+ "data-marker-tick": "",
1353
+ className: "absolute -left-0.5 -right-0.5 h-0.5 translate-y-1/2 rounded-full bg-fg ring-1 ring-surface",
1354
+ style: { bottom: `${(fraction(entry.value) * 100).toFixed(2)}%` }
1355
+ }, `m-${entry.value}-${entry.label ?? ""}`))
1356
+ ]
1357
+ }),
1358
+ /* @__PURE__ */ jsx("div", {
1359
+ className: "relative ml-1.5 min-w-8",
1360
+ children: values.map((value) => /* @__PURE__ */ jsx("span", {
1361
+ "data-tick": "",
1362
+ className: "absolute left-0 translate-y-1/2 whitespace-nowrap font-mono text-[10px] leading-none tabular-nums",
1363
+ style: { bottom: `${(fraction(value) * 100).toFixed(2)}%` },
1364
+ children: tickText(value)
1365
+ }, value))
1366
+ }),
1367
+ markers.length > 0 && /* @__PURE__ */ jsx("div", {
1368
+ className: "relative ml-1.5 min-w-8",
1369
+ children: markers.map((entry) => /* @__PURE__ */ jsx("span", {
1370
+ "data-marker": "",
1371
+ className: "absolute left-0 translate-y-1/2 whitespace-nowrap font-mono text-[10px] leading-none tabular-nums text-fg",
1372
+ style: { bottom: `${(fraction(entry.value) * 100).toFixed(2)}%` },
1373
+ children: markerText(entry)
1374
+ }, `mt-${entry.value}-${entry.label ?? ""}`))
1375
+ })
1376
+ ]
1377
+ })]
1378
+ });
1379
+ }
1380
+ //#endregion
1381
+ //#region src/scatter.ts
1382
+ /**
1383
+ * The arithmetic behind `ScatterChart`: which point is under the pointer, which colour step a
1384
+ * value falls in, and the domain a colour scale covers.
1385
+ *
1386
+ * Pure: the component is a thin list of SVG elements over it.
1387
+ */
1388
+ /** The number of colour steps a value-coloured series is quantised into: one path each. */
1389
+ const SCATTER_COLOUR_STEPS = 24;
1390
+ /**
1391
+ * The projected point nearest to a position, within a radius.
1392
+ *
1393
+ * @param xy - Flat `[x0, y0, x1, y1, …]` in the plot's own units (viewBox units); a non-finite
1394
+ * coordinate is skipped.
1395
+ * @param x - The query's x.
1396
+ * @param y - The query's y.
1397
+ * @param radius - How far from a point the query still picks it.
1398
+ * @returns The index of the nearest point (the lower index on a tie), or `-1`.
1399
+ */
1400
+ function nearestProjected(xy, x, y, radius) {
1401
+ const limit = radius * radius;
1402
+ let best = -1;
1403
+ let bestD = Infinity;
1404
+ const count = Math.floor(xy.length / 2);
1405
+ for (let i = 0; i < count; i++) {
1406
+ const dx = xy[2 * i] - x;
1407
+ const dy = xy[2 * i + 1] - y;
1408
+ const d = dx * dx + dy * dy;
1409
+ if (d <= limit && d < bestD) {
1410
+ best = i;
1411
+ bestD = d;
1412
+ }
1413
+ }
1414
+ return best;
1415
+ }
1416
+ /**
1417
+ * The colour step of a value.
1418
+ *
1419
+ * @param value - The point's value.
1420
+ * @param domain - `[low, high]`: `low` maps to the first step.
1421
+ * @param steps - How many steps. Defaults to `SCATTER_COLOUR_STEPS`.
1422
+ * @returns An integer in `[0, steps - 1]`; `-1` for a non-finite value; a degenerate domain puts
1423
+ * every value in step `0`.
1424
+ */
1425
+ function colourStep(value, domain, steps = 24) {
1426
+ if (!Number.isFinite(value)) return -1;
1427
+ const [low, high] = domain;
1428
+ if (!(high > low)) return 0;
1429
+ return Math.min(steps - 1, Math.max(0, Math.floor((value - low) / (high - low) * steps)));
1430
+ }
1431
+ /**
1432
+ * The domain a value colouring covers.
1433
+ *
1434
+ * @param values - Every point's value; non-finite ones are ignored.
1435
+ * @param symmetric - Centre it on zero, for a diverging map.
1436
+ * @param given - A domain the caller fixed. It wins, centred if `symmetric`.
1437
+ * @returns `[low, high]`; `[0, 1]` when there is no finite value.
1438
+ */
1439
+ function colourDomain(values, symmetric, given) {
1440
+ let low = Infinity;
1441
+ let high = -Infinity;
1442
+ if (given) [low, high] = given;
1443
+ else {
1444
+ for (const v of values) {
1445
+ if (!Number.isFinite(v)) continue;
1446
+ if (v < low) low = v;
1447
+ if (v > high) high = v;
1448
+ }
1449
+ if (low > high) return symmetric ? [-1, 1] : [0, 1];
1450
+ }
1451
+ return symmetric ? symmetricDomain([low, high]) : [low, high];
1452
+ }
1453
+ //#endregion
1454
+ //#region src/ScatterChart.tsx
1455
+ /**
1456
+ * A scatter plot: points over two numeric axes, each optionally coloured by a third value.
1457
+ *
1458
+ * Points are drawn as a few batched paths (one per series, or one per colour step with
1459
+ * `colourBy`), never one element per point, and the pointer is resolved from the projected
1460
+ * positions, not from the DOM. A few thousand points stay cheap.
1461
+ */
1462
+ /** How near the pointer must be to a point, in viewBox units, to pick it. */
1463
+ const PICK_RADIUS = 10;
1464
+ const MUTED = "var(--fg-subtle)";
1465
+ const formatValue = (value) => Math.abs(value) >= 100 ? value.toFixed(0) : String(Number(value.toPrecision(3)));
1466
+ /**
1467
+ * A scatter plot over a shared frame — residuals against position, one run against another.
1468
+ *
1469
+ * @remarks
1470
+ * An SVG `role="img"` named by `label`, with the series legend (or, with `colourBy`, the colour
1471
+ * scale) as real text under it. Series are told apart by the legend's names, never by colour
1472
+ * alone. `referenceLines` mark a value on either axis; `onHover` rings the nearest point and
1473
+ * reads its numbers, `onPick` reports a click's point, and `highlighted` rings one chosen
1474
+ * elsewhere. Picking is by pointer, so the same points must be reachable from a table beside
1475
+ * the chart. A point with a non-finite coordinate is skipped.
1476
+ */
1477
+ function ScatterChart({ series, label, xLabel, yLabel, xDomain, yDomain, colourBy, referenceLines, markerSize = 4, underlay, highlighted, onHover, onPick, footer, showLegend = true, variant = "panel", className, height = 200 }) {
1478
+ const clipId = useId();
1479
+ const [fluidRef, fluidSize] = useFluidSize(height);
1480
+ const size = variant === "fluid" ? fluidSize : void 0;
1481
+ const area = areaFor(variant, size);
1482
+ const allX = [];
1483
+ const allY = [];
1484
+ for (const entry of series) for (const p of entry.points) {
1485
+ allX.push(p.x);
1486
+ allY.push(p.y);
1487
+ }
1488
+ const xScale = linearScale(xDomain ?? paddedExtent(allX), area.x0, area.x1);
1489
+ const yScale = linearScale(yDomain ?? paddedExtent(allY), area.y0, area.y1);
1490
+ const symmetric = colourBy ? colourBy.symmetric ?? isDivergingColormap(colourBy.map) : false;
1491
+ const domain = useMemo(() => colourBy ? colourDomain(series.flatMap((s) => s.points.map((p) => p.value ?? NaN)), symmetric, colourBy.domain) : null, [
1492
+ series,
1493
+ colourBy,
1494
+ symmetric
1495
+ ]);
1496
+ const projected = useMemo(() => {
1497
+ const xy = [];
1498
+ const owner = [];
1499
+ series.forEach((entry, s) => {
1500
+ entry.points.forEach((p, index) => {
1501
+ const px = xScale.project(p.x);
1502
+ const py = yScale.project(p.y);
1503
+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y) || !Number.isFinite(px) || !Number.isFinite(py)) return;
1504
+ xy.push(px, py);
1505
+ owner.push({
1506
+ series: s,
1507
+ index
1508
+ });
1509
+ });
1510
+ });
1511
+ return {
1512
+ xy,
1513
+ owner
1514
+ };
1515
+ }, [
1516
+ series,
1517
+ xScale.domain[0],
1518
+ xScale.domain[1],
1519
+ yScale.domain[0],
1520
+ yScale.domain[1],
1521
+ area.x0,
1522
+ area.x1,
1523
+ area.y0,
1524
+ area.y1
1525
+ ]);
1526
+ const batches = useMemo(() => {
1527
+ const out = [];
1528
+ let cursor = 0;
1529
+ series.forEach((entry, s) => {
1530
+ const parts = /* @__PURE__ */ new Map();
1531
+ while (cursor < projected.owner.length && projected.owner[cursor].series === s) {
1532
+ const point = entry.points[projected.owner[cursor].index];
1533
+ const step = colourBy && domain ? colourStep(point.value ?? NaN, domain) : 0;
1534
+ parts.set(step, `${parts.get(step) ?? ""}M${projected.xy[2 * cursor].toFixed(2)} ${projected.xy[2 * cursor + 1].toFixed(2)}h0`);
1535
+ cursor++;
1536
+ }
1537
+ for (const [step, d] of parts) {
1538
+ let colour;
1539
+ if (!colourBy) colour = entry.colour ?? seriesColour(s);
1540
+ else if (step < 0) colour = MUTED;
1541
+ else {
1542
+ const [r, g, b] = colormapRgb(colourBy.map, (step + .5) / 24);
1543
+ colour = `rgb(${r} ${g} ${b})`;
1544
+ }
1545
+ out.push({
1546
+ key: `${s}|${step}`,
1547
+ d,
1548
+ colour
1549
+ });
1550
+ }
1551
+ });
1552
+ return out;
1553
+ }, [
1554
+ series,
1555
+ projected,
1556
+ colourBy,
1557
+ domain
1558
+ ]);
1559
+ const [hover, setHover] = useState(null);
1560
+ const pickAt = (event) => {
1561
+ const svg = event.currentTarget.ownerSVGElement;
1562
+ const ctm = svg?.getScreenCTM();
1563
+ let x = event.clientX;
1564
+ let y = event.clientY;
1565
+ if (svg && ctm) {
1566
+ const point = svg.createSVGPoint();
1567
+ point.x = event.clientX;
1568
+ point.y = event.clientY;
1569
+ const local = point.matrixTransform(ctm.inverse());
1570
+ x = local.x;
1571
+ y = local.y;
1572
+ }
1573
+ const found = nearestProjected(projected.xy, x, y, PICK_RADIUS);
1574
+ return found < 0 ? null : pointOf(found);
1575
+ };
1576
+ const pointOf = (k) => {
1577
+ const { series: s, index } = projected.owner[k];
1578
+ const entry = series[s];
1579
+ const point = entry.points[index];
1580
+ return {
1581
+ series: entry.name,
1582
+ index,
1583
+ x: point.x,
1584
+ y: point.y,
1585
+ value: point.value
1586
+ };
1587
+ };
1588
+ const ringed = hover ?? (highlighted ? findPick(series, highlighted) : null);
1589
+ const ringAt = ringed ? {
1590
+ cx: xScale.project(ringed.x),
1591
+ cy: yScale.project(ringed.y)
1592
+ } : null;
1593
+ const interactive = onHover !== void 0 || onPick !== void 0;
1594
+ const radius = markerSize / 2;
1595
+ return /* @__PURE__ */ jsxs(Frame, {
1596
+ xScale,
1597
+ yScale,
1598
+ xLabel,
1599
+ yLabel,
1600
+ label,
1601
+ variant,
1602
+ className,
1603
+ size,
1604
+ figureRef: variant === "fluid" ? fluidRef : void 0,
1605
+ footer: /* @__PURE__ */ jsxs("div", {
1606
+ className: "flex flex-col gap-1",
1607
+ children: [colourBy && domain ? /* @__PURE__ */ jsx(ColormapLegend, {
1608
+ map: colourBy.map,
1609
+ domain,
1610
+ label: colourBy.label,
1611
+ unit: colourBy.unit,
1612
+ symmetric,
1613
+ format: formatValue
1614
+ }) : showLegend && /* @__PURE__ */ jsx(Legend, { items: series.map((entry, s) => ({
1615
+ label: entry.name,
1616
+ colour: entry.colour ?? seriesColour(s)
1617
+ })) }), footer]
1618
+ }),
1619
+ children: [
1620
+ /* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsx("clipPath", {
1621
+ id: clipId,
1622
+ children: /* @__PURE__ */ jsx("rect", {
1623
+ x: area.x0,
1624
+ y: area.y1,
1625
+ width: area.x1 - area.x0,
1626
+ height: area.y0 - area.y1
1627
+ })
1628
+ }) }),
1629
+ underlay?.(xScale, yScale),
1630
+ referenceLines && referenceLines.length > 0 && /* @__PURE__ */ jsx(ReferenceLines, {
1631
+ lines: referenceLines,
1632
+ xScale,
1633
+ yScale,
1634
+ area
1635
+ }),
1636
+ /* @__PURE__ */ jsxs("g", {
1637
+ clipPath: `url(#${clipId})`,
1638
+ "data-points": "",
1639
+ fill: "none",
1640
+ strokeLinecap: "round",
1641
+ children: [batches.map((batch) => /* @__PURE__ */ jsx("path", {
1642
+ d: batch.d,
1643
+ stroke: "var(--surface)",
1644
+ strokeWidth: markerSize + 1.5,
1645
+ opacity: .7
1646
+ }, batch.key)), batches.map((batch) => /* @__PURE__ */ jsx("path", {
1647
+ "data-batch": batch.key,
1648
+ d: batch.d,
1649
+ stroke: batch.colour,
1650
+ strokeWidth: markerSize
1651
+ }, `p|${batch.key}`))]
1652
+ }),
1653
+ ringAt && /* @__PURE__ */ jsxs("g", {
1654
+ "data-highlight": "",
1655
+ pointerEvents: "none",
1656
+ children: [/* @__PURE__ */ jsx("circle", {
1657
+ ...ringAt,
1658
+ r: radius + 3,
1659
+ fill: "none",
1660
+ stroke: "var(--surface)",
1661
+ strokeWidth: 3.5
1662
+ }), /* @__PURE__ */ jsx("circle", {
1663
+ ...ringAt,
1664
+ r: radius + 3,
1665
+ fill: "none",
1666
+ stroke: "var(--signal)",
1667
+ strokeWidth: 1.75
1668
+ })]
1669
+ }),
1670
+ hover && /* @__PURE__ */ jsx("text", {
1671
+ "data-readout": "",
1672
+ x: xScale.project(hover.x) > (area.x0 + area.x1) / 2 ? area.x1 - 4 : area.x0 + 4,
1673
+ y: area.y1 + 10,
1674
+ textAnchor: xScale.project(hover.x) > (area.x0 + area.x1) / 2 ? "end" : "start",
1675
+ fontSize: 10,
1676
+ fill: "currentColor",
1677
+ children: [`${formatValue(hover.x)}, ${formatValue(hover.y)}`, hover.value !== void 0 ? formatValue(hover.value) : null].filter((part) => part !== null).join(" · ")
1678
+ }),
1679
+ interactive && /* @__PURE__ */ jsx("rect", {
1680
+ "data-plot-target": "",
1681
+ x: area.x0,
1682
+ y: area.y1,
1683
+ width: area.x1 - area.x0,
1684
+ height: area.y0 - area.y1,
1685
+ fill: "transparent",
1686
+ style: { cursor: onPick ? "pointer" : "crosshair" },
1687
+ onPointerMove: (event) => {
1688
+ const next = pickAt(event);
1689
+ setHover(next);
1690
+ onHover?.(next);
1691
+ },
1692
+ onPointerLeave: () => {
1693
+ setHover(null);
1694
+ onHover?.(null);
1695
+ },
1696
+ onClick: (event) => {
1697
+ const picked = pickAt(event);
1698
+ if (picked) onPick?.(picked);
1699
+ }
1700
+ })
1701
+ ]
1702
+ });
1703
+ }
1704
+ /** The extent of the values with 4 % on each side, so a marker on an extreme is not cut by the axis or the frame. */
1705
+ function paddedExtent(values) {
1706
+ const [low, high] = extent(values);
1707
+ const pad = (high - low) * .04;
1708
+ return [low - pad, high + pad];
1709
+ }
1710
+ /** The point a `highlighted` names, or `null` when it names none that exists and is finite. */
1711
+ function findPick(series, at) {
1712
+ const point = series.find((s) => s.name === at.series)?.points[at.index];
1713
+ if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y)) return null;
1714
+ return {
1715
+ series: at.series,
1716
+ index: at.index,
1717
+ x: point.x,
1718
+ y: point.y,
1719
+ value: point.value
1720
+ };
1721
+ }
1722
+ /** Dashed rules across the plot, with their labels at the end. */
1723
+ function ReferenceLines({ lines, xScale, yScale, area }) {
1724
+ return /* @__PURE__ */ jsx("g", {
1725
+ "data-reference-lines": "",
1726
+ children: lines.map((line) => {
1727
+ const horizontal = line.axis === "y";
1728
+ const at = (horizontal ? yScale : xScale).project(line.value);
1729
+ const [lo, hi] = horizontal ? [area.y1, area.y0] : [area.x0, area.x1];
1730
+ if (!Number.isFinite(at) || at < Math.min(lo, hi) - .5 || at > Math.max(lo, hi) + .5) return null;
1731
+ const colour = toneColor(line.tone, "muted");
1732
+ return /* @__PURE__ */ jsxs("g", {
1733
+ "data-reference-line": line.axis,
1734
+ children: [/* @__PURE__ */ jsx("line", {
1735
+ x1: horizontal ? area.x0 : at,
1736
+ x2: horizontal ? area.x1 : at,
1737
+ y1: horizontal ? at : area.y0,
1738
+ y2: horizontal ? at : area.y1,
1739
+ stroke: colour,
1740
+ strokeWidth: 1.25,
1741
+ strokeDasharray: "3 2"
1742
+ }), line.label && /* @__PURE__ */ jsx("text", {
1743
+ x: horizontal ? area.x1 - 3 : at + 3,
1744
+ y: horizontal ? at - 3 : area.y1 + 10,
1745
+ textAnchor: horizontal ? "end" : "start",
1746
+ fontSize: 9,
1747
+ fill: colour,
1748
+ children: line.label
1749
+ })]
1750
+ }, `${line.axis}|${line.value}|${line.label ?? ""}`);
1751
+ })
1752
+ });
1753
+ }
1754
+ //#endregion
1755
+ //#region src/BarChart.tsx
1756
+ /**
1757
+ * Horizontal stacked bars — a per-category breakdown.
1758
+ *
1759
+ * Horizontal because the categories are free text — a defect type, a part family — and a
1760
+ * vertical axis would either truncate them or turn them sideways. Stacked because the
1761
+ * usual question is "of this category, how many landed in each outcome", which is a
1762
+ * proportion of a known total rather than independent counts.
1763
+ */
1764
+ /**
1765
+ * Horizontal stacked bars, one row per category, all on one shared scale (the widest row's
1766
+ * total).
1767
+ *
1768
+ * @remarks
1769
+ * Exposed as an ARIA `table`: each row has a `rowheader` (the category) and a text cell that
1770
+ * spells every non-zero segment out as `"<value> <name>"`, so nothing depends on colour or
1771
+ * on bar width. A row with no non-zero segment shows its total.
1772
+ */
1773
+ function StackedBars({ rows, label, className }) {
1774
+ const widest = Math.max(1, ...rows.map((row) => row.segments.reduce((total, segment) => total + segment.value, 0)));
1775
+ return /* @__PURE__ */ jsx("div", {
1776
+ className: cn("flex flex-col gap-2", className),
1777
+ role: "table",
1778
+ "aria-label": label,
1779
+ children: rows.map((row) => {
1780
+ const total = row.segments.reduce((sum, segment) => sum + segment.value, 0);
1781
+ return /* @__PURE__ */ jsxs("div", {
1782
+ className: "flex items-center gap-3 text-xs",
1783
+ role: "row",
1784
+ children: [
1785
+ /* @__PURE__ */ jsx("span", {
1786
+ className: "w-28 shrink-0 truncate font-mono",
1787
+ role: "rowheader",
1788
+ title: row.label,
1789
+ children: row.label
1790
+ }),
1791
+ /* @__PURE__ */ jsx("div", {
1792
+ className: "flex h-4 flex-1 overflow-hidden rounded-control bg-raised",
1793
+ role: "cell",
1794
+ children: row.segments.map((segment) => segment.value === 0 ? null : /* @__PURE__ */ jsx("div", {
1795
+ className: "h-full",
1796
+ style: {
1797
+ width: `${segment.value / widest * 100}%`,
1798
+ backgroundColor: segment.colour
1799
+ },
1800
+ title: `${segment.name}: ${segment.value}`
1801
+ }, segment.name))
1802
+ }),
1803
+ /* @__PURE__ */ jsx("span", {
1804
+ className: "w-24 shrink-0 text-right font-mono text-fg-muted",
1805
+ role: "cell",
1806
+ children: row.segments.filter((segment) => segment.value > 0).map((segment) => `${segment.value} ${segment.name}`).join(" · ") || `${total}`
1807
+ })
1808
+ ]
1809
+ }, row.label);
1810
+ })
1811
+ });
1812
+ }
1813
+ /** A finite, ordered, non-degenerate domain; `[0, 1]` when `domain` is unusable. */
1814
+ function usableDomain(low, high) {
1815
+ return padDomain(Math.min(low, high), Math.max(low, high));
1816
+ }
1817
+ /**
1818
+ * Bin raw values into `bins` equal-width buckets.
1819
+ *
1820
+ * @param values - The samples. Non-finite values are ignored, and so are values outside an
1821
+ * explicit `domain` (the upper edge itself belongs to the last bin).
1822
+ * @param bins - Bucket count; a non-finite or sub-1 request falls back to 1, and `undefined`
1823
+ * to {@link DEFAULT_BINS}.
1824
+ * @param domain - The x range. Omitted: the data's extent. A single distinct value is
1825
+ * widened so it lands in a middle bin rather than on an edge.
1826
+ * @returns The counts and the domain they span.
1827
+ */
1828
+ function binValues(values, bins, domain) {
1829
+ const count = bins === void 0 ? 32 : Number.isFinite(bins) ? Math.max(1, Math.floor(bins)) : 1;
1830
+ const finite = [];
1831
+ for (let index = 0; index < values.length; index += 1) {
1832
+ const value = values[index];
1833
+ if (value !== void 0 && Number.isFinite(value)) finite.push(value);
1834
+ }
1835
+ const [low, high] = domain ? usableDomain(domain[0], domain[1]) : usableDomain(...extent(finite));
1836
+ const counts = new Array(count).fill(0);
1837
+ const span = high - low;
1838
+ for (const value of finite) {
1839
+ if (value < low || value > high) continue;
1840
+ const index = Math.min(count - 1, Math.floor((value - low) / span * count));
1841
+ counts[index] = (counts[index] ?? 0) + 1;
1842
+ }
1843
+ return {
1844
+ counts,
1845
+ domain: [low, high]
1846
+ };
1847
+ }
1848
+ /**
1849
+ * Take pre-binned counts as given, with the junk removed.
1850
+ *
1851
+ * @param counts - One count per bin, left to right.
1852
+ * @param domain - The x range the bins span.
1853
+ * @returns The counts with every non-finite or negative entry set to 0, and a usable domain.
1854
+ */
1855
+ function cleanCounts(counts, domain) {
1856
+ return {
1857
+ counts: Array.from(counts, (value) => Number.isFinite(value) && value > 0 ? value : 0),
1858
+ domain: usableDomain(domain[0], domain[1])
1859
+ };
1860
+ }
1861
+ /**
1862
+ * The bin containing `x`, or `null` when `x` is not finite, outside `domain`, or there are
1863
+ * no bins. The domain's upper edge belongs to the last bin.
1864
+ */
1865
+ function binAt(binCount, domain, x) {
1866
+ if (x === null || x === void 0 || !Number.isFinite(x) || binCount < 1) return null;
1867
+ const [low, high] = domain;
1868
+ if (x < low || x > high) return null;
1869
+ return Math.min(binCount - 1, Math.floor((x - low) / (high - low) * binCount));
1870
+ }
1871
+ /**
1872
+ * One SVG path `d` drawing every non-empty bar as a rectangle from the baseline.
1873
+ *
1874
+ * @param counts - The bins' counts.
1875
+ * @param yScale - Maps a count to a pixel `y`.
1876
+ * @param area - The plot area; the bins fill `x0`…`x1` and stand on `y0`.
1877
+ * @param select - `{ skip: null }` (the default) draws every bar; `{ only: i }` draws just
1878
+ * bin `i`; `{ skip: i }` draws all but bin `i` — so a highlighted bin is its own path.
1879
+ */
1880
+ function barsPath(counts, yScale, area, select = { skip: null }) {
1881
+ const width = (area.x1 - area.x0) / Math.max(1, counts.length);
1882
+ const barWidth = Math.max(.5, width > 3 ? width - .5 : width);
1883
+ const parts = [];
1884
+ counts.forEach((count, index) => {
1885
+ if (count <= 0) return;
1886
+ if ("only" in select ? index !== select.only : index === select.skip) return;
1887
+ const x = area.x0 + index * width;
1888
+ const y = yScale.project(count);
1889
+ if (!Number.isFinite(y)) return;
1890
+ parts.push(`M${x.toFixed(2)} ${area.y0}V${y.toFixed(2)}h${barWidth.toFixed(2)}V${area.y0}z`);
1891
+ });
1892
+ return parts.join("");
1893
+ }
1894
+ /** The largest count, at least 1, so an empty or all-zero histogram still has a y axis. */
1895
+ function tallest(...series) {
1896
+ let max = 1;
1897
+ for (const counts of series) for (const count of counts) if (count > max) max = count;
1898
+ return max;
1899
+ }
1900
+ //#endregion
1901
+ //#region src/ThresholdRule.tsx
1902
+ /**
1903
+ * The decision threshold of a histogram: a dashed rule across the plot at one x, and — when
1904
+ * the caller can take a new value — a handle on it that a pointer drags and the arrow keys
1905
+ * step.
1906
+ */
1907
+ /** A dashed vertical rule at `value`; nothing when it is missing or not finite. */
1908
+ function ThresholdRule({ value, xScale, area }) {
1909
+ if (value === void 0 || !Number.isFinite(value)) return null;
1910
+ const x = xScale.project(value);
1911
+ return /* @__PURE__ */ jsx("line", {
1912
+ "data-threshold": "",
1913
+ x1: x,
1914
+ x2: x,
1915
+ y1: area.y0,
1916
+ y2: area.y1,
1917
+ stroke: "currentColor",
1918
+ strokeWidth: 1.25,
1919
+ strokeDasharray: "3 2"
1920
+ });
1921
+ }
1922
+ /** How wide the grab area around the rule is, in viewBox units. */
1923
+ const GRAB = 12;
1924
+ /**
1925
+ * The threshold as a slider: the dashed rule plus a wider invisible grab area and a small
1926
+ * handle at the top. Pointer capture keeps a drag going outside the plot.
1927
+ */
1928
+ function DraggableThreshold({ value, xScale, area, step, onChange, label, unit, disabled = false }) {
1929
+ const dragging = useRef(false);
1930
+ if (value === void 0 || !Number.isFinite(value)) return null;
1931
+ const [low, high] = [Math.min(...xScale.domain), Math.max(...xScale.domain)];
1932
+ const off = disabled !== false;
1933
+ const reason = typeof disabled === "string" ? disabled : void 0;
1934
+ const x = xScale.project(value);
1935
+ const emit = (next) => onChange(Math.min(high, Math.max(low, next)));
1936
+ const xAt = (event) => {
1937
+ const svg = event.currentTarget.ownerSVGElement;
1938
+ const ctm = svg?.getScreenCTM();
1939
+ if (!svg || !ctm) return value;
1940
+ const point = svg.createSVGPoint();
1941
+ point.x = event.clientX;
1942
+ point.y = event.clientY;
1943
+ return xScale.invert(point.matrixTransform(ctm.inverse()).x);
1944
+ };
1945
+ const keyStep = (key) => {
1946
+ switch (key) {
1947
+ case "ArrowRight":
1948
+ case "ArrowUp": return value + step;
1949
+ case "ArrowLeft":
1950
+ case "ArrowDown": return value - step;
1951
+ case "PageUp": return value + 10 * step;
1952
+ case "PageDown": return value - 10 * step;
1953
+ case "Home": return low;
1954
+ case "End": return high;
1955
+ default: return null;
1956
+ }
1957
+ };
1958
+ return /* @__PURE__ */ jsxs("g", {
1959
+ "data-threshold-handle": "",
1960
+ "data-disabled": off ? "" : void 0,
1961
+ role: "slider",
1962
+ tabIndex: off ? -1 : 0,
1963
+ "aria-label": label,
1964
+ "aria-orientation": "horizontal",
1965
+ "aria-valuemin": low,
1966
+ "aria-valuemax": high,
1967
+ "aria-valuenow": value,
1968
+ "aria-valuetext": `${defaultFormat$1(value)}${unit ? ` ${unit}` : ""}`,
1969
+ "aria-disabled": off || void 0,
1970
+ className: "group text-fg outline-none",
1971
+ style: {
1972
+ cursor: off ? "not-allowed" : "col-resize",
1973
+ touchAction: "none"
1974
+ },
1975
+ onKeyDown: (event) => {
1976
+ if (off) return;
1977
+ const next = keyStep(event.key);
1978
+ if (next === null) return;
1979
+ event.preventDefault();
1980
+ emit(next);
1981
+ },
1982
+ onPointerDown: (event) => {
1983
+ if (off) return;
1984
+ dragging.current = true;
1985
+ event.currentTarget.setPointerCapture(event.pointerId);
1986
+ event.currentTarget.focus();
1987
+ emit(xAt(event));
1988
+ },
1989
+ onPointerMove: (event) => {
1990
+ if (dragging.current) emit(xAt(event));
1991
+ },
1992
+ onPointerUp: (event) => {
1993
+ dragging.current = false;
1994
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
1995
+ },
1996
+ onPointerCancel: () => {
1997
+ dragging.current = false;
1998
+ },
1999
+ children: [
2000
+ reason !== void 0 && /* @__PURE__ */ jsx("title", { children: reason }),
2001
+ /* @__PURE__ */ jsx("rect", {
2002
+ x: x - GRAB / 2,
2003
+ y: area.y1,
2004
+ width: GRAB,
2005
+ height: area.y0 - area.y1,
2006
+ fill: "transparent"
2007
+ }),
2008
+ /* @__PURE__ */ jsx("line", {
2009
+ "data-threshold": "",
2010
+ x1: x,
2011
+ x2: x,
2012
+ y1: area.y0,
2013
+ y2: area.y1,
2014
+ stroke: "currentColor",
2015
+ strokeWidth: 1.25,
2016
+ strokeDasharray: "3 2",
2017
+ opacity: off ? .6 : 1
2018
+ }),
2019
+ /* @__PURE__ */ jsx("path", {
2020
+ "data-handle": "",
2021
+ d: `M${x - 4} ${area.y1 - 1} h8 l-4 6 z`,
2022
+ fill: "currentColor",
2023
+ opacity: off ? .6 : 1
2024
+ }),
2025
+ /* @__PURE__ */ jsx("rect", {
2026
+ x: x - GRAB / 2,
2027
+ y: area.y1 - 2,
2028
+ width: GRAB,
2029
+ height: area.y0 - area.y1 + 2,
2030
+ rx: 2,
2031
+ fill: "none",
2032
+ stroke: "var(--signal)",
2033
+ strokeWidth: 2,
2034
+ className: "hidden group-focus-visible:block"
2035
+ })
2036
+ ]
2037
+ });
2038
+ }
2039
+ //#endregion
2040
+ //#region src/Histogram.tsx
2041
+ /**
2042
+ * One distribution as a bar chart over equal-width bins.
2043
+ *
2044
+ * @remarks
2045
+ * An SVG `role="img"` named by `label`. `threshold` draws a dashed decision rule, `markers`
2046
+ * tick the x axis, `bands` shade x ranges, `onHover` adds a crosshair and the x under it,
2047
+ * `onPick` reports the x of a click, `onThresholdChange` makes the threshold a draggable slider, and `cursor` draws the bin containing an x chosen
2048
+ * elsewhere in the selection colour (`--signal`) — no highlight when it lies outside the
2049
+ * domain. Empty data draws an empty frame. For two classes sharing a threshold use
849
2050
  * {@link ScoreHistogram}.
850
2051
  */
851
2052
  function Histogram(props) {
852
- const { label, xLabel, yLabel, unit, logY = false, variant = "panel", height = 200, footer, className, threshold, bands, markers, cursor, onHover, onPick } = props;
2053
+ const { label, xLabel, yLabel, unit, logY = false, variant = "panel", height = 200, footer, className, threshold, onThresholdChange, thresholdLabel = "Threshold", thresholdDisabled = false, bands, markers, cursor, onHover, onPick } = props;
853
2054
  const { counts, domain } = props.counts !== void 0 ? cleanCounts(props.counts, props.domain) : binValues(props.values, props.bins, props.domain);
854
2055
  const [fluidRef, fluidSize] = useFluidSize(height);
855
2056
  const size = variant === "fluid" ? fluidSize : void 0;
@@ -859,6 +2060,7 @@ function Histogram(props) {
859
2060
  const yScale = logY ? logScale([.5, top], plotArea.y0, plotArea.y1) : linearScale([0, top], plotArea.y0, plotArea.y1);
860
2061
  const highlighted = binAt(counts.length, domain, cursor);
861
2062
  const hasHighlight = highlighted !== null && (counts[highlighted] ?? 0) > 0;
2063
+ const draggable = onThresholdChange !== void 0 && threshold !== void 0 && Number.isFinite(threshold);
862
2064
  const xTitle = [xLabel, unit ? `(${unit})` : void 0].filter(Boolean).join(" ") || void 0;
863
2065
  return /* @__PURE__ */ jsxs(Frame, {
864
2066
  xScale,
@@ -871,6 +2073,7 @@ function Histogram(props) {
871
2073
  size,
872
2074
  figureRef: variant === "fluid" ? fluidRef : void 0,
873
2075
  footer,
2076
+ interactive: draggable,
874
2077
  children: [
875
2078
  bands && bands.length > 0 && /* @__PURE__ */ jsx(Bands, {
876
2079
  bands,
@@ -888,7 +2091,7 @@ function Histogram(props) {
888
2091
  d: barsPath(counts, yScale, plotArea, { only: highlighted }),
889
2092
  fill: "var(--signal)"
890
2093
  }),
891
- /* @__PURE__ */ jsx(ThresholdRule, {
2094
+ !draggable && /* @__PURE__ */ jsx(ThresholdRule, {
892
2095
  value: threshold,
893
2096
  xScale,
894
2097
  area: plotArea
@@ -905,6 +2108,16 @@ function Histogram(props) {
905
2108
  series: [],
906
2109
  onHover,
907
2110
  onPick
2111
+ }),
2112
+ draggable && /* @__PURE__ */ jsx(DraggableThreshold, {
2113
+ value: threshold,
2114
+ xScale,
2115
+ area: plotArea,
2116
+ step: (domain[1] - domain[0]) / Math.max(1, counts.length),
2117
+ onChange: onThresholdChange,
2118
+ label: thresholdLabel,
2119
+ unit,
2120
+ disabled: thresholdDisabled
908
2121
  })
909
2122
  ]
910
2123
  });
@@ -1112,193 +2325,6 @@ function LineProfile({ series, edges = [], label, xLabel = "arc length (px)", yL
1112
2325
  });
1113
2326
  }
1114
2327
  //#endregion
1115
- //#region src/colormap.ts
1116
- const ANCHORS = {
1117
- viridis: [
1118
- [
1119
- 68,
1120
- 1,
1121
- 84
1122
- ],
1123
- [
1124
- 71,
1125
- 44,
1126
- 122
1127
- ],
1128
- [
1129
- 59,
1130
- 81,
1131
- 139
1132
- ],
1133
- [
1134
- 44,
1135
- 113,
1136
- 142
1137
- ],
1138
- [
1139
- 33,
1140
- 144,
1141
- 141
1142
- ],
1143
- [
1144
- 39,
1145
- 173,
1146
- 129
1147
- ],
1148
- [
1149
- 92,
1150
- 200,
1151
- 99
1152
- ],
1153
- [
1154
- 170,
1155
- 220,
1156
- 50
1157
- ],
1158
- [
1159
- 253,
1160
- 231,
1161
- 37
1162
- ]
1163
- ],
1164
- cividis: [
1165
- [
1166
- 0,
1167
- 34,
1168
- 78
1169
- ],
1170
- [
1171
- 18,
1172
- 53,
1173
- 112
1174
- ],
1175
- [
1176
- 59,
1177
- 73,
1178
- 108
1179
- ],
1180
- [
1181
- 87,
1182
- 93,
1183
- 109
1184
- ],
1185
- [
1186
- 112,
1187
- 113,
1188
- 115
1189
- ],
1190
- [
1191
- 138,
1192
- 135,
1193
- 121
1194
- ],
1195
- [
1196
- 165,
1197
- 157,
1198
- 116
1199
- ],
1200
- [
1201
- 196,
1202
- 182,
1203
- 101
1204
- ],
1205
- [
1206
- 254,
1207
- 232,
1208
- 56
1209
- ]
1210
- ]
1211
- };
1212
- /** The names of the shipped maps. */
1213
- const COLORMAPS = ["viridis", "cividis"];
1214
- /**
1215
- * The colour of `t` on a map.
1216
- *
1217
- * @param name - The map.
1218
- * @param t - Position in `[0, 1]`; clamped. A non-finite `t` gives the map's low end.
1219
- * @returns A CSS `rgb(r g b)` colour.
1220
- */
1221
- function colormap(name, t) {
1222
- const [r, g, b] = colormapRgb(name, t);
1223
- return `rgb(${r} ${g} ${b})`;
1224
- }
1225
- /**
1226
- * The colour of `t` on a map, as integer channels.
1227
- *
1228
- * @param name - The map.
1229
- * @param t - Position in `[0, 1]`; clamped.
1230
- * @returns `[r, g, b]`, each 0–255.
1231
- */
1232
- function colormapRgb(name, t) {
1233
- const anchors = ANCHORS[name];
1234
- const scaled = (Number.isFinite(t) ? Math.min(1, Math.max(0, t)) : 0) * (anchors.length - 1);
1235
- const i = Math.min(anchors.length - 2, Math.floor(scaled));
1236
- const f = scaled - i;
1237
- const a = anchors[i];
1238
- const b = anchors[i + 1];
1239
- return [
1240
- Math.round(a[0] + f * (b[0] - a[0])),
1241
- Math.round(a[1] + f * (b[1] - a[1])),
1242
- Math.round(a[2] + f * (b[2] - a[2]))
1243
- ];
1244
- }
1245
- /**
1246
- * A value's colour on a map, over a domain.
1247
- *
1248
- * @param name - The map.
1249
- * @param value - The value.
1250
- * @param domain - `[low, high]`: low maps to the map's start. A reversed domain reverses the map.
1251
- * @returns A CSS colour.
1252
- */
1253
- function colormapValue(name, value, domain) {
1254
- const [low, high] = domain;
1255
- const span = high - low;
1256
- return colormap(name, span === 0 ? 0 : (value - low) / span);
1257
- }
1258
- /**
1259
- * A CSS `linear-gradient` of a map, for a legend bar.
1260
- *
1261
- * @param name - The map.
1262
- * @param direction - The gradient's direction. Defaults to `to right`.
1263
- * @returns A CSS `background-image` value.
1264
- */
1265
- function colormapGradient(name, direction = "to right") {
1266
- const anchors = ANCHORS[name];
1267
- return `linear-gradient(${direction}, ${anchors.map(([r, g, b], i) => `rgb(${r} ${g} ${b}) ${(i / (anchors.length - 1) * 100).toFixed(1)}%`).join(", ")})`;
1268
- }
1269
- //#endregion
1270
- //#region src/ColormapLegend.tsx
1271
- /**
1272
- * The scale of a colour map, shown beside the map: every chart or map shows its scale, with units.
1273
- */
1274
- /**
1275
- * A gradient bar with its end values and unit, read as one line: "Edge error 0 [bar] 2.5 px".
1276
- * The bar is decorative; the label and the end values carry the meaning as text.
1277
- */
1278
- function ColormapLegend({ map, domain, unit, label, format = (value) => String(Number(value.toPrecision(3))), className }) {
1279
- const end = (value) => unit ? `${format(value)} ${unit}` : format(value);
1280
- return /* @__PURE__ */ jsxs("div", {
1281
- className: cn("flex items-center gap-2 text-xs text-fg-muted", className),
1282
- "data-colormap": map,
1283
- children: [
1284
- /* @__PURE__ */ jsx("span", { children: label }),
1285
- /* @__PURE__ */ jsx("span", {
1286
- className: "font-mono tabular-nums",
1287
- children: end(domain[0])
1288
- }),
1289
- /* @__PURE__ */ jsx("span", {
1290
- "aria-hidden": true,
1291
- className: "h-2 w-24 rounded-full",
1292
- style: { backgroundImage: colormapGradient(map) }
1293
- }),
1294
- /* @__PURE__ */ jsx("span", {
1295
- className: "font-mono tabular-nums",
1296
- children: end(domain[1])
1297
- })
1298
- ]
1299
- });
1300
- }
1301
- //#endregion
1302
- export { Bands, COLORMAPS, ColormapLegend, DEFECT_COLOUR, FLUID_DEFAULT_HEIGHT, Frame, Histogram, Legend, LineChart, LineProfile, Markers, NORMAL_COLOUR, PlotInteraction, SERIES_COLOURS, ScoreHistogram, StackedBars, areaFor, colormap, colormapGradient, colormapRgb, colormapValue, extent, formatTick, histogram, linePath, linearScale, logScale, niceStep, padDomain, plotArea, seriesColour, seriesValueAt, useFluidSize };
2328
+ export { Bands, COLORMAPS, ColormapLegend, DEFECT_COLOUR, DIVERGING_COLORMAPS, FLUID_DEFAULT_HEIGHT, Frame, Histogram, Legend, LineChart, LineProfile, Markers, NORMAL_COLOUR, PlotInteraction, SCATTER_COLOUR_STEPS, SERIES_COLOURS, ScatterChart, ScoreHistogram, StackedBars, areaFor, bandPath, colormap, colormapGradient, colormapRgb, colormapValue, colourDomain, colourStep, extent, formatTick, formatWithBand, histogram, isDivergingColormap, linePath, linearScale, logScale, nearestProjected, niceStep, padDomain, plotArea, seriesColour, seriesValueAt, symmetricDomain, useFluidSize };
1303
2329
 
1304
2330
  //# sourceMappingURL=index.js.map