@vitavision/charts 0.7.1 → 0.8.1

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @vitavision/charts
2
2
 
3
- Small, hand-rolled SVG charts for the vitavision lab apps, on `@vitavision/ui` tokens.
3
+ Small, hand-rolled SVG charts for the vitavision apps, on `@vitavision/ui` tokens.
4
4
 
5
5
  ```bash
6
6
  bun add @vitavision/charts @vitavision/ui
@@ -20,22 +20,22 @@ is accepted.
20
20
 
21
21
  **Charts** — hand-rolled SVG over the pure domain/tick/project math in `scale.ts`:
22
22
  `Frame` + `Legend` (the axes/grid/label shell every chart composes), `LineChart`
23
- (multi-series, optional log y), `StackedBars`, `ScoreHistogram` (two-class distribution
24
- with a threshold rule), and `LineProfile` (one or more series against arc length in pixels
23
+ (multi-series, optional log y), `StackedBars`, `Histogram` (one distribution from raw
24
+ `values` or pre-binned `counts`, with markers, a cursor bin and hover/pick), `ScoreHistogram` (two-class
25
+ distribution with a threshold rule), and `LineProfile` (one or more series against arc length in pixels
25
26
  along a scan line or caliper axis, with detected edges drawn as labelled vertical rules).
26
27
 
27
28
  **Fitting a chart to its container**: `variant="fluid"` takes the container's width at a fixed
28
29
  `height`, for a chart in a resizable inspector.
29
30
 
30
- **Interaction** on `LineChart` and `LineProfile`:
31
+ **Interaction** on `LineChart`, `LineProfile` and `Histogram`:
31
32
  - `onHover` draws a crosshair with a value readout, and `onPick` reports a click's x.
32
33
  - `cursor` draws an x chosen elsewhere, such as the pointer on the canvas a profile came from.
33
34
  - `bands` shade x ranges, and `markers` tick positions on the x axis.
34
35
 
35
36
  **Sequential colour maps**: `colormap("viridis" | "cividis", t)` and
36
37
  `colormapValue(map, value, domain)`, for a magnitude such as an error, a validity or a
37
- confidence. `ColormapLegend` shows the scale with its units; a map is never shown without one
38
- (visual-language §4).
38
+ confidence. `ColormapLegend` shows the scale with its units; a map is never shown without one.
39
39
 
40
40
  ## License
41
41
 
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ import { MeasureTone } from "@vitavision/ui";
5
5
  * The arithmetic behind every chart: domains, ticks, and the map from a value to a pixel.
6
6
  *
7
7
  * Hand-rolled SVG rather than a charting library: the chart types this design system needs
8
- * are few and simple, and a library that lags the React and Tailwind versions the lab apps
8
+ * are few and simple, and a library that lags the React and Tailwind versions the apps
9
9
  * are deliberately on would mean either downgrading a consumer or isolating a laggard — a
10
10
  * cost that outweighs a few hundred lines of scale maths.
11
11
  *
@@ -227,7 +227,7 @@ export declare function Legend({ items, className }: LegendProps): import("react
227
227
  * a neutral grey as the sixth — and only its lightness changes, so every colour holds 3:1
228
228
  * against the panel in both. The six stay distinguishable under simulated protanopia,
229
229
  * deuteranopia and tritanopia, and none of them is a verdict colour (`--normal`,
230
- * `--defect`, `--warn`): a series is never read as a verdict (PLAN §5).
230
+ * `--defect`, `--warn`): a series is never read as a verdict.
231
231
  *
232
232
  * Before 0.6 these were fixed hex strings; the names are unchanged.
233
233
  */
@@ -451,6 +451,71 @@ interface StackedBarsProps {
451
451
  export declare function StackedBars({ rows, label, className }: StackedBarsProps): import("react").JSX.Element;
452
452
  //#endregion
453
453
  //#region src/Histogram.d.ts
454
+ /** Props every {@link Histogram} takes, whichever way its data is given. */
455
+ interface HistogramOptions extends InteractionProps {
456
+ /** Accessible name of the chart (the SVG's `aria-label`). Required. */
457
+ label: string;
458
+ /** x-axis title. */
459
+ xLabel?: string | undefined;
460
+ /** y-axis title. */
461
+ yLabel?: string | undefined;
462
+ /** Unit of x, appended to the x-axis title in parentheses: `luminance (DN)`. */
463
+ unit?: string | undefined;
464
+ /**
465
+ * A decision threshold on x, drawn as a dashed rule across the plot (as `ScoreHistogram`
466
+ * draws its own). Omitted or non-finite: none. For other x positions use `markers`.
467
+ */
468
+ threshold?: number | undefined;
469
+ /** Counts span decades in a long-tailed distribution; a log axis keeps the tail visible. */
470
+ logY?: boolean | undefined;
471
+ /** Where the chart is going (see {@link Variant}). Default `"panel"`. */
472
+ variant?: Variant | undefined;
473
+ /** For `variant="fluid"`: the chart's height in CSS pixels. Default 200. */
474
+ height?: number | undefined;
475
+ /** Rendered under the plot, inside the `<figcaption>`. */
476
+ footer?: ReactNode;
477
+ /** Extra classes for the outer `<figure>`, merged with `cn`. */
478
+ className?: string | undefined;
479
+ }
480
+ /** A histogram given as raw samples, binned by the chart. */
481
+ interface HistogramValues {
482
+ /** The samples. Non-finite values, and values outside `domain`, are ignored. */
483
+ values: ArrayLike<number>;
484
+ /** Number of equal-width bins. Default 32. */
485
+ bins?: number | undefined;
486
+ /** The x range the bins span. Omitted: the extent of `values`. */
487
+ domain?: [number, number] | undefined;
488
+ /** Not accepted with `values` — pass one or the other. */
489
+ counts?: undefined;
490
+ }
491
+ /** A histogram given as counts per bin, already binned by the caller. */
492
+ interface HistogramCounts {
493
+ /** One count per bin, left to right; the bins are equal-width and fill `domain`. */
494
+ counts: ArrayLike<number>;
495
+ /** The x range the bins span. Required: without samples there is no extent to fall back on. */
496
+ domain: [number, number];
497
+ /** Not accepted with `counts` — pass one or the other. */
498
+ values?: undefined;
499
+ }
500
+ /**
501
+ * Props for {@link Histogram}: {@link HistogramOptions} plus data as either
502
+ * {@link HistogramValues} or {@link HistogramCounts}, never both.
503
+ */
504
+ type HistogramProps = HistogramOptions & (HistogramValues | HistogramCounts);
505
+ /**
506
+ * One distribution as a bar chart over equal-width bins.
507
+ *
508
+ * @remarks
509
+ * An SVG `role="img"` named by `label`. `threshold` draws a dashed decision rule, `markers`
510
+ * tick the x axis, `bands` shade x ranges, `onHover` adds a crosshair and the x under it,
511
+ * `onPick` reports the x of a click, and `cursor` draws the bin containing an x chosen
512
+ * elsewhere in the selection colour (`--signal`) — no highlight when it lies outside the
513
+ * domain. Empty data draws an empty frame. For two classes sharing a threshold use
514
+ * {@link ScoreHistogram}.
515
+ */
516
+ export declare function Histogram(props: HistogramProps): import("react").JSX.Element;
517
+ //#endregion
518
+ //#region src/ScoreHistogram.d.ts
454
519
  /**
455
520
  * Score distribution by class, with a threshold drawn on it.
456
521
  *
@@ -463,7 +528,7 @@ export declare function StackedBars({ rows, label, className }: StackedBarsProps
463
528
  * looking at — would be an artefact of the binning.
464
529
  */
465
530
  /** Props for {@link ScoreHistogram}. */
466
- interface HistogramProps {
531
+ interface ScoreHistogramProps {
467
532
  /** Anomaly scores of the samples labelled normal. */
468
533
  normal: number[];
469
534
  /** Anomaly scores of the samples labelled defective. */
@@ -485,7 +550,7 @@ interface HistogramProps {
485
550
  * Always the `wide` variant. Painted in the verdict tokens (`--normal`, `--defect`); the
486
551
  * legend names both classes with their counts, so the chart does not rely on colour alone.
487
552
  */
488
- export declare function ScoreHistogram({ normal, defect, threshold, bins, label, className }: HistogramProps): import("react").JSX.Element;
553
+ export declare function ScoreHistogram({ normal, defect, threshold, bins, label, className }: ScoreHistogramProps): import("react").JSX.Element;
489
554
  //#endregion
490
555
  //#region src/LineProfile.d.ts
491
556
  /** One sampled profile of a {@link LineProfile}. */
@@ -550,7 +615,7 @@ export declare function LineProfile({ series, edges, label, xLabel, yLabel, xDom
550
615
  //#endregion
551
616
  //#region src/colormap.d.ts
552
617
  /**
553
- * Sequential colour maps for a magnitude (visual-language §4): a residual's size, a per-cell
618
+ * Sequential colour maps for a magnitude: a residual's size, a per-cell
554
619
  * error, a confidence, a validity fraction.
555
620
  *
556
621
  * Only perceptually uniform maps ship, so equal steps in the data look like equal steps.
@@ -624,5 +689,5 @@ interface ColormapLegendProps {
624
689
  */
625
690
  export declare function ColormapLegend({ map, domain, unit, label, format, className }: ColormapLegendProps): import("react").JSX.Element;
626
691
  //#endregion
627
- export type { Band, BarRow, ColormapLegendProps, ColormapName, EdgeMark, FrameProps, HistogramProps, InteractionProps, LegendItem, LegendProps, LineChartProps, LineProfileProps, Marker, PlotArea, ProfileSeries, ReadoutSeries, Scale, Series, StackedBarsProps, Tick, Variant };
692
+ export type { Band, BarRow, ColormapLegendProps, ColormapName, EdgeMark, FrameProps, HistogramCounts, HistogramOptions, HistogramProps, HistogramValues, InteractionProps, LegendItem, LegendProps, LineChartProps, LineProfileProps, Marker, PlotArea, ProfileSeries, ReadoutSeries, Scale, ScoreHistogramProps, Series, StackedBarsProps, Tick, Variant };
628
693
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -226,7 +226,7 @@ function Legend({ items, className }) {
226
226
  * a neutral grey as the sixth — and only its lightness changes, so every colour holds 3:1
227
227
  * against the panel in both. The six stay distinguishable under simulated protanopia,
228
228
  * deuteranopia and tritanopia, and none of them is a verdict colour (`--normal`,
229
- * `--defect`, `--warn`): a series is never read as a verdict (PLAN §5).
229
+ * `--defect`, `--warn`): a series is never read as a verdict.
230
230
  *
231
231
  * Before 0.6 these were fixed hex strings; the names are unchanged.
232
232
  */
@@ -731,9 +731,187 @@ function StackedBars({ rows, label, className }) {
731
731
  })
732
732
  });
733
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
+ }
734
838
  //#endregion
735
839
  //#region src/Histogram.tsx
736
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
849
+ * {@link ScoreHistogram}.
850
+ */
851
+ function Histogram(props) {
852
+ const { label, xLabel, yLabel, unit, logY = false, variant = "panel", height = 200, footer, className, threshold, bands, markers, cursor, onHover, onPick } = props;
853
+ const { counts, domain } = props.counts !== void 0 ? cleanCounts(props.counts, props.domain) : binValues(props.values, props.bins, props.domain);
854
+ const [fluidRef, fluidSize] = useFluidSize(height);
855
+ const size = variant === "fluid" ? fluidSize : void 0;
856
+ const plotArea = areaFor(variant, size);
857
+ const xScale = linearScale(domain, plotArea.x0, plotArea.x1);
858
+ const top = tallest(counts);
859
+ const yScale = logY ? logScale([.5, top], plotArea.y0, plotArea.y1) : linearScale([0, top], plotArea.y0, plotArea.y1);
860
+ const highlighted = binAt(counts.length, domain, cursor);
861
+ const hasHighlight = highlighted !== null && (counts[highlighted] ?? 0) > 0;
862
+ const xTitle = [xLabel, unit ? `(${unit})` : void 0].filter(Boolean).join(" ") || void 0;
863
+ return /* @__PURE__ */ jsxs(Frame, {
864
+ xScale,
865
+ yScale,
866
+ xLabel: xTitle,
867
+ yLabel,
868
+ label,
869
+ variant,
870
+ className,
871
+ size,
872
+ figureRef: variant === "fluid" ? fluidRef : void 0,
873
+ footer,
874
+ children: [
875
+ bands && bands.length > 0 && /* @__PURE__ */ jsx(Bands, {
876
+ bands,
877
+ xScale,
878
+ area: plotArea
879
+ }),
880
+ /* @__PURE__ */ jsx("path", {
881
+ "data-bars": "",
882
+ d: barsPath(counts, yScale, plotArea, { skip: hasHighlight ? highlighted : null }),
883
+ fill: seriesColour(0),
884
+ opacity: .8
885
+ }),
886
+ hasHighlight && /* @__PURE__ */ jsx("path", {
887
+ "data-cursor-bin": highlighted,
888
+ d: barsPath(counts, yScale, plotArea, { only: highlighted }),
889
+ fill: "var(--signal)"
890
+ }),
891
+ /* @__PURE__ */ jsx(ThresholdRule, {
892
+ value: threshold,
893
+ xScale,
894
+ area: plotArea
895
+ }),
896
+ markers && markers.length > 0 && /* @__PURE__ */ jsx(Markers, {
897
+ markers,
898
+ xScale,
899
+ area: plotArea
900
+ }),
901
+ (onHover || onPick) && /* @__PURE__ */ jsx(PlotInteraction, {
902
+ xScale,
903
+ yScale,
904
+ area: plotArea,
905
+ series: [],
906
+ onHover,
907
+ onPick
908
+ })
909
+ ]
910
+ });
911
+ }
912
+ //#endregion
913
+ //#region src/ScoreHistogram.tsx
914
+ /**
737
915
  * Score distribution by class, with a threshold drawn on it.
738
916
  *
739
917
  * This is the chart that makes a threshold decision legible: a confusion matrix says how
@@ -759,21 +937,9 @@ function ScoreHistogram({ normal, defect, threshold, bins = 32, label, className
759
937
  const domain = extent([...normal, ...defect]);
760
938
  const normalBins = histogram(normal, domain, bins);
761
939
  const defectBins = histogram(defect, domain, bins);
762
- const tallest = Math.max(1, ...normalBins, ...defectBins);
940
+ const top = tallest(normalBins, defectBins);
763
941
  const xScale = linearScale(domain, plotArea$1.x0, plotArea$1.x1);
764
- const yScale = linearScale([0, tallest], plotArea$1.y0, plotArea$1.y1);
765
- const binWidth = (plotArea$1.x1 - plotArea$1.x0) / bins;
766
- const bars = (counts, fill, opacity) => counts.map((count, index) => ({
767
- count,
768
- x: plotArea$1.x0 + index * binWidth
769
- })).map(({ count, x }) => count === 0 ? null : /* @__PURE__ */ jsx("rect", {
770
- x,
771
- y: yScale.project(count),
772
- width: Math.max(.5, binWidth - .5),
773
- height: plotArea$1.y0 - yScale.project(count),
774
- fill,
775
- opacity
776
- }, `${fill}-${x}`));
942
+ const yScale = linearScale([0, top], plotArea$1.y0, plotArea$1.y1);
777
943
  return /* @__PURE__ */ jsxs(Frame, {
778
944
  xScale,
779
945
  yScale,
@@ -828,16 +994,22 @@ function ScoreHistogram({ normal, defect, threshold, bins = 32, label, className
828
994
  ]
829
995
  }),
830
996
  children: [
831
- bars(normalBins, NORMAL_FILL, .65),
832
- bars(defectBins, DEFECT_FILL, .65),
833
- threshold !== void 0 && Number.isFinite(threshold) && /* @__PURE__ */ jsx("line", {
834
- x1: xScale.project(threshold),
835
- x2: xScale.project(threshold),
836
- y1: plotArea$1.y0,
837
- y2: plotArea$1.y1,
838
- stroke: "currentColor",
839
- strokeWidth: 1.25,
840
- strokeDasharray: "3 2"
997
+ /* @__PURE__ */ jsx("path", {
998
+ "data-bars": "",
999
+ d: barsPath(normalBins, yScale, plotArea$1),
1000
+ fill: NORMAL_FILL,
1001
+ opacity: .65
1002
+ }),
1003
+ /* @__PURE__ */ jsx("path", {
1004
+ "data-bars": "",
1005
+ d: barsPath(defectBins, yScale, plotArea$1),
1006
+ fill: DEFECT_FILL,
1007
+ opacity: .65
1008
+ }),
1009
+ /* @__PURE__ */ jsx(ThresholdRule, {
1010
+ value: threshold,
1011
+ xScale,
1012
+ area: plotArea$1
841
1013
  })
842
1014
  ]
843
1015
  });
@@ -1097,8 +1269,7 @@ function colormapGradient(name, direction = "to right") {
1097
1269
  //#endregion
1098
1270
  //#region src/ColormapLegend.tsx
1099
1271
  /**
1100
- * The scale of a colour map, shown beside the map: visual-language §4 requires every chart or
1101
- * map to show its scale, with units.
1272
+ * The scale of a colour map, shown beside the map: every chart or map shows its scale, with units.
1102
1273
  */
1103
1274
  /**
1104
1275
  * A gradient bar with its end values and unit, read as one line: "Edge error 0 [bar] 2.5 px".
@@ -1128,6 +1299,6 @@ function ColormapLegend({ map, domain, unit, label, format = (value) => String(N
1128
1299
  });
1129
1300
  }
1130
1301
  //#endregion
1131
- export { Bands, COLORMAPS, ColormapLegend, DEFECT_COLOUR, FLUID_DEFAULT_HEIGHT, Frame, 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 };
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 };
1132
1303
 
1133
1304
  //# sourceMappingURL=index.js.map