@vitavision/charts 0.6.0

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/src/scale.ts ADDED
@@ -0,0 +1,236 @@
1
+ /**
2
+ * The arithmetic behind every chart: domains, ticks, and the map from a value to a pixel.
3
+ *
4
+ * Hand-rolled SVG rather than a charting library: the chart types this design system needs
5
+ * are few and simple, and a library that lags the React and Tailwind versions the lab apps
6
+ * are deliberately on would mean either downgrading a consumer or isolating a laggard — a
7
+ * cost that outweighs a few hundred lines of scale maths.
8
+ *
9
+ * Everything here is pure. That is the point: it is the part worth unit-testing, and it
10
+ * leaves the components themselves as thin as an SVG element list.
11
+ */
12
+
13
+ /** A tick's position in domain units, with the label to draw beside it. */
14
+ export interface Tick {
15
+ /** Where the tick sits, in domain units — pass it to {@link Scale.project}. */
16
+ value: number;
17
+ /** The text to draw beside it, formatted by {@link formatTick}. */
18
+ label: string;
19
+ }
20
+
21
+ /**
22
+ * A map from a numeric domain onto a pixel range, with the ticks to label it.
23
+ *
24
+ * @remarks
25
+ * Built by {@link linearScale} or {@link logScale}. `project` is not clamped: a value
26
+ * outside the domain lands outside the range.
27
+ */
28
+ export interface Scale {
29
+ /** Domain, after padding and after any log transform's guard. */
30
+ domain: [number, number];
31
+ /** Map one domain value onto the pixel range this scale was built for. */
32
+ project: (value: number) => number;
33
+ /**
34
+ * Ticks inside the domain, in ascending order.
35
+ *
36
+ * @param count - Roughly how many ticks to aim for (default 5). The result may have a
37
+ * few more or fewer: steps are "nice" (see {@link niceStep}), or whole decades on a log
38
+ * scale.
39
+ */
40
+ ticks: (count?: number) => Tick[];
41
+ }
42
+
43
+ /** Smallest value a log scale will accept, so a zero loss cannot become `-Infinity`. */
44
+ const LOG_FLOOR = 1e-12;
45
+
46
+ const TICK_STEPS = [1, 2, 2.5, 5, 10];
47
+
48
+ /** Past this a label is noise; anything finer is shown as an exponent instead. */
49
+ const MAX_DECIMALS = 6;
50
+
51
+ /**
52
+ * A "nice" step at or above `rough` — one of 1, 2, 2.5 or 5 times a power of ten.
53
+ *
54
+ * Axis labels a reader can hold in their head are the whole reason: 0.25 / 0.50 / 0.75
55
+ * rather than 0.237 / 0.474 / 0.711.
56
+ */
57
+ export function niceStep(rough: number): number {
58
+ if (!Number.isFinite(rough) || rough <= 0) return 1;
59
+ const magnitude = 10 ** Math.floor(Math.log10(rough));
60
+ const normalized = rough / magnitude;
61
+ const step = TICK_STEPS.find((candidate) => candidate >= normalized - 1e-9) ?? 10;
62
+ return step * magnitude;
63
+ }
64
+
65
+ /**
66
+ * How many decimals a label needs so that neighbouring ticks do not print identically.
67
+ *
68
+ * Derived from the step rather than fixed, because one chart here might be a loss around
69
+ * 1e-4 and another a residual in whole pixels. Enough decimals to print the *step* exactly
70
+ * is the right rule, and `ceil(-log10(step))` is not it: a 0.25 step gets one decimal that
71
+ * way, and the axis reads 0.3 / 0.5 / 0.8 — three labels for four evenly spaced ticks.
72
+ */
73
+ function decimalsFor(step: number): number {
74
+ if (!Number.isFinite(step) || step <= 0) return 0;
75
+ for (let decimals = 0; decimals < MAX_DECIMALS; decimals += 1) {
76
+ if (Math.abs(Number(step.toFixed(decimals)) - step) < step * 1e-6) return decimals;
77
+ }
78
+ return MAX_DECIMALS;
79
+ }
80
+
81
+ /**
82
+ * The label for one tick: as many decimals as the step needs, or an exponent for a
83
+ * magnitude below 1e-3 or from 1e6 upwards.
84
+ *
85
+ * @param value - The tick's value.
86
+ * @param step - The spacing between neighbouring ticks; it decides the decimals.
87
+ * @returns The label, or `""` for a non-finite value.
88
+ */
89
+ export function formatTick(value: number, step: number): string {
90
+ if (!Number.isFinite(value)) return "";
91
+ const magnitude = Math.abs(value);
92
+ // Outside the range where a decimal reads better than an exponent. A loss of 3.2e-5 is
93
+ // legible; 0.000032 is a row of zeroes the eye has to count.
94
+ if (magnitude !== 0 && (magnitude < 1e-3 || magnitude >= 1e6)) {
95
+ return value.toExponential(1);
96
+ }
97
+ return value.toFixed(decimalsFor(step));
98
+ }
99
+
100
+ /**
101
+ * Widen a degenerate domain into one that can be drawn.
102
+ *
103
+ * A single-point series, or a constant one, has `min === max`. Left alone that divides by
104
+ * zero and the line vanishes; widened, the point sits in the middle of a sensible axis,
105
+ * which is what watching the first moments of a training run, or a profile with one sample
106
+ * so far, should look like.
107
+ */
108
+ export function padDomain(min: number, max: number): [number, number] {
109
+ if (!Number.isFinite(min) || !Number.isFinite(max)) return [0, 1];
110
+ if (min === max) {
111
+ const margin = Math.abs(min) > 0 ? Math.abs(min) * 0.1 : 1;
112
+ return [min - margin, max + margin];
113
+ }
114
+ return [min, max];
115
+ }
116
+
117
+ /**
118
+ * The `[min, max]` of the finite values, ignoring `NaN` and infinities.
119
+ *
120
+ * @returns `[0, 1]` when there is no finite value, so an empty series still has an axis.
121
+ */
122
+ export function extent(values: readonly number[]): [number, number] {
123
+ const finite = values.filter((value) => Number.isFinite(value));
124
+ if (finite.length === 0) return [0, 1];
125
+ return [Math.min(...finite), Math.max(...finite)];
126
+ }
127
+
128
+ /** A linear scale from `domain` onto `[rangeStart, rangeEnd]` pixels. */
129
+ export function linearScale(
130
+ domain: [number, number],
131
+ rangeStart: number,
132
+ rangeEnd: number,
133
+ ): Scale {
134
+ const [low, high] = padDomain(domain[0], domain[1]);
135
+ const span = high - low;
136
+ return {
137
+ domain: [low, high],
138
+ project: (value) => rangeStart + ((value - low) / span) * (rangeEnd - rangeStart),
139
+ ticks: (count = 5) => {
140
+ const step = niceStep(span / Math.max(1, count));
141
+ const first = Math.ceil(low / step) * step;
142
+ const ticks: Tick[] = [];
143
+ for (let value = first; value <= high + step * 1e-9; value += step) {
144
+ // Re-derived from the step index rather than accumulated, so floating-point drift
145
+ // cannot turn 0.30000000000000004 into a label.
146
+ const exact = Math.round(value / step) * step;
147
+ ticks.push({ value: exact, label: formatTick(exact, step) });
148
+ }
149
+ return ticks;
150
+ },
151
+ };
152
+ }
153
+
154
+ /**
155
+ * A base-10 log scale, for series that span decades.
156
+ *
157
+ * A loss curve is the canonical case: three terms that span decades and start far apart
158
+ * are a flat line along the bottom for two of the three on a linear axis. Non-positive
159
+ * values are clamped to `LOG_FLOOR` rather than dropped: a value that reaches exactly zero
160
+ * is a real observation, and a gap in the line would read as missing data.
161
+ */
162
+ export function logScale(domain: [number, number], rangeStart: number, rangeEnd: number): Scale {
163
+ const low = Math.log10(Math.max(domain[0], LOG_FLOOR));
164
+ const high = Math.log10(Math.max(domain[1], LOG_FLOOR));
165
+ const [paddedLow, paddedHigh] = padDomain(low, high);
166
+ const span = paddedHigh - paddedLow;
167
+
168
+ return {
169
+ domain: [10 ** paddedLow, 10 ** paddedHigh],
170
+ project: (value) => {
171
+ const transformed = Math.log10(Math.max(value, LOG_FLOOR));
172
+ return rangeStart + ((transformed - paddedLow) / span) * (rangeEnd - rangeStart);
173
+ },
174
+ ticks: (count = 5) => {
175
+ // One tick per decade, thinned when the range covers more decades than fit.
176
+ const stride = Math.max(1, Math.ceil(span / Math.max(1, count)));
177
+ const ticks: Tick[] = [];
178
+ for (
179
+ let exponent = Math.ceil(paddedLow);
180
+ exponent <= paddedHigh + 1e-9;
181
+ exponent += stride
182
+ ) {
183
+ const value = 10 ** exponent;
184
+ ticks.push({ value, label: formatTick(value, value) });
185
+ }
186
+ return ticks;
187
+ },
188
+ };
189
+ }
190
+
191
+ /** An SVG `d` attribute through the projected points, skipping non-finite ones. */
192
+ export function linePath(
193
+ points: readonly { x: number; y: number }[],
194
+ xScale: Scale,
195
+ yScale: Scale,
196
+ ): string {
197
+ const commands: string[] = [];
198
+ let pen = "M";
199
+ for (const point of points) {
200
+ if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {
201
+ // Lift the pen rather than bridging the gap: a straight line across missing data
202
+ // is an assertion nobody made.
203
+ pen = "M";
204
+ continue;
205
+ }
206
+ commands.push(`${pen}${xScale.project(point.x).toFixed(2)} ${yScale.project(point.y).toFixed(2)}`);
207
+ pen = "L";
208
+ }
209
+ return commands.join(" ");
210
+ }
211
+
212
+ /**
213
+ * Bin values into `count` equal-width buckets over their own extent.
214
+ *
215
+ * Used for the score histogram, where the two classes must share one set of edges or the
216
+ * bars cannot be compared. Callers pass the shared domain in for exactly that reason.
217
+ */
218
+ export function histogram(
219
+ values: readonly number[],
220
+ domain: [number, number],
221
+ count: number,
222
+ ): number[] {
223
+ const bins = new Array<number>(Math.max(1, count)).fill(0);
224
+ const [low, high] = domain;
225
+ const span = high - low;
226
+ if (span <= 0) {
227
+ bins[0] = values.length;
228
+ return bins;
229
+ }
230
+ for (const value of values) {
231
+ if (!Number.isFinite(value)) continue;
232
+ const index = Math.min(bins.length - 1, Math.floor(((value - low) / span) * bins.length));
233
+ if (index >= 0) bins[index] = (bins[index] ?? 0) + 1;
234
+ }
235
+ return bins;
236
+ }
package/src/styles.css ADDED
@@ -0,0 +1,44 @@
1
+ /*
2
+ * `@source` makes Tailwind v4 find this package's class names: it resolves against the
3
+ * stylesheet that declares it, and this file is exported from `src/` (which ships), so it scans
4
+ * the package's sources. Import it after `@vitavision/ui/styles.css`.
5
+ */
6
+ @source "./";
7
+
8
+ /*
9
+ * The categorical series palette (PLAN §5), read by `SERIES_COLOURS` / `seriesColour` as
10
+ * `var(--series-n)` — SVG `fill`/`stroke` resolve custom properties, so both themes are the
11
+ * same one class swap on <html> as the rest of the design system.
12
+ *
13
+ * Each slot keeps its hue family in both themes — cyan, orange, violet, blue, pink, then a
14
+ * neutral — and only the lightness moves, so a curve is the same curve in a light and a dark
15
+ * screenshot. The values were chosen, not picked by eye, against three checks:
16
+ *
17
+ * - Non-text contrast (WCAG 1.4.11): every colour is at least 3:1 against `--surface` and
18
+ * `--ground` in its theme, so a 1.5 px line is visible on a panel and on the page.
19
+ * - Colour-vision deficiency: simulated protanopia, deuteranopia and tritanopia (Machado et
20
+ * al. 2009, full severity), every pair stays at least 9.4 apart in OKLab (ΔE × 100) —
21
+ * wider than Okabe–Ito's closest pair under the same test. Lightness is staggered between
22
+ * neighbouring hues for exactly that reason.
23
+ * - Verdicts are reserved: no slot is, or sits near, `--normal`, `--defect` or `--warn`. The
24
+ * earlier palette used the dark theme's normal and defect hexes as series 4 and 5.
25
+ *
26
+ * Any sixth-plus series is still told apart by its legend text, never by colour alone.
27
+ */
28
+ :root {
29
+ --series-1: #0f92c5; /* cyan */
30
+ --series-2: #b57c38; /* orange */
31
+ --series-3: #7e5be6; /* violet */
32
+ --series-4: #482ab3; /* indigo */
33
+ --series-5: #e04b9b; /* pink */
34
+ --series-6: #595f65; /* neutral */
35
+ }
36
+
37
+ .dark {
38
+ --series-1: #27e4ef;
39
+ --series-2: #c27421;
40
+ --series-3: #8ba3ff;
41
+ --series-4: #4a6ee0;
42
+ --series-5: #f96dcc;
43
+ --series-6: #7f878d;
44
+ }