@pharos-ds/charts 0.0.0-stage → 1.0.10

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 (139) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/LICENSE +24 -0
  3. package/README.md +117 -2
  4. package/dist/Chart.d.ts +62 -0
  5. package/dist/Chart.d.ts.map +1 -0
  6. package/dist/Chart.js +401 -0
  7. package/dist/ChartAxis.d.ts +37 -0
  8. package/dist/ChartAxis.d.ts.map +1 -0
  9. package/dist/ChartAxis.js +233 -0
  10. package/dist/ChartContext.d.ts +4 -0
  11. package/dist/ChartContext.d.ts.map +1 -0
  12. package/dist/ChartContext.js +15 -0
  13. package/dist/ChartGrid.d.ts +26 -0
  14. package/dist/ChartGrid.d.ts.map +1 -0
  15. package/dist/ChartGrid.js +118 -0
  16. package/dist/ChartLegend.d.ts +14 -0
  17. package/dist/ChartLegend.d.ts.map +1 -0
  18. package/dist/ChartLegend.js +62 -0
  19. package/dist/ChartSwatch.d.ts +36 -0
  20. package/dist/ChartSwatch.d.ts.map +1 -0
  21. package/dist/ChartSwatch.js +85 -0
  22. package/dist/ChartTooltip.d.ts +46 -0
  23. package/dist/ChartTooltip.d.ts.map +1 -0
  24. package/dist/ChartTooltip.js +330 -0
  25. package/dist/charts.css +33 -0
  26. package/dist/dataTable.d.ts +56 -0
  27. package/dist/dataTable.d.ts.map +1 -0
  28. package/dist/dataTable.js +88 -0
  29. package/dist/formatters.d.ts +37 -0
  30. package/dist/formatters.d.ts.map +1 -0
  31. package/dist/formatters.js +156 -0
  32. package/dist/getChartColors.d.ts +67 -0
  33. package/dist/getChartColors.d.ts.map +1 -0
  34. package/dist/getChartColors.js +191 -0
  35. package/dist/index.d.ts +17 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +19 -0
  38. package/dist/layout.d.ts +40 -0
  39. package/dist/layout.d.ts.map +1 -0
  40. package/dist/layout.js +322 -0
  41. package/dist/legend.d.ts +17 -0
  42. package/dist/legend.d.ts.map +1 -0
  43. package/dist/legend.js +40 -0
  44. package/dist/markColor.d.ts +20 -0
  45. package/dist/markColor.d.ts.map +1 -0
  46. package/dist/markColor.js +56 -0
  47. package/dist/marks/area.d.ts +19 -0
  48. package/dist/marks/area.d.ts.map +1 -0
  49. package/dist/marks/area.js +121 -0
  50. package/dist/marks/band.d.ts +9 -0
  51. package/dist/marks/band.d.ts.map +1 -0
  52. package/dist/marks/band.js +64 -0
  53. package/dist/marks/bar.d.ts +21 -0
  54. package/dist/marks/bar.d.ts.map +1 -0
  55. package/dist/marks/bar.js +161 -0
  56. package/dist/marks/candlestick.d.ts +16 -0
  57. package/dist/marks/candlestick.d.ts.map +1 -0
  58. package/dist/marks/candlestick.js +110 -0
  59. package/dist/marks/dot.d.ts +19 -0
  60. package/dist/marks/dot.d.ts.map +1 -0
  61. package/dist/marks/dot.js +98 -0
  62. package/dist/marks/dotGL.d.ts +16 -0
  63. package/dist/marks/dotGL.d.ts.map +1 -0
  64. package/dist/marks/dotGL.js +231 -0
  65. package/dist/marks/dotGLInteractive.d.ts +35 -0
  66. package/dist/marks/dotGLInteractive.d.ts.map +1 -0
  67. package/dist/marks/dotGLInteractive.js +584 -0
  68. package/dist/marks/errorBar.d.ts +29 -0
  69. package/dist/marks/errorBar.d.ts.map +1 -0
  70. package/dist/marks/errorBar.js +95 -0
  71. package/dist/marks/heatmapGL.d.ts +27 -0
  72. package/dist/marks/heatmapGL.d.ts.map +1 -0
  73. package/dist/marks/heatmapGL.js +335 -0
  74. package/dist/marks/index.d.ts +13 -0
  75. package/dist/marks/index.d.ts.map +1 -0
  76. package/dist/marks/index.js +14 -0
  77. package/dist/marks/line.d.ts +18 -0
  78. package/dist/marks/line.d.ts.map +1 -0
  79. package/dist/marks/line.js +83 -0
  80. package/dist/marks/referenceLine.d.ts +37 -0
  81. package/dist/marks/referenceLine.d.ts.map +1 -0
  82. package/dist/marks/referenceLine.js +204 -0
  83. package/dist/marks/streamGL.d.ts +41 -0
  84. package/dist/marks/streamGL.d.ts.map +1 -0
  85. package/dist/marks/streamGL.js +317 -0
  86. package/dist/tooltip.d.ts +38 -0
  87. package/dist/tooltip.d.ts.map +1 -0
  88. package/dist/tooltip.js +57 -0
  89. package/dist/types.d.ts +193 -0
  90. package/dist/types.d.ts.map +1 -0
  91. package/dist/types.js +70 -0
  92. package/dist/useChartColors.d.ts +16 -0
  93. package/dist/useChartColors.d.ts.map +1 -0
  94. package/dist/useChartColors.js +37 -0
  95. package/dist/utils.d.ts +15 -0
  96. package/dist/utils.d.ts.map +1 -0
  97. package/dist/utils.js +31 -0
  98. package/dist/webgl.d.ts +77 -0
  99. package/dist/webgl.d.ts.map +1 -0
  100. package/dist/webgl.js +235 -0
  101. package/package.json +71 -3
  102. package/src/Chart.doc.mjs +174 -0
  103. package/src/Chart.test.tsx +273 -0
  104. package/src/Chart.tsx +535 -0
  105. package/src/ChartAxis.tsx +289 -0
  106. package/src/ChartContext.ts +18 -0
  107. package/src/ChartGrid.tsx +136 -0
  108. package/src/ChartLegend.tsx +77 -0
  109. package/src/ChartSwatch.doc.mjs +17 -0
  110. package/src/ChartSwatch.tsx +89 -0
  111. package/src/ChartTooltip.tsx +452 -0
  112. package/src/charts.css.d.ts +3 -0
  113. package/src/dataTable.test.ts +86 -0
  114. package/src/dataTable.ts +124 -0
  115. package/src/formatters.ts +167 -0
  116. package/src/getChartColors.test.ts +114 -0
  117. package/src/getChartColors.ts +282 -0
  118. package/src/index.ts +88 -0
  119. package/src/layout.ts +372 -0
  120. package/src/legend.ts +44 -0
  121. package/src/markColor.ts +70 -0
  122. package/src/marks/area.tsx +142 -0
  123. package/src/marks/band.tsx +86 -0
  124. package/src/marks/bar.tsx +210 -0
  125. package/src/marks/candlestick.tsx +128 -0
  126. package/src/marks/dot.tsx +119 -0
  127. package/src/marks/dotGL.tsx +274 -0
  128. package/src/marks/dotGLInteractive.tsx +660 -0
  129. package/src/marks/errorBar.tsx +119 -0
  130. package/src/marks/heatmapGL.tsx +392 -0
  131. package/src/marks/index.ts +17 -0
  132. package/src/marks/line.tsx +118 -0
  133. package/src/marks/referenceLine.tsx +252 -0
  134. package/src/marks/streamGL.tsx +381 -0
  135. package/src/tooltip.ts +73 -0
  136. package/src/types.ts +212 -0
  137. package/src/useChartColors.ts +41 -0
  138. package/src/utils.ts +38 -0
  139. package/src/webgl.ts +262 -0
@@ -0,0 +1,452 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file ChartTooltip.tsx
5
+ * @output Grouped chart tooltip — shows all series values at the hovered x-position.
6
+ * Composable: drop into `<Chart tooltip>` or render directly inside a chart
7
+ * to take full control of props.
8
+ * @position Reads from ChartContext — must render inside an <Chart>.
9
+ *
10
+ * Pointer-only: the card is portaled with `pointer-events: none` and holds no
11
+ * focusable content, so it never traps keyboard focus. Keyboard/screen-reader
12
+ * users get the same values from the chart's hidden data table instead.
13
+ *
14
+ * In a horizontal chart the tooltip renders in the vertical plot space (Chart
15
+ * wraps it in the same transpose as the marks), so only the screen position of
16
+ * the card needs to know about `orientation`.
17
+ *
18
+ * @example
19
+ * ```
20
+ * // Default — declarative on Chart
21
+ * <Chart tooltip />
22
+ *
23
+ * // Custom render function via Chart prop
24
+ * <Chart tooltip={{render: (x, rows) => <MyCard x={x} rows={rows} />}} />
25
+ *
26
+ * // Composable — drop into the chart's children for full control
27
+ * <Chart>
28
+ * <ChartTooltip hoverIndicator={false} placement="top" />
29
+ * </Chart>
30
+ * ```
31
+ */
32
+
33
+ 'use client';
34
+
35
+ import {
36
+ memo,
37
+ useState,
38
+ useEffect,
39
+ useMemo,
40
+ useRef,
41
+ useCallback,
42
+ type ReactNode,
43
+ } from 'react';
44
+ import {createPortal} from 'react-dom';
45
+ import * as stylex from '@stylexjs/stylex';
46
+ import {
47
+ colorVars,
48
+ radiusVars,
49
+ shadowVars,
50
+ spacingVars,
51
+ } from '@pharos-ds/core/theme/tokens.stylex';
52
+ import {Text} from '@pharos-ds/core';
53
+ import {VStack, HStack} from '@pharos-ds/core';
54
+ import {useChart} from './ChartContext';
55
+ import {ChartSwatch, swatchVariantForType} from './ChartSwatch';
56
+ import {
57
+ deriveTooltipSeriesValues,
58
+ shouldRenderHoverDot,
59
+ type TooltipSeriesValue,
60
+ } from './tooltip';
61
+ import type {SeriesDef, ChartPointerEvent} from './types';
62
+ import {isBandScale, xPixel} from './utils';
63
+
64
+ export type ChartTooltipPlacement = 'auto' | 'right' | 'left' | 'top';
65
+
66
+ export interface ChartTooltipProps {
67
+ /**
68
+ * Series definitions — used to map the hovered datum to per-series rows.
69
+ * When rendered via `<Chart tooltip />`, Chart injects this automatically.
70
+ * When composing directly, pass the same `series` array you gave Chart.
71
+ */
72
+ series?: readonly SeriesDef[];
73
+ /**
74
+ * Custom render function. Receives the x-value and one row per visible series.
75
+ * Returning `null` hides the card while still rendering the band highlight + dots.
76
+ */
77
+ render?: (xValue: unknown, seriesValues: TooltipSeriesValue[]) => ReactNode;
78
+ /**
79
+ * Whether to draw a hover indicator at the focused x-position.
80
+ * Picks the right shape automatically:
81
+ * - **band-highlight rect** when the chart includes bar series on a band scale
82
+ * - **vertical crosshair line** for line / area / dot charts
83
+ *
84
+ * Default: `true`.
85
+ */
86
+ hoverIndicator?: boolean;
87
+ /**
88
+ * Whether to draw a hover dot at each series' point (skipped for bars).
89
+ * Default: `true`.
90
+ */
91
+ showHoverDots?: boolean;
92
+ /**
93
+ * Card placement relative to the hovered point:
94
+ * - `'auto'` (default): right of the point, flips to left if it would overflow
95
+ * - `'right'` / `'left'` / `'top'`: pinned position
96
+ */
97
+ placement?: ChartTooltipPlacement;
98
+ }
99
+
100
+ const styles = stylex.create({
101
+ // Card chrome — static visual styles. Position (left/top/display) is updated
102
+ // imperatively via ref to keep pointer-move cost free of React renders.
103
+ card: {
104
+ position: 'fixed',
105
+ backgroundColor: colorVars['--color-background-popover'],
106
+ border: `1px solid ${colorVars['--color-border']}`,
107
+ borderRadius: radiusVars['--radius-container'],
108
+ paddingBlock: spacingVars['--spacing-2'],
109
+ paddingInline: spacingVars['--spacing-3'],
110
+ boxShadow: shadowVars['--shadow-med'],
111
+ pointerEvents: 'none',
112
+ whiteSpace: 'nowrap',
113
+ zIndex: 9999,
114
+ display: 'none',
115
+ },
116
+ crosshair: {
117
+ stroke: colorVars['--color-text-primary'],
118
+ strokeWidth: 1,
119
+ },
120
+ });
121
+
122
+ /** Default tooltip body — used when `render` is not provided. */
123
+ const DefaultTooltipContent = memo(function DefaultTooltipContent({
124
+ xValue,
125
+ rows,
126
+ }: {
127
+ xValue: unknown;
128
+ rows: TooltipSeriesValue[];
129
+ }) {
130
+ return (
131
+ <VStack gap={1}>
132
+ <Text type="body" weight="semibold">
133
+ {String(xValue)}
134
+ </Text>
135
+ {rows.length === 1 ? (
136
+ <Text type="supporting">{String(rows[0].value)}</Text>
137
+ ) : (
138
+ <VStack gap={1}>
139
+ {rows.map((row, i) => (
140
+ <HStack key={`${row.key}-${i}`} gap={2} vAlign="center">
141
+ <ChartSwatch
142
+ color={row.color}
143
+ variant={swatchVariantForType(row.type)}
144
+ />
145
+ <Text type="supporting">{row.label}</Text>
146
+ <Text type="supporting" weight="semibold">
147
+ {String(row.value)}
148
+ </Text>
149
+ </HStack>
150
+ ))}
151
+ </VStack>
152
+ )}
153
+ </VStack>
154
+ );
155
+ });
156
+
157
+ /**
158
+ * Composable grouped tooltip for Chart.
159
+ *
160
+ * Subscribes to the chart's pointer event stream and only re-renders when the
161
+ * hovered data index changes (not on every pointer move). Card position is
162
+ * updated imperatively via a ref to keep pointer-move cost ~free.
163
+ */
164
+ export function ChartTooltip({
165
+ series = [],
166
+ render,
167
+ hoverIndicator = true,
168
+ showHoverDots = true,
169
+ placement = 'auto',
170
+ }: ChartTooltipProps) {
171
+ const {
172
+ data,
173
+ xKey,
174
+ resolved,
175
+ onPointer,
176
+ svgRef,
177
+ margin,
178
+ xScale,
179
+ width,
180
+ height,
181
+ orientation,
182
+ } = useChart();
183
+ const isHorizontal = orientation === 'horizontal';
184
+ const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
185
+ const cardRef = useRef<HTMLDivElement>(null);
186
+ // Whether the card is currently suppressed (no content, or a custom `render`
187
+ // opted out by returning null). positionCard reads this so a same-index
188
+ // pointer move — which repositions the card without a React commit — can't
189
+ // re-reveal a card the visibility effect below has hidden.
190
+ const cardHiddenRef = useRef(false);
191
+
192
+ // Stable Set of resolved series keys — used by deriveTooltipSeriesValues.
193
+ // Recomputed only when the resolved map identity changes (per layout pass).
194
+ const resolvedKeys = useMemo(() => new Set(resolved.keys()), [resolved]);
195
+
196
+ // ─── Card positioning ──────────────────────────────────────────────────
197
+ // Imperative — the card is portaled, and we don't want pointer-move to
198
+ // trigger React renders.
199
+ const positionCard = useCallback(
200
+ (e: ChartPointerEvent) => {
201
+ const card = cardRef.current;
202
+ const svg = svgRef.current;
203
+ if (!card) {
204
+ return;
205
+ }
206
+ if (!svg || !e.nearest || cardHiddenRef.current) {
207
+ card.style.display = 'none';
208
+ return;
209
+ }
210
+ const svgRect = svg.getBoundingClientRect();
211
+ const cardWidth = card.offsetWidth;
212
+ const cardHeight = card.offsetHeight;
213
+ // Plot space → screen. Horizontal charts are transposed: the category
214
+ // (px) runs down the y-axis and the value end of the mark (py) maps to
215
+ // x = plot height − py, so the card sits beside the hovered row.
216
+ const screenX = isHorizontal
217
+ ? svgRect.left +
218
+ margin.left +
219
+ (Number.isFinite(e.nearest.py) ? height - e.nearest.py : 0)
220
+ : svgRect.left + margin.left + e.nearest.px;
221
+ const screenY = isHorizontal
222
+ ? svgRect.top + margin.top + e.nearest.px - cardHeight / 2
223
+ : svgRect.top + margin.top;
224
+ const viewportWidth = window.innerWidth;
225
+ const viewportHeight = window.innerHeight;
226
+ const gap = 8;
227
+
228
+ let x: number;
229
+ let y = screenY;
230
+ switch (placement) {
231
+ case 'left':
232
+ x = screenX - cardWidth - gap;
233
+ break;
234
+ case 'right':
235
+ x = screenX + gap;
236
+ break;
237
+ case 'top':
238
+ x = screenX - cardWidth / 2;
239
+ y = screenY - cardHeight - gap;
240
+ break;
241
+ case 'auto':
242
+ default: {
243
+ const rightX = screenX + gap;
244
+ x =
245
+ rightX + cardWidth > viewportWidth
246
+ ? screenX - cardWidth - gap
247
+ : rightX;
248
+ }
249
+ }
250
+
251
+ // Clamp to the viewport so the card never clips off-screen — it's
252
+ // portaled and position:fixed, so this keeps it fully visible for every
253
+ // placement (pinned placements and the near-edge `auto` flip alike).
254
+ x = Math.max(gap, Math.min(x, viewportWidth - cardWidth - gap));
255
+ y = Math.max(gap, Math.min(y, viewportHeight - cardHeight - gap));
256
+
257
+ card.style.left = `${x}px`;
258
+ card.style.top = `${y}px`;
259
+ card.style.display = 'block';
260
+ },
261
+ [svgRef, margin, placement, isHorizontal, height],
262
+ );
263
+
264
+ // ─── Subscribe to pointer events ───────────────────────────────────────
265
+ useEffect(() => {
266
+ let currentIndex: number | null = null;
267
+ const unsub = onPointer((e: ChartPointerEvent) => {
268
+ const newIndex = e.nearest?.dataIndex ?? null;
269
+ if (newIndex !== currentIndex) {
270
+ currentIndex = newIndex;
271
+ // Optimistically treat the new index as showable; the visibility effect
272
+ // re-hides it after commit if there's no content (e.g. custom `render`
273
+ // returned null). This keeps the card appearing on the first move.
274
+ cardHiddenRef.current = false;
275
+ setHoveredIndex(newIndex);
276
+ }
277
+ positionCard(e);
278
+ });
279
+ return unsub;
280
+ }, [onPointer, positionCard]);
281
+
282
+ // ─── Derived data ──────────────────────────────────────────────────────
283
+ const datum = hoveredIndex != null ? data[hoveredIndex] : undefined;
284
+ const xValue = datum?.[xKey];
285
+
286
+ const seriesValues = useMemo(
287
+ () => deriveTooltipSeriesValues(series, datum, resolvedKeys),
288
+ [series, datum, resolvedKeys],
289
+ );
290
+
291
+ // Hover dots — read from the resolved map at the hovered index.
292
+ const dots = useMemo(() => {
293
+ if (!showHoverDots || hoveredIndex == null) {
294
+ return null;
295
+ }
296
+ const elements: ReactNode[] = [];
297
+ for (const s of series) {
298
+ if (!shouldRenderHoverDot(s.type)) {
299
+ continue;
300
+ }
301
+ const points = s._uid ? resolved.get(s._uid) : undefined;
302
+ const point = points?.find(p => p.dataIndex === hoveredIndex);
303
+ // A resolved point exists at every index, but its coordinates are NaN when
304
+ // this series' value here is missing/non-finite (the mark itself filters
305
+ // these at render time — mirror that so we never emit cx/cy="NaN").
306
+ if (!point || !Number.isFinite(point.px) || !Number.isFinite(point.py)) {
307
+ continue;
308
+ }
309
+ elements.push(
310
+ <circle
311
+ key={s._uid}
312
+ cx={point.px}
313
+ cy={point.py}
314
+ r={4}
315
+ fill="var(--color-background-surface)"
316
+ stroke={
317
+ s.color ?? s._resolvedColor ?? 'var(--color-border-emphasized)'
318
+ }
319
+ strokeWidth={2}
320
+ pointerEvents="none"
321
+ />,
322
+ );
323
+ }
324
+ return elements;
325
+ }, [showHoverDots, hoveredIndex, series, resolved]);
326
+
327
+ // Hover indicator — band-highlight rect for bar charts, vertical crosshair
328
+ // line for line/area charts. Same source-of-truth (hoveredIndex), distinct
329
+ // visual idioms picked automatically based on the series mix.
330
+ const hoverIndicatorElement = useMemo(() => {
331
+ if (!hoverIndicator || hoveredIndex == null) {
332
+ return null;
333
+ }
334
+ const hoveredDatum = data[hoveredIndex];
335
+ const xv = hoveredDatum?.[xKey];
336
+ if (hoveredDatum == null || xv == null) {
337
+ return null;
338
+ }
339
+ const hasBars = series.some(s => s.type === 'bar');
340
+
341
+ // Bar charts on a band scale → soft column highlight.
342
+ if (hasBars && isBandScale(xScale)) {
343
+ const x = xScale(String(xv)) ?? 0;
344
+ const bw = xScale.bandwidth();
345
+ const pad = 8;
346
+ const rectX = Math.max(0, x - pad);
347
+ const rectRight = Math.min(width, x + bw + pad);
348
+ const rectWidth = rectRight - rectX;
349
+ // Plot-space "top" is the display's right edge when horizontal.
350
+ const topPad = Math.min(pad, isHorizontal ? margin.right : margin.top);
351
+ return (
352
+ <rect
353
+ x={rectX}
354
+ y={-topPad}
355
+ width={rectWidth}
356
+ height={height + topPad}
357
+ fill="currentColor"
358
+ opacity={0.06}
359
+ rx={4}
360
+ pointerEvents="none"
361
+ />
362
+ );
363
+ }
364
+
365
+ // Line / area / dot charts → vertical crosshair through the point
366
+ // (band-center or linear position, resolved by the shared helper).
367
+ const px = xPixel(hoveredDatum, xKey, xScale);
368
+ // xPixel returns NaN for a non-finite x on a linear scale; skip rather than
369
+ // emit x1/x2="NaN". (The band branch above is always finite via `?? 0`.)
370
+ if (!Number.isFinite(px)) {
371
+ return null;
372
+ }
373
+ return (
374
+ <line
375
+ x1={px}
376
+ x2={px}
377
+ y1={0}
378
+ y2={height}
379
+ {...stylex.props(styles.crosshair)}
380
+ pointerEvents="none"
381
+ />
382
+ );
383
+ }, [
384
+ hoverIndicator,
385
+ hoveredIndex,
386
+ series,
387
+ xScale,
388
+ data,
389
+ xKey,
390
+ width,
391
+ height,
392
+ margin.top,
393
+ margin.right,
394
+ isHorizontal,
395
+ ]);
396
+
397
+ // Single source of truth for whether the card has anything to show. It's
398
+ // hidden when there's no hover, when the hovered index is stale/out-of-range
399
+ // (e.g. `data` shrank while hovering, so `datum` is undefined), or when a
400
+ // custom `render` opts out by returning null — the documented contract, which
401
+ // still shows the band highlight + dots. The decision is stored in a ref so
402
+ // the imperative positionCard honors it on subsequent same-index moves
403
+ // (otherwise it would re-reveal an empty bordered box). Runs after commit, so
404
+ // `render` (which may return null, or throw) never executes on the SSR path.
405
+ useEffect(() => {
406
+ const hidden =
407
+ hoveredIndex == null ||
408
+ datum == null ||
409
+ (render != null && render(xValue, seriesValues) == null);
410
+ cardHiddenRef.current = hidden;
411
+ if (hidden) {
412
+ const card = cardRef.current;
413
+ if (card) {
414
+ card.style.display = 'none';
415
+ }
416
+ }
417
+ }, [render, hoveredIndex, datum, xValue, seriesValues]);
418
+
419
+ // ─── Render ────────────────────────────────────────────────────────────
420
+ if (typeof document === 'undefined') {
421
+ // SSR: no DOM portal target; band highlight + dots still render in SVG.
422
+ return (
423
+ <>
424
+ {hoverIndicatorElement}
425
+ {dots}
426
+ </>
427
+ );
428
+ }
429
+
430
+ // Mirrors the visibility effect's first two conditions: no card when there's
431
+ // no hover or the hovered datum is stale/out-of-range (so `render` and the
432
+ // default body are never called with an undefined x-value + empty rows).
433
+ const cardContent =
434
+ hoveredIndex == null || datum == null ? null : render ? (
435
+ render(xValue, seriesValues)
436
+ ) : (
437
+ <DefaultTooltipContent xValue={xValue} rows={seriesValues} />
438
+ );
439
+
440
+ return (
441
+ <>
442
+ {hoverIndicatorElement}
443
+ {dots}
444
+ {createPortal(
445
+ <div ref={cardRef} role="tooltip" {...stylex.props(styles.card)}>
446
+ {cardContent}
447
+ </div>,
448
+ document.body,
449
+ )}
450
+ </>
451
+ );
452
+ }
@@ -0,0 +1,3 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ export {};
@@ -0,0 +1,86 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ import {describe, expect, it} from 'vitest';
4
+ import {buildDataTable, fallbackChartLabel} from './dataTable';
5
+ import {bar, line, band, candlestick, errorBar} from './marks';
6
+
7
+ const data = [
8
+ {mes: 'jan', leads: 1200, custo: 300.5},
9
+ {mes: 'fev', leads: null, custo: 280},
10
+ ];
11
+
12
+ describe('buildDataTable', () => {
13
+ it('builds headers from xKey + series labels and one row per datum', () => {
14
+ const model = buildDataTable(data, 'mes', [
15
+ bar('leads', {label: 'Leads'}),
16
+ line('custo'),
17
+ ]);
18
+ expect(model?.headers).toEqual(['mes', 'Leads', 'custo']);
19
+ expect(model?.rows.map(r => r.header)).toEqual(['jan', 'fev']);
20
+ expect(model?.rows[0].cells).toEqual([
21
+ (1200).toLocaleString(),
22
+ (300.5).toLocaleString(),
23
+ ]);
24
+ // Missing values become empty cells, never "null"/"NaN".
25
+ expect(model?.rows[1].cells[0]).toBe('');
26
+ });
27
+
28
+ it('skips utility marks and splits multi-key marks into columns', () => {
29
+ const model = buildDataTable(
30
+ [{d: 'seg', open: 1, high: 3, low: 0, close: 2, lo: 0, hi: 1}],
31
+ 'd',
32
+ [
33
+ candlestick({
34
+ open: 'open',
35
+ high: 'high',
36
+ low: 'low',
37
+ close: 'close',
38
+ }),
39
+ band({lower: 'lo', upper: 'hi'}),
40
+ errorBar({low: 'lo', high: 'hi'}),
41
+ ],
42
+ );
43
+ expect(model?.headers).toEqual([
44
+ 'd',
45
+ 'ohlc-close (open)',
46
+ 'ohlc-close (high)',
47
+ 'ohlc-close (low)',
48
+ 'ohlc-close (close)',
49
+ ]);
50
+ });
51
+
52
+ it('applies custom labels and formatters', () => {
53
+ const model = buildDataTable(data, 'mes', [bar('leads')], {
54
+ xLabel: 'Mês',
55
+ formatX: v => String(v).toUpperCase(),
56
+ formatValue: (v, s, key) => `${s.type}:${key}:${String(v)}`,
57
+ });
58
+ expect(model?.headers[0]).toBe('Mês');
59
+ expect(model?.rows[0]).toMatchObject({
60
+ header: 'JAN',
61
+ cells: ['bar:leads:1200'],
62
+ });
63
+ });
64
+
65
+ it('returns null for empty data, no data series, or more rows than maxRows', () => {
66
+ expect(buildDataTable([], 'mes', [bar('leads')])).toBeNull();
67
+ expect(
68
+ buildDataTable(data, 'mes', [band({lower: 'leads', upper: 'custo'})]),
69
+ ).toBeNull();
70
+ expect(
71
+ buildDataTable(data, 'mes', [bar('leads')], {maxRows: 1}),
72
+ ).toBeNull();
73
+ });
74
+ });
75
+
76
+ describe('fallbackChartLabel', () => {
77
+ it('joins the data series labels, skipping utility marks', () => {
78
+ expect(
79
+ fallbackChartLabel([
80
+ bar('leads', {label: 'Leads'}),
81
+ line('custo'),
82
+ band({lower: 'a', upper: 'b'}),
83
+ ]),
84
+ ).toBe('Leads, custo');
85
+ });
86
+ });
@@ -0,0 +1,124 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file dataTable.ts
5
+ * @output Pure builder for the chart's text alternative (WCAG 1.1.1): turns
6
+ * `data` + `xKey` + `series` into a header row and one row per x value.
7
+ * @position Used by Chart to render the visually hidden `<table>` that sits
8
+ * next to the `role="img"` SVG. Mirrors legend.ts / tooltip.ts: data shaping
9
+ * lives here, presentation lives in Chart.tsx.
10
+ *
11
+ * Utility marks (band, errorBar, referenceLine) are annotations, not data the
12
+ * reader compares, so they get no column — same rule as the legend and the
13
+ * tooltip. A mark that reads several keys (candlestick: open/high/low/close)
14
+ * gets one column per key.
15
+ *
16
+ * SYNC: When modified, update /packages/charts/src/Chart.doc.mjs
17
+ */
18
+
19
+ import {isUtilityMarkType, type SeriesDef} from './types';
20
+
21
+ /** Options for the hidden data table rendered by `<Chart>`. */
22
+ export interface ChartDataTableOptions {
23
+ /** Header of the first column (the x values). Default: the chart's `xKey`. */
24
+ xLabel?: string;
25
+ /** Formats an x value for its row header cell. Default: `String(value)`. */
26
+ formatX?: (value: unknown) => string;
27
+ /**
28
+ * Formats one value cell. Receives the raw value, the series and the data key
29
+ * being read. Default: locale-formatted numbers, `String()` otherwise and an
30
+ * empty cell for missing values.
31
+ */
32
+ formatValue?: (value: unknown, series: SeriesDef, dataKey: string) => string;
33
+ /**
34
+ * Largest `data.length` that still renders a table. Above it the table is
35
+ * omitted (streaming/WebGL charts with thousands of points) and the chart
36
+ * relies on its accessible name and `description`. Default: `1000`.
37
+ */
38
+ maxRows?: number;
39
+ }
40
+
41
+ export interface ChartDataTableModel {
42
+ headers: string[];
43
+ rows: {key: string; header: string; cells: string[]}[];
44
+ }
45
+
46
+ /** Default row cap — see `ChartDataTableOptions.maxRows`. */
47
+ export const DATA_TABLE_MAX_ROWS = 1000;
48
+
49
+ function defaultFormatValue(value: unknown): string {
50
+ if (value == null) {
51
+ return '';
52
+ }
53
+ if (typeof value === 'number') {
54
+ return Number.isFinite(value) ? value.toLocaleString() : '';
55
+ }
56
+ if (value instanceof Date) {
57
+ return value.toLocaleDateString();
58
+ }
59
+ return String(value);
60
+ }
61
+
62
+ function defaultFormatX(value: unknown): string {
63
+ if (value instanceof Date) {
64
+ return value.toLocaleDateString();
65
+ }
66
+ return value == null ? '' : String(value);
67
+ }
68
+
69
+ /**
70
+ * Build the table model, or `null` when there is nothing to tabulate (no data,
71
+ * no data series) or `data` exceeds `maxRows`.
72
+ */
73
+ export function buildDataTable(
74
+ data: readonly Record<string, unknown>[],
75
+ xKey: string,
76
+ series: readonly SeriesDef[],
77
+ options: ChartDataTableOptions = {},
78
+ ): ChartDataTableModel | null {
79
+ const maxRows = options.maxRows ?? DATA_TABLE_MAX_ROWS;
80
+ if (data.length === 0 || data.length > maxRows) {
81
+ return null;
82
+ }
83
+
84
+ const columns: {series: SeriesDef; dataKey: string; header: string}[] = [];
85
+ for (const s of series) {
86
+ if (isUtilityMarkType(s.type)) {
87
+ continue;
88
+ }
89
+ const label = s.label ?? s.key;
90
+ for (const dataKey of s.dataKeys) {
91
+ columns.push({
92
+ series: s,
93
+ dataKey,
94
+ header: s.dataKeys.length > 1 ? `${label} (${dataKey})` : label,
95
+ });
96
+ }
97
+ }
98
+ if (columns.length === 0) {
99
+ return null;
100
+ }
101
+
102
+ const formatX = options.formatX ?? defaultFormatX;
103
+ const formatValue = options.formatValue ?? defaultFormatValue;
104
+
105
+ return {
106
+ headers: [options.xLabel ?? xKey, ...columns.map(c => c.header)],
107
+ rows: data.map((d, i) => ({
108
+ key: String(i),
109
+ header: formatX(d[xKey]),
110
+ cells: columns.map(c => formatValue(d[c.dataKey], c.series, c.dataKey)),
111
+ })),
112
+ };
113
+ }
114
+
115
+ /**
116
+ * Accessible name fallback when the chart has neither `aria-label` nor
117
+ * `title`: the data series labels, so the name is never empty.
118
+ */
119
+ export function fallbackChartLabel(series: readonly SeriesDef[]): string {
120
+ return series
121
+ .filter(s => !isUtilityMarkType(s.type))
122
+ .map(s => s.label ?? s.key)
123
+ .join(', ');
124
+ }