@c9up/nebula 0.2.3 → 0.2.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.
Files changed (99) hide show
  1. package/README.md +9 -8
  2. package/dist/atoms/AspectRatio.d.ts +10 -4
  3. package/dist/atoms/AspectRatio.js +21 -6
  4. package/dist/atoms/Avatar.d.ts +14 -0
  5. package/dist/atoms/Avatar.js +46 -8
  6. package/dist/atoms/NativeSelect.d.ts +10 -0
  7. package/dist/atoms/NativeSelect.js +4 -1
  8. package/dist/atoms/Progress.d.ts +9 -1
  9. package/dist/atoms/Progress.js +21 -5
  10. package/dist/atoms/Switch.d.ts +7 -1
  11. package/dist/atoms/Switch.js +7 -1
  12. package/dist/cli/add.d.ts +2 -0
  13. package/dist/cli/add.js +4 -1
  14. package/dist/cli/diff.d.ts +48 -0
  15. package/dist/cli/diff.js +77 -3
  16. package/dist/cli/projectConfig.d.ts +16 -0
  17. package/dist/cli/projectConfig.js +61 -0
  18. package/dist/console/AddCommand.js +6 -1
  19. package/dist/console/DiffCommand.js +12 -12
  20. package/dist/lib/icons.d.ts +8 -0
  21. package/dist/lib/icons.js +8 -0
  22. package/dist/lib/image.js +12 -1
  23. package/dist/molecules/Accordion.js +1 -2
  24. package/dist/molecules/Collapsible.js +1 -2
  25. package/dist/molecules/InputOTP.d.ts +12 -0
  26. package/dist/molecules/InputOTP.js +68 -27
  27. package/dist/molecules/Resizable.d.ts +6 -0
  28. package/dist/molecules/Resizable.js +8 -2
  29. package/dist/molecules/index.d.ts +1 -1
  30. package/dist/molecules/index.js +1 -1
  31. package/dist/organisms/AlertDialog.js +4 -5
  32. package/dist/organisms/Chart.d.ts +103 -15
  33. package/dist/organisms/Chart.js +518 -99
  34. package/dist/organisms/Combobox.d.ts +13 -0
  35. package/dist/organisms/Combobox.js +5 -2
  36. package/dist/organisms/Command.js +56 -8
  37. package/dist/organisms/Dialog.js +7 -7
  38. package/dist/organisms/Form.d.ts +15 -0
  39. package/dist/organisms/Form.js +10 -0
  40. package/dist/organisms/Select.d.ts +6 -4
  41. package/dist/organisms/Select.js +1 -0
  42. package/dist/organisms/Sidebar.d.ts +9 -9
  43. package/dist/organisms/Sidebar.js +77 -32
  44. package/dist/organisms/Sonner.d.ts +243 -0
  45. package/dist/organisms/Sonner.js +916 -0
  46. package/dist/organisms/Toaster.d.ts +9 -0
  47. package/dist/organisms/Toaster.js +28 -5
  48. package/dist/organisms/Tooltip.d.ts +4 -0
  49. package/dist/organisms/index.d.ts +7 -1
  50. package/dist/organisms/index.js +7 -1
  51. package/dist/primitives/dismissable.d.ts +11 -4
  52. package/dist/primitives/dismissable.js +8 -6
  53. package/dist/primitives/floating.d.ts +5 -1
  54. package/dist/primitives/floating.js +8 -1
  55. package/dist/primitives/menu.js +2 -1
  56. package/dist/primitives/menuParts.js +3 -3
  57. package/dist/primitives/modalSurface.js +70 -36
  58. package/dist/primitives/portal.d.ts +15 -0
  59. package/dist/primitives/portal.js +18 -1
  60. package/dist/primitives/presence.js +8 -5
  61. package/nebula.css +2 -2
  62. package/package.json +1 -1
  63. package/registry.json +13 -0
  64. package/src/atoms/AspectRatio.ts +21 -6
  65. package/src/atoms/Avatar.ts +54 -7
  66. package/src/atoms/NativeSelect.ts +14 -1
  67. package/src/atoms/Progress.ts +21 -5
  68. package/src/atoms/Switch.ts +7 -1
  69. package/src/cli/add.ts +7 -1
  70. package/src/cli/diff.ts +130 -3
  71. package/src/cli/projectConfig.ts +71 -0
  72. package/src/console/AddCommand.ts +6 -1
  73. package/src/console/DiffCommand.ts +18 -16
  74. package/src/lib/icons.ts +28 -0
  75. package/src/lib/image.ts +13 -1
  76. package/src/molecules/Accordion.ts +1 -2
  77. package/src/molecules/Collapsible.ts +1 -3
  78. package/src/molecules/InputOTP.ts +81 -27
  79. package/src/molecules/Resizable.ts +8 -2
  80. package/src/molecules/index.ts +3 -0
  81. package/src/organisms/AlertDialog.ts +3 -5
  82. package/src/organisms/Chart.ts +633 -125
  83. package/src/organisms/Combobox.ts +18 -2
  84. package/src/organisms/Command.ts +66 -7
  85. package/src/organisms/Dialog.ts +6 -7
  86. package/src/organisms/Form.ts +21 -0
  87. package/src/organisms/Select.ts +7 -4
  88. package/src/organisms/Sidebar.ts +75 -25
  89. package/src/organisms/Sonner.ts +1373 -0
  90. package/src/organisms/Toaster.ts +30 -6
  91. package/src/organisms/Tooltip.ts +4 -0
  92. package/src/organisms/index.ts +29 -0
  93. package/src/primitives/dismissable.ts +16 -8
  94. package/src/primitives/floating.ts +13 -2
  95. package/src/primitives/menu.ts +2 -1
  96. package/src/primitives/menuParts.ts +3 -3
  97. package/src/primitives/modalSurface.ts +77 -40
  98. package/src/primitives/portal.ts +27 -1
  99. package/src/primitives/presence.ts +12 -9
@@ -8,166 +8,585 @@
8
8
  * the shadcn chart examples are and what dashboards overwhelmingly need.
9
9
  *
10
10
  * Anything beyond that — stacked bars with negative values, dual axes, brushes,
11
- * candlesticks — is a charting library's job, and an app needing one should
12
- * install one rather than have this component grow into a bad copy.
11
+ * candlesticks, horizontal bars, heatmaps, funnels — is a charting library's
12
+ * job, and an app needing one should install one rather than have this
13
+ * component grow into a bad copy.
13
14
  *
14
15
  * The colours come from `--chart-1` … `--chart-5`, so a chart re-themes with
15
16
  * the rest of the design system instead of carrying its own palette.
16
17
  *
17
- * An SVG chart is invisible to a screen reader whatever ARIA is put on it, so
18
- * the same data is emitted as a real `<table>`, visually hidden. That is the
19
- * only approach that actually works: the reader gets rows and values it can
20
- * navigate, not a described picture.
18
+ * **Geometry.** Text is never stretched. The drawing is two SVGs in pixel
19
+ * space — the value axis in a fixed gutter, the plot at full width — with
20
+ * every horizontal position written as a percentage of the plot's width and
21
+ * every vertical one in pixels. Only the curves and bars live in a nested SVG
22
+ * stretched to the plot (`preserveAspectRatio="none"`), with strokes that do
23
+ * not scale. Everything is an attribute: no `style` attribute, which a strict
24
+ * Content-Security-Policy blocks, and the server's markup is the chart.
25
+ *
26
+ * **Missing values.** A value that is absent, `null` or not a finite number is
27
+ * a gap: the line breaks, the area stops, no bar is drawn, and the table says
28
+ * so. Drawing it as `0` would invent a number.
29
+ *
30
+ * **Reading it.** An SVG chart is invisible to a screen reader whatever ARIA is
31
+ * put on it, so the same data is emitted as a real `<table>`, visually hidden.
32
+ * The plot also takes focus: the arrow keys walk the categories, and what the
33
+ * pointer or the keyboard points at is shown in a tooltip and announced in a
34
+ * live region.
21
35
  */
22
- import { component, html } from "@c9up/aurora";
36
+ import { component, html, onMount, onUnmount, signal, } from "@c9up/aurora";
23
37
  import { cn } from "../lib/cn.js";
24
38
  import { uid } from "../lib/id.js";
25
39
  import { read } from "../lib/props.js";
26
- const VIEWBOX_WIDTH = 600;
27
- const PADDING = { top: 8, right: 8, bottom: 24, left: 40 };
40
+ /** Where the plot's drawing starts and stops, in pixels from its top. */
41
+ const PADDING = { top: 8, bottom: 24 };
42
+ /** Font size of every axis label, in pixels. */
43
+ const FONT_SIZE = 11;
44
+ /**
45
+ * Average advance of one character at {@link FONT_SIZE}. An estimate — the
46
+ * server cannot measure text — erring wide, so labels never touch.
47
+ */
48
+ const CHARACTER_WIDTH = FONT_SIZE * 0.62;
49
+ /** Space kept between two category labels, in pixels. */
50
+ const LABEL_GAP = 8;
51
+ /**
52
+ * The plot's width before it is measured: on the server, and until the first
53
+ * resize report. Labels are thinned for this width, then for the real one.
54
+ */
55
+ const NOMINAL_PLOT_WIDTH = 600;
28
56
  function colorFor(series, index) {
29
57
  return series.color ?? `var(--chart-${(index % 5) + 1})`;
30
58
  }
59
+ /** The value of `key`, or `null` for a gap. */
31
60
  function numberAt(datum, key) {
32
61
  const value = datum[key];
33
- return typeof value === "number" ? value : 0;
62
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
34
63
  }
35
64
  function categoryAt(datum, key) {
36
65
  const value = datum[key];
37
- return typeof value === "string" ? value : String(value ?? "");
66
+ if (typeof value === "string" ||
67
+ typeof value === "number" ||
68
+ value instanceof Date) {
69
+ return value;
70
+ }
71
+ return "";
38
72
  }
39
73
  /**
40
- * The value range the Y axis covers.
74
+ * The range the data covers.
41
75
  *
42
- * Anchored at zero whenever the data is non-negative. A bar chart whose axis
43
- * starts at the minimum value exaggerates every difference — the classic
44
- * misleading chart — and it is not a choice worth exposing as an option.
76
+ * Gaps are skipped. With `zero` (the default), the range always includes zero.
77
+ * A flat range is widened — to `0`–`1` when it sits on zero, by a tenth of its
78
+ * value either side otherwise — so there is always something to scale
79
+ * against, and no data at all reads as `0`–`1`.
45
80
  */
46
- export function valueRange(data, series) {
47
- let min = 0;
48
- let max = 0;
81
+ export function valueRange(data, series, options = {}) {
82
+ const zero = options.zero !== false;
83
+ let min = Number.POSITIVE_INFINITY;
84
+ let max = Number.NEGATIVE_INFINITY;
49
85
  for (const datum of data) {
50
86
  for (const entry of series) {
51
87
  const value = numberAt(datum, entry.key);
88
+ if (value === null)
89
+ continue;
52
90
  if (value < min)
53
91
  min = value;
54
92
  if (value > max)
55
93
  max = value;
56
94
  }
57
95
  }
58
- // A flat all-zero dataset would divide by zero when scaling.
59
- if (min === max)
60
- return { min, max: max + 1 };
96
+ if (min > max)
97
+ return { min: 0, max: 1 };
98
+ if (zero) {
99
+ min = Math.min(min, 0);
100
+ max = Math.max(max, 0);
101
+ }
102
+ // Flat. With `zero` that can only be all zeros; without, a flat series
103
+ // away from zero is centred in a band a fifth of its value wide.
104
+ if (min === max) {
105
+ if (min === 0)
106
+ return { min: 0, max: 1 };
107
+ const pad = Math.abs(min) * 0.1;
108
+ return { min: min - pad, max: max + pad };
109
+ }
61
110
  return { min, max };
62
111
  }
112
+ /**
113
+ * A "round" step near `raw`: 1, 2, 2.5 or 5 times a power of ten — the steps
114
+ * a reader can add up in their head.
115
+ */
116
+ function niceStep(raw) {
117
+ const exponent = Math.floor(Math.log10(raw));
118
+ const magnitude = 10 ** exponent;
119
+ const fraction = raw / magnitude;
120
+ const nice = fraction <= 1
121
+ ? 1
122
+ : fraction <= 2
123
+ ? 2
124
+ : fraction <= 2.5
125
+ ? 2.5
126
+ : fraction <= 5
127
+ ? 5
128
+ : 10;
129
+ return Number((nice * magnitude).toPrecision(12));
130
+ }
131
+ /** Drop floating-point dust: `0.30000000000000004` → `0.3`. */
132
+ function clean(value) {
133
+ return Number(value.toPrecision(12));
134
+ }
135
+ /**
136
+ * Round ticks covering `min`–`max`, about `count` of them.
137
+ *
138
+ * The range is widened outwards to the nearest tick, so the first and last
139
+ * ticks are the axis' ends.
140
+ */
141
+ export function niceTicks(min, max, count = 5) {
142
+ let low = Math.min(min, max);
143
+ let high = Math.max(min, max);
144
+ if (!Number.isFinite(low) || !Number.isFinite(high)) {
145
+ low = 0;
146
+ high = 1;
147
+ }
148
+ if (low === high) {
149
+ const pad = low === 0 ? 1 : Math.abs(low) * 0.1;
150
+ low -= pad;
151
+ high += pad;
152
+ }
153
+ const intervals = Math.max(1, Math.round(count) - 1);
154
+ const step = niceStep((high - low) / intervals);
155
+ const first = clean(Math.floor(low / step) * step);
156
+ const last = clean(Math.ceil(high / step) * step);
157
+ const ticks = [];
158
+ for (let index = 0;; index += 1) {
159
+ const tick = clean(first + index * step);
160
+ if (tick > last + step / 2)
161
+ break;
162
+ ticks.push(tick);
163
+ }
164
+ return { min: first, max: last, step, ticks };
165
+ }
166
+ /**
167
+ * The value axis a chart draws: its ends and its ticks.
168
+ *
169
+ * An `"auto"` end fits the data and is rounded outwards to a tick. A number is
170
+ * kept exactly and is a tick itself, with any round tick too close to it
171
+ * dropped so the two labels do not collide.
172
+ */
173
+ export function valueAxis(data, series, options = {}) {
174
+ const [lowBound, highBound] = options.domain ?? ["auto", "auto"];
175
+ const fitted = valueRange(data, series, { zero: options.zero });
176
+ const fixedLow = typeof lowBound === "number" && Number.isFinite(lowBound);
177
+ const fixedHigh = typeof highBound === "number" && Number.isFinite(highBound);
178
+ let low = fixedLow ? lowBound : fitted.min;
179
+ let high = fixedHigh ? highBound : fitted.max;
180
+ // A fixed end beyond the data on the other side: keep the fixed end and
181
+ // give the other one room.
182
+ if (low >= high) {
183
+ if (fixedLow && !fixedHigh)
184
+ high = low + Math.abs(low || 1);
185
+ else if (fixedHigh && !fixedLow)
186
+ low = high - Math.abs(high || 1);
187
+ else
188
+ [low, high] = [Math.min(low, high), Math.max(low, high)];
189
+ }
190
+ const nice = niceTicks(low, high, options.tickCount);
191
+ const min = fixedLow ? low : nice.min;
192
+ const max = fixedHigh ? high : nice.max;
193
+ if (min === max)
194
+ return { min, max: max + 1, ticks: [min, max + 1] };
195
+ const margin = nice.step / 2;
196
+ const inside = nice.ticks.filter((tick) => tick >= min &&
197
+ tick <= max &&
198
+ !(fixedLow && tick !== min && tick - min < margin) &&
199
+ !(fixedHigh && tick !== max && max - tick < margin));
200
+ const ticks = [
201
+ ...(fixedLow && !inside.includes(min) ? [min] : []),
202
+ ...inside,
203
+ ...(fixedHigh && !inside.includes(max) ? [max] : []),
204
+ ];
205
+ return { min, max, ticks };
206
+ }
207
+ /**
208
+ * Which category labels fit: every `step`-th one, the smallest step at which
209
+ * the widest label no longer reaches its neighbour.
210
+ */
211
+ export function visibleCategories(count, widestLabel, plotWidth) {
212
+ if (count === 0)
213
+ return [];
214
+ const slot = plotWidth / count;
215
+ const step = slot <= 0
216
+ ? count
217
+ : Math.max(1, Math.ceil((widestLabel + LABEL_GAP) / slot));
218
+ const visible = [];
219
+ for (let index = 0; index < count; index += step)
220
+ visible.push(index);
221
+ return visible;
222
+ }
63
223
  export const Chart = component((props) => {
64
224
  const titleId = uid("chart-title");
225
+ const plotId = uid("chart-plot");
226
+ const hintId = uid("chart-hint");
65
227
  const height = props.height ?? 240;
66
228
  const type = props.type ?? "line";
67
- const { min, max } = valueRange(props.data, props.series);
68
- const plotWidth = VIEWBOX_WIDTH - PADDING.left - PADDING.right;
69
- const plotHeight = height - PADDING.top - PADDING.bottom;
70
- const y = (value) => PADDING.top + plotHeight - ((value - min) / (max - min)) * plotHeight;
71
- /** Centre of the slot for index `i`, so points sit above their labels. */
72
- const x = (index) => {
73
- const count = Math.max(props.data.length, 1);
74
- const step = plotWidth / count;
75
- return PADDING.left + step * index + step / 2;
229
+ const data = props.data;
230
+ const series = props.series;
231
+ const count = data.length;
232
+ const numberFormat = new Intl.NumberFormat(props.locale);
233
+ const dateFormat = new Intl.DateTimeFormat(props.locale, {
234
+ dateStyle: "medium",
235
+ });
236
+ const formatValue = props.formatValue ?? ((value) => numberFormat.format(value));
237
+ const formatCategory = props.formatCategory ??
238
+ ((category) => category instanceof Date
239
+ ? dateFormat.format(category)
240
+ : String(category));
241
+ const axis = valueAxis(data, series, {
242
+ domain: props.domain,
243
+ zero: type === "bar" || props.zero !== false,
244
+ tickCount: props.tickCount,
245
+ });
246
+ const reversed = props.reversed === true;
247
+ const top = PADDING.top;
248
+ const bottom = height - PADDING.bottom;
249
+ const plotHeight = Math.max(bottom - top, 1);
250
+ /** Pixels from the top for `value`. */
251
+ const y = (value) => {
252
+ const share = (value - axis.min) / (axis.max - axis.min);
253
+ return top + (reversed ? share : 1 - share) * plotHeight;
76
254
  };
77
- const gridLines = [0, 0.25, 0.5, 0.75, 1].map((fraction) => PADDING.top + plotHeight * fraction);
78
- function linePath(series) {
79
- return props.data
80
- .map((datum, index) => `${index === 0 ? "M" : "L"}${x(index)},${y(numberAt(datum, series.key))}`)
81
- .join(" ");
82
- }
83
- function areaPath(series) {
84
- if (props.data.length === 0)
255
+ /** Centre of category `index`, as a share of the plot's width. */
256
+ const centre = (index) => count === 0 ? 0 : (index + 0.5) / count;
257
+ const percent = (share) => `${clean(share * 100)}%`;
258
+ /** The line bars and areas grow from: zero when the axis shows it. */
259
+ const baselineValue = Math.min(Math.max(0, axis.min), axis.max);
260
+ const baseline = y(baselineValue);
261
+ const tickLabels = axis.ticks.map((tick) => formatValue(tick));
262
+ const gutter = Math.ceil(Math.max(...tickLabels.map((text) => text.length), 1) * CHARACTER_WIDTH +
263
+ 10);
264
+ const categoryLabels = data.map((datum) => formatCategory(categoryAt(datum, props.categoryKey)));
265
+ const widestCategory = Math.max(...categoryLabels.map((text) => text.length), 0) * CHARACTER_WIDTH;
266
+ const plotWidth = signal(NOMINAL_PLOT_WIDTH);
267
+ /** The category the pointer or the keyboard points at. */
268
+ const active = signal(undefined);
269
+ const valueText = (value) => value === null ? "—" : formatValue(value);
270
+ /** What the tooltip shows and the live region says for `index`. */
271
+ function describe(index) {
272
+ const datum = data[index];
273
+ if (datum === undefined)
85
274
  return "";
86
- const baseline = y(Math.max(min, 0));
87
- return `${linePath(series)} L${x(props.data.length - 1)},${baseline} L${x(0)},${baseline} Z`;
275
+ const values = series.map((entry) => `${entry.label}: ${valueText(numberAt(datum, entry.key))}`);
276
+ return `${categoryLabels[index] ?? ""} — ${values.join(", ")}`;
277
+ }
278
+ let observer;
279
+ onMount(() => {
280
+ if (typeof ResizeObserver !== "function")
281
+ return;
282
+ const plot = document.getElementById(plotId);
283
+ if (plot === null)
284
+ return;
285
+ observer = new ResizeObserver((entries) => {
286
+ const width = entries[0]?.contentRect.width;
287
+ if (width !== undefined && width > 0)
288
+ plotWidth(width);
289
+ });
290
+ observer.observe(plot);
291
+ });
292
+ onUnmount(() => observer?.disconnect());
293
+ function pointAt(event) {
294
+ const plot = event.currentTarget;
295
+ if (!(plot instanceof Element) || count === 0)
296
+ return;
297
+ const box = plot.getBoundingClientRect();
298
+ if (box.width <= 0)
299
+ return;
300
+ const share = (event.clientX - box.left) / box.width;
301
+ active(Math.min(count - 1, Math.max(0, Math.floor(share * count))));
302
+ }
303
+ function onKeyDown(event) {
304
+ if (count === 0)
305
+ return;
306
+ const current = active();
307
+ let next;
308
+ switch (event.key) {
309
+ case "ArrowRight":
310
+ case "ArrowDown":
311
+ next = current === undefined ? 0 : Math.min(count - 1, current + 1);
312
+ break;
313
+ case "ArrowLeft":
314
+ case "ArrowUp":
315
+ next = current === undefined ? count - 1 : Math.max(0, current - 1);
316
+ break;
317
+ case "Home":
318
+ next = 0;
319
+ break;
320
+ case "End":
321
+ next = count - 1;
322
+ break;
323
+ case "Escape":
324
+ if (current === undefined)
325
+ return;
326
+ active(undefined);
327
+ event.preventDefault();
328
+ return;
329
+ default:
330
+ return;
331
+ }
332
+ event.preventDefault();
333
+ active(next);
88
334
  }
89
335
  return html `<figure
90
336
  data-slot="chart"
91
337
  class="${() => cn("w-full", read(props.class))}"
92
338
  >
93
- <svg
94
- viewBox="${`0 0 ${VIEWBOX_WIDTH} ${height}`}"
95
- role="img"
96
- aria-labelledby="${titleId}"
97
- preserveAspectRatio="none"
98
- class="h-auto w-full overflow-visible"
99
- >
100
- <title id="${titleId}">${props.label}</title>
101
- ${props.grid === false
102
- ? null
103
- : gridLines.map((position) => html `<line
104
- x1="${PADDING.left}"
105
- x2="${VIEWBOX_WIDTH - PADDING.right}"
106
- y1="${position}"
107
- y2="${position}"
108
- stroke="var(--border)"
109
- stroke-width="1"
110
- />`)}
111
- ${props.series.map((series, seriesIndex) => type === "bar"
112
- ? renderBars(series, seriesIndex)
113
- : renderCurve(series, seriesIndex))}
114
- ${props.data.map((datum, index) => html `<text
115
- x="${x(index)}"
116
- y="${height - 6}"
117
- text-anchor="middle"
118
- font-size="10"
339
+ <div class="flex w-full">
340
+ <svg
341
+ data-slot="chart-value-axis"
342
+ aria-hidden="true"
343
+ focusable="false"
344
+ width="${gutter}"
345
+ height="${height}"
346
+ class="shrink-0 overflow-visible"
347
+ >${axis.ticks.map((tick, index) => html `<g><text
348
+ x="${gutter - 6}"
349
+ y="${y(tick)}"
350
+ text-anchor="end"
351
+ dominant-baseline="middle"
352
+ font-size="${FONT_SIZE}"
119
353
  fill="var(--muted-foreground)"
120
- >${categoryAt(datum, props.categoryKey)}</text>`)}
121
- </svg>
354
+ >${tickLabels[index]}</text></g>`)}</svg>
355
+ <div
356
+ id="${plotId}"
357
+ data-slot="chart-plot"
358
+ role="group"
359
+ aria-roledescription="${props.roleDescription ?? "chart"}"
360
+ aria-labelledby="${titleId}"
361
+ aria-describedby="${hintId}"
362
+ tabindex="0"
363
+ class="focus-visible:ring-ring/50 relative min-w-0 flex-1 rounded-sm outline-none focus-visible:ring-[3px]"
364
+ @pointermove="${pointAt}"
365
+ @pointerdown="${pointAt}"
366
+ @pointerleave="${() => active(undefined)}"
367
+ @keydown="${onKeyDown}"
368
+ @blur="${() => active(undefined)}"
369
+ >
370
+ <svg
371
+ aria-hidden="true"
372
+ focusable="false"
373
+ width="100%"
374
+ height="${height}"
375
+ class="block overflow-visible"
376
+ >
377
+ ${props.grid === false ? null : axis.ticks.map(renderGridline)}
378
+ <svg
379
+ x="0"
380
+ y="${top - 4}"
381
+ width="100%"
382
+ height="${plotHeight + 8}"
383
+ viewBox="${`0 ${top - 4} ${Math.max(count, 1)} ${plotHeight + 8}`}"
384
+ preserveAspectRatio="none"
385
+ >${series.map((entry, index) => type === "bar"
386
+ ? renderBars(entry, index)
387
+ : renderCurve(entry, index))}</svg>
388
+ ${type === "bar" ? null : series.map(renderLonePoints)}
389
+ ${() => visibleCategories(count, widestCategory, plotWidth()).map((index) => html `<g><text
390
+ x="${percent(centre(index))}"
391
+ y="${height - 6}"
392
+ text-anchor="middle"
393
+ font-size="${FONT_SIZE}"
394
+ fill="var(--muted-foreground)"
395
+ >${categoryLabels[index]}</text></g>`)}
396
+ ${() => renderMarker(active())}
397
+ </svg>
398
+ ${() => renderTooltip(active())}
399
+ </div>
400
+ </div>
401
+ <span id="${titleId}" class="sr-only">${props.label}</span>
402
+ <span id="${hintId}" class="sr-only">${count === 0
403
+ ? ""
404
+ : (props.keyboardHint ?? "Arrow keys read each category.")}</span>
405
+ <div role="status" aria-live="polite" class="sr-only">${() => {
406
+ const index = active();
407
+ return index === undefined ? "" : describe(index);
408
+ }}</div>
122
409
  <figcaption class="sr-only">${renderDataTable()}</figcaption>
123
410
  <div data-slot="chart-legend" class="mt-2 flex flex-wrap justify-center gap-4 text-xs">
124
- ${props.series.map((series, index) => html `<span class="flex items-center gap-1.5">
125
- <span
126
- aria-hidden="true"
127
- class="size-2 shrink-0 rounded-[2px]"
128
- style="${`background:${colorFor(series, index)}`}"
129
- ></span>
130
- <span class="text-muted-foreground">${series.label}</span>
411
+ ${series.map((entry, index) => html `<span class="flex items-center gap-1.5">
412
+ ${swatch(colorFor(entry, index))}
413
+ <span class="text-muted-foreground">${entry.label}</span>
131
414
  </span>`)}
132
415
  </div>
133
416
  </figure>`;
134
- function renderCurve(series, index) {
135
- const color = colorFor(series, index);
136
- return html `<g>
137
- ${type === "area"
138
- ? html `<path d="${areaPath(series)}" fill="${color}" fill-opacity="0.15" />`
417
+ function swatch(color) {
418
+ return html `<svg
419
+ aria-hidden="true"
420
+ focusable="false"
421
+ viewBox="0 0 8 8"
422
+ class="size-2 shrink-0"
423
+ ><rect width="8" height="8" rx="2" fill="${color}" /></svg>`;
424
+ }
425
+ function renderGridline(tick) {
426
+ return html `<g><line
427
+ x1="0"
428
+ x2="100%"
429
+ y1="${y(tick)}"
430
+ y2="${y(tick)}"
431
+ stroke="var(--border)"
432
+ stroke-width="1"
433
+ /></g>`;
434
+ }
435
+ /**
436
+ * The runs of consecutive values, each one an unbroken stretch of line. A
437
+ * gap ends a run; nothing is drawn across it.
438
+ */
439
+ function runsOf(entry) {
440
+ const runs = [];
441
+ let run = [];
442
+ data.forEach((datum, index) => {
443
+ const value = numberAt(datum, entry.key);
444
+ if (value === null) {
445
+ if (run.length > 0)
446
+ runs.push(run);
447
+ run = [];
448
+ return;
449
+ }
450
+ run.push({ index, value });
451
+ });
452
+ if (run.length > 0)
453
+ runs.push(run);
454
+ return runs;
455
+ }
456
+ function renderCurve(entry, index) {
457
+ const color = colorFor(entry, index);
458
+ const runs = runsOf(entry);
459
+ const line = runs
460
+ .map((run) => run
461
+ .map((point, at) => `${at === 0 ? "M" : "L"}${clean(point.index + 0.5)},${clean(y(point.value))}`)
462
+ .join(" "))
463
+ .join(" ");
464
+ const area = runs
465
+ .filter((run) => run.length > 1)
466
+ .map((run) => {
467
+ const first = run[0];
468
+ const last = run[run.length - 1];
469
+ if (first === undefined || last === undefined)
470
+ return "";
471
+ const path = run
472
+ .map((point, at) => `${at === 0 ? "M" : "L"}${clean(point.index + 0.5)},${clean(y(point.value))}`)
473
+ .join(" ");
474
+ return `${path} L${clean(last.index + 0.5)},${clean(baseline)} L${clean(first.index + 0.5)},${clean(baseline)} Z`;
475
+ })
476
+ .join(" ");
477
+ return html `<g data-series="${entry.key}">
478
+ ${type === "area" && area !== ""
479
+ ? html `<path d="${area}" fill="${color}" fill-opacity="0.15" />`
139
480
  : null}
140
481
  <path
141
- d="${linePath(series)}"
482
+ d="${line}"
142
483
  fill="none"
143
484
  stroke="${color}"
144
485
  stroke-width="2"
145
486
  stroke-linecap="round"
146
487
  stroke-linejoin="round"
488
+ vector-effect="non-scaling-stroke"
147
489
  />
148
490
  </g>`;
149
491
  }
150
- function renderBars(series, seriesIndex) {
151
- const count = Math.max(props.data.length, 1);
152
- const slot = plotWidth / count;
492
+ /**
493
+ * A value with a gap on both sides has no segment to be part of; drawn as a
494
+ * line it would be invisible. A dot shows it exists.
495
+ */
496
+ function renderLonePoints(entry, index) {
497
+ const lone = runsOf(entry).filter((run) => run.length === 1);
498
+ return html `<g data-lone="${entry.key}" fill="${colorFor(entry, index)}">${lone.map((run) => {
499
+ const point = run[0];
500
+ if (point === undefined)
501
+ return null;
502
+ return html `<circle
503
+ cx="${percent(centre(point.index))}"
504
+ cy="${y(point.value)}"
505
+ r="2.5"
506
+ />`;
507
+ })}</g>`;
508
+ }
509
+ function renderBars(entry, seriesIndex) {
153
510
  // Share each slot between the series so grouped bars sit side by side,
154
511
  // with a quarter of the slot left as the gap between groups.
155
- const barWidth = (slot * 0.75) / props.series.length;
156
- const baseline = y(Math.max(min, 0));
157
- return html `<g fill="${colorFor(series, seriesIndex)}">
158
- ${props.data.map((datum, index) => {
159
- const top = y(numberAt(datum, series.key));
160
- const left = PADDING.left + slot * index + slot * 0.125 + barWidth * seriesIndex;
512
+ const barWidth = 0.75 / Math.max(series.length, 1);
513
+ return html `<g data-series="${entry.key}" fill="${colorFor(entry, seriesIndex)}">
514
+ ${data.map((datum, index) => {
515
+ const value = numberAt(datum, entry.key);
516
+ if (value === null)
517
+ return null;
518
+ const tip = y(value);
161
519
  return html `<rect
162
- x="${left}"
163
- y="${Math.min(top, baseline)}"
164
- width="${barWidth}"
165
- height="${Math.abs(baseline - top)}"
166
- rx="2"
520
+ x="${clean(index + 0.125 + barWidth * seriesIndex)}"
521
+ y="${clean(Math.min(tip, baseline))}"
522
+ width="${clean(barWidth)}"
523
+ height="${clean(Math.abs(baseline - tip))}"
167
524
  />`;
168
525
  })}
169
526
  </g>`;
170
527
  }
528
+ /** The guide under the pointer, and a dot on each value it crosses. */
529
+ function renderMarker(index) {
530
+ const datum = index === undefined ? undefined : data[index];
531
+ if (index === undefined || datum === undefined)
532
+ return null;
533
+ const x = percent(centre(index));
534
+ return html `<g data-slot="chart-marker">
535
+ <line
536
+ x1="${x}"
537
+ x2="${x}"
538
+ y1="${top}"
539
+ y2="${bottom}"
540
+ stroke="var(--muted-foreground)"
541
+ stroke-width="1"
542
+ stroke-dasharray="3 3"
543
+ />
544
+ ${type === "bar"
545
+ ? null
546
+ : series.map((entry, seriesIndex) => {
547
+ const value = numberAt(datum, entry.key);
548
+ if (value === null)
549
+ return null;
550
+ return html `<circle
551
+ cx="${x}"
552
+ cy="${y(value)}"
553
+ r="4"
554
+ fill="${colorFor(entry, seriesIndex)}"
555
+ stroke="var(--background)"
556
+ stroke-width="2"
557
+ />`;
558
+ })}
559
+ </g>`;
560
+ }
561
+ /**
562
+ * The values at the pointed category. Hidden from assistive technology —
563
+ * the live region says the same — and placed through `.style`, which goes
564
+ * through the CSSOM: a `style` attribute would be blocked by a strict CSP.
565
+ */
566
+ function renderTooltip(index) {
567
+ const datum = index === undefined ? undefined : data[index];
568
+ if (index === undefined || datum === undefined)
569
+ return null;
570
+ const share = centre(index);
571
+ const side = share < 0.2
572
+ ? "translate-x-2"
573
+ : share > 0.8
574
+ ? "-translate-x-full -ml-2"
575
+ : "-translate-x-1/2";
576
+ return html `<div
577
+ data-slot="chart-tooltip"
578
+ aria-hidden="true"
579
+ class="${cn("bg-popover text-popover-foreground pointer-events-none absolute top-0 z-10 grid min-w-32 gap-1 rounded-md border px-2.5 py-1.5 text-xs shadow-md", side)}"
580
+ .style="${`left:${percent(share)}`}"
581
+ >
582
+ <div class="font-medium">${categoryLabels[index]}</div>
583
+ ${series.map((entry, seriesIndex) => html `<div class="flex items-center gap-1.5">
584
+ ${swatch(colorFor(entry, seriesIndex))}
585
+ <span class="text-muted-foreground">${entry.label}</span>
586
+ <span class="ml-auto font-mono font-medium tabular-nums">${valueText(numberAt(datum, entry.key))}</span>
587
+ </div>`)}
588
+ </div>`;
589
+ }
171
590
  /** The same numbers as a real table, for anything that cannot see the SVG. */
172
591
  function renderDataTable() {
173
592
  return html `<table>
@@ -175,13 +594,13 @@ export const Chart = component((props) => {
175
594
  <thead>
176
595
  <tr>
177
596
  <th scope="col">${props.categoryKey}</th>
178
- ${props.series.map((series) => html `<th scope="col">${series.label}</th>`)}
597
+ ${series.map((entry) => html `<th scope="col">${entry.label}</th>`)}
179
598
  </tr>
180
599
  </thead>
181
600
  <tbody>
182
- ${props.data.map((datum) => html `<tr>
183
- <th scope="row">${categoryAt(datum, props.categoryKey)}</th>
184
- ${props.series.map((series) => html `<td>${numberAt(datum, series.key)}</td>`)}
601
+ ${data.map((datum, index) => html `<tr>
602
+ <th scope="row">${categoryLabels[index]}</th>
603
+ ${series.map((entry) => html `<td>${valueText(numberAt(datum, entry.key))}</td>`)}
185
604
  </tr>`)}
186
605
  </tbody>
187
606
  </table>`;