@automattic/charts 4.6.0 → 4.8.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.
Files changed (91) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/TOKENS.md +15 -10
  3. package/dist/index.cjs +427 -211
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.css +40 -26
  6. package/dist/index.d.cts +69 -29
  7. package/dist/index.d.ts +69 -29
  8. package/dist/index.js +427 -213
  9. package/dist/index.js.map +1 -1
  10. package/package.json +1 -1
  11. package/src/charts/area-chart/area-chart.tsx +2 -2
  12. package/src/charts/area-chart/test/area-chart.test.tsx +1 -1
  13. package/src/charts/area-chart/test/tooltip-resolution-branches.test.tsx +1 -1
  14. package/src/charts/bar-chart/bar-chart.module.scss +7 -0
  15. package/src/charts/bar-chart/bar-chart.tsx +20 -14
  16. package/src/charts/bar-chart/private/comparison-bars.tsx +1 -0
  17. package/src/charts/bar-chart/test/bar-chart.test.tsx +25 -0
  18. package/src/charts/conversion-funnel-chart/conversion-funnel-chart.module.scss +0 -10
  19. package/src/charts/conversion-funnel-chart/conversion-funnel-chart.tsx +5 -3
  20. package/src/charts/conversion-funnel-chart/test/conversion-funnel-chart.test.tsx +20 -1
  21. package/src/charts/conversion-funnel-chart/types.ts +3 -0
  22. package/src/charts/heatmap-chart/heatmap-chart.module.scss +16 -7
  23. package/src/charts/heatmap-chart/heatmap-chart.tsx +80 -53
  24. package/src/charts/heatmap-chart/private/heatmap-context.ts +2 -2
  25. package/src/charts/heatmap-chart/private/heatmap-legend.tsx +2 -2
  26. package/src/charts/heatmap-chart/private/heatmap-scale.ts +74 -0
  27. package/src/charts/heatmap-chart/private/index.ts +2 -1
  28. package/src/charts/heatmap-chart/private/use-heatmap-colors.ts +24 -6
  29. package/src/charts/heatmap-chart/test/heatmap-chart.test.tsx +221 -25
  30. package/src/charts/heatmap-chart/test/heatmap-scale.test.ts +78 -0
  31. package/src/charts/heatmap-chart/test/use-heatmap-colors.test.ts +18 -6
  32. package/src/charts/heatmap-chart/types.ts +6 -9
  33. package/src/charts/line-chart/crosshair-style-types.fixture.ts +23 -0
  34. package/src/charts/line-chart/line-chart.module.scss +0 -5
  35. package/src/charts/line-chart/line-chart.tsx +10 -42
  36. package/src/charts/line-chart/test/line-chart.test.tsx +19 -47
  37. package/src/charts/pie-chart/pie-chart.module.scss +9 -0
  38. package/src/charts/pie-chart/pie-chart.tsx +26 -80
  39. package/src/charts/pie-chart/test/pie-chart.test.tsx +21 -8
  40. package/src/charts/pie-semi-circle-chart/pie-semi-circle-chart.tsx +4 -4
  41. package/src/charts/pie-semi-circle-chart/test/pie-semi-circle-chart.test.tsx +1 -1
  42. package/src/charts/private/chart-composition/chart-html.tsx +1 -1
  43. package/src/charts/private/chart-composition/chart-svg.tsx +1 -1
  44. package/src/charts/private/label-text-color.ts +116 -0
  45. package/src/charts/private/radial-wipe-animation/radial-wipe-animation.tsx +2 -0
  46. package/src/charts/private/svg-empty-state/svg-empty-state.tsx +1 -1
  47. package/src/charts/private/test/label-text-color.test.ts +189 -0
  48. package/src/charts/private/with-responsive/test/with-responsive.test.tsx +1 -0
  49. package/src/charts/private/with-responsive/with-responsive.tsx +2 -5
  50. package/src/components/tooltip/base-tooltip.tsx +31 -30
  51. package/src/components/tooltip/index.ts +3 -1
  52. package/src/components/tooltip/private/bounded-tooltip.tsx +32 -13
  53. package/src/components/tooltip/private/label-value-content.tsx +8 -0
  54. package/src/components/tooltip/private/tooltip-theme.tsx +37 -0
  55. package/src/components/tooltip/private/xy-chart-tooltip-overlay.tsx +336 -0
  56. package/src/components/tooltip/test/bounded-tooltip.test.tsx +82 -1
  57. package/src/components/tooltip/test/tool-tip.test.tsx +10 -3
  58. package/src/components/tooltip/test/tooltip-box.test.tsx +53 -0
  59. package/src/components/tooltip/test/tooltip-theme.test.tsx +61 -0
  60. package/src/components/tooltip/test/xy-chart-tooltip-overlay.test.tsx +445 -0
  61. package/src/components/tooltip/test/xy-chart-tooltip.test.tsx +286 -356
  62. package/src/components/tooltip/tooltip-box.module.scss +21 -0
  63. package/src/components/tooltip/tooltip-box.tsx +43 -0
  64. package/src/components/tooltip/types.ts +7 -1
  65. package/src/components/tooltip/xy-chart-tooltip.tsx +411 -301
  66. package/src/components/trend-indicator/trend-indicator.tsx +1 -0
  67. package/src/hooks/index.ts +1 -0
  68. package/src/hooks/test/use-chart-margin.test.tsx +8 -4
  69. package/src/hooks/test/use-xychart-theme.test.tsx +3 -3
  70. package/src/hooks/use-chart-margin.tsx +21 -18
  71. package/src/hooks/use-isomorphic-layout-effect.ts +5 -0
  72. package/src/hooks/use-xychart-theme.ts +4 -12
  73. package/src/index.ts +8 -3
  74. package/src/providers/chart-context/global-charts-provider.tsx +5 -14
  75. package/src/providers/chart-context/hooks/use-default-hidden-series.ts +3 -5
  76. package/src/providers/chart-context/private/catalog-pointers.ts +1 -0
  77. package/src/providers/chart-context/private/perceptual-color.ts +45 -4
  78. package/src/providers/chart-context/private/resolve-opaque-hex.ts +16 -0
  79. package/src/providers/chart-context/test/perceptual-color.test.ts +31 -0
  80. package/src/providers/chart-context/test/use-default-hidden-series.test.tsx +1 -1
  81. package/src/styles/chart-scope-class.ts +5 -0
  82. package/src/styles/chart-scope.scss +10 -6
  83. package/src/styles/test/chart-scope.test.ts +3 -3
  84. package/src/test-utils/zoned-parsing-suite.ts +0 -10
  85. package/src/utils/color-utils.ts +2 -1
  86. package/src/utils/test/date-formatting.test.ts +0 -10
  87. package/src/visx/types.ts +1 -1
  88. package/src/charts/line-chart/test/crosshair-style-types.test.ts +0 -31
  89. package/src/components/tooltip/accessible-tooltip.tsx +0 -433
  90. package/src/components/tooltip/base-tooltip.module.scss +0 -20
  91. package/src/components/tooltip/test/accessible-tooltip.test.tsx +0 -331
@@ -1,405 +1,335 @@
1
- import { render, screen, waitFor } from '@testing-library/react';
2
- import { BarSeries, buildChartTheme, LineSeries, TooltipContext, XYChart } from '@visx/xychart';
3
- import { useContext, useEffect } from 'react';
4
- import { XyChartTooltip } from '../xy-chart-tooltip';
5
- import type { XyChartTooltipProps } from '../../../visx/types';
6
- import type { EventHandlerParams, XYChartTheme } from '@visx/xychart';
7
-
8
- type Datum = { x: number; y: number };
9
-
10
- const SERIES_A: Datum[] = [
11
- { x: 0, y: 0 },
12
- { x: 5, y: 50 },
13
- { x: 10, y: 100 },
14
- ];
15
- const SERIES_B: Datum[] = [
16
- { x: 0, y: 100 },
17
- { x: 5, y: 25 },
18
- { x: 10, y: 0 },
19
- ];
20
-
21
- const xAccessor = ( d: Datum ) => d.x;
22
- const yAccessor = ( d: Datum ) => d.y;
23
-
24
- type BandDatum = { x: string; y: number };
25
- const BAND_DATA: BandDatum[] = [
26
- { x: 'a', y: 50 },
27
- { x: 'b', y: 80 },
28
- ];
29
- const bandXAccessor = ( d: BandDatum ) => d.x;
30
- const bandYAccessor = ( d: BandDatum ) => d.y;
31
- const renderBarTooltip = () => <span>bar</span>;
32
- const BAND_PARAMS = [
33
- { key: 'bars', index: 0, datum: BAND_DATA[ 0 ], svgPoint: { x: 20, y: 90 } },
34
- ] as unknown as EventHandlerParams< Datum >[];
35
-
36
- // The pointer sits on A's datum, 25px above B's, so A is the nearest datum.
37
- const BOTH_SERIES: EventHandlerParams< Datum >[] = [
38
- {
39
- key: 'A',
40
- index: 1,
41
- datum: SERIES_A[ 1 ],
42
- svgPoint: { x: 100, y: 50 },
43
- distanceX: 0,
44
- distanceY: 0,
45
- },
46
- {
47
- key: 'B',
48
- index: 1,
49
- datum: SERIES_B[ 1 ],
50
- svgPoint: { x: 100, y: 50 },
51
- distanceX: 0,
52
- distanceY: 25,
53
- },
54
- ];
55
-
56
- // Opens the tooltip the way a pointer event would, once the series have registered.
57
- const OpenTooltip = ( { params }: { params: EventHandlerParams< Datum >[] } ) => {
58
- const tooltipContext = useContext( TooltipContext );
59
- useEffect( () => {
60
- params.forEach( p => tooltipContext?.showTooltip( p ) );
61
- // The context object changes identity on every tooltip update; re-running would loop.
62
- // eslint-disable-next-line react-hooks/exhaustive-deps
63
- }, [] );
64
- return null;
65
- };
1
+ import { act, render, screen } from '@testing-library/react';
2
+ import userEvent from '@testing-library/user-event';
3
+ import { useCallback, useRef, useState } from 'react';
4
+ import { LineChartUnresponsive } from '../../../charts/line-chart/line-chart';
5
+ import { GlobalChartsProvider } from '../../../providers';
6
+ import { ChartScopeContext } from '../../../providers/chart-scope';
7
+ import { AccessibleTooltip, XYChartTooltip, useKeyboardNavigation } from '../xy-chart-tooltip';
8
+ import type { ReactNode } from 'react';
9
+
10
+ // A real chart is the harness rather than the subject: the crosshairs render only once visx has a data context and an open tooltip. The unresponsive export is what lets the test own the scope element — `withResponsive` otherwise provides its own wrapper as the scope.
11
+ const renderChart = ( scope?: HTMLElement, tooltipPlacement?: 'auto' | 'below-axis' ) => {
12
+ const chart = (
13
+ <LineChartUnresponsive
14
+ width={ 500 }
15
+ height={ 300 }
16
+ data={ [
17
+ {
18
+ label: 'Series A',
19
+ data: [
20
+ { date: new Date( '2024-01-01' ), value: 10, label: 'Jan 1' },
21
+ { date: new Date( '2024-01-02' ), value: 20, label: 'Jan 2' },
22
+ ],
23
+ options: {},
24
+ },
25
+ ] }
26
+ withTooltips
27
+ tooltipPlacement={ tooltipPlacement }
28
+ withTooltipCrosshairs={ { showVertical: true } }
29
+ withGradientFill={ false }
30
+ />
31
+ );
66
32
 
67
- const renderTooltip: XyChartTooltipProps< Datum >[ 'renderTooltip' ] = ( { tooltipData } ) => (
68
- <span>{ `nearest:${ tooltipData?.nearestDatum?.key ?? '' }` }</span>
69
- );
70
-
71
- const NO_MARGIN = { top: 0, right: 0, bottom: 0, left: 0 };
72
-
73
- // 200x100 chart; with no margin x maps 0..10 to 0..200px and y maps 0..100 to 100..0px.
74
- const renderChart = (
75
- tooltipProps: Partial< XyChartTooltipProps< Datum > > = {},
76
- params: EventHandlerParams< Datum >[] = [
77
- { key: 'A', index: 1, datum: SERIES_A[ 1 ], svgPoint: { x: 123, y: 45 } },
78
- ],
79
- margin = NO_MARGIN,
80
- theme?: XYChartTheme
81
- ) =>
82
- render(
83
- <div data-testid="wrapper" style={ { position: 'relative' } }>
84
- <XYChart
85
- width={ 200 }
86
- height={ 100 }
87
- margin={ margin }
88
- theme={ theme }
89
- xScale={ { type: 'linear', domain: [ 0, 10 ] } }
90
- yScale={ { type: 'linear', domain: [ 0, 100 ] } }
91
- >
92
- <LineSeries dataKey="A" data={ SERIES_A } xAccessor={ xAccessor } yAccessor={ yAccessor } />
93
- <LineSeries dataKey="B" data={ SERIES_B } xAccessor={ xAccessor } yAccessor={ yAccessor } />
94
- <XyChartTooltip
95
- renderTooltip={ renderTooltip }
96
- data-testid="tooltip-box"
97
- { ...tooltipProps }
98
- />
99
- <OpenTooltip params={ params } />
100
- </XYChart>
101
- </div>
33
+ const scoped: ReactNode = scope ? (
34
+ <ChartScopeContext.Provider value={ scope }>{ chart }</ChartScopeContext.Provider>
35
+ ) : (
36
+ chart
102
37
  );
103
38
 
104
- describe( 'XyChartTooltip', () => {
105
- test.each( [
106
- [ 'CanvasText', '0 1px 2px #22222255' ],
107
- [ '#123456', '0 1px 2px #12345655' ],
108
- ] )( 'renders a valid shadow for htmlLabel color %s', async ( color, boxShadow ) => {
109
- const theme = buildChartTheme( {
110
- backgroundColor: '#ffffff',
111
- colors: [ '#123456' ],
112
- tickLength: 4,
113
- gridColor: '#dddddd',
114
- gridColorDark: '#222222',
115
- htmlLabel: { color },
116
- } );
117
- renderChart( {}, undefined, undefined, theme );
118
-
119
- await expect( screen.findByTestId( 'tooltip-box' ) ).resolves.toHaveStyle( { boxShadow } );
120
- } );
39
+ return render( <GlobalChartsProvider>{ scoped }</GlobalChartsProvider> );
40
+ };
121
41
 
122
- test( 'renders the tooltip box inside the chart wrapper, not in a body-level portal', async () => {
123
- const { container } = renderChart();
42
+ const openTooltip = async () => {
43
+ const user = userEvent.setup();
124
44
 
125
- const box = await screen.findByTestId( 'tooltip-box' );
45
+ screen.getByRole( 'grid', { name: /line chart/i } ).focus();
46
+ await user.keyboard( '{ArrowRight}' );
126
47
 
127
- expect( box ).toHaveTextContent( 'nearest:A' );
128
- expect( screen.getByTestId( 'wrapper' ) ).toContainElement( box );
129
- // A body-level portal would sit outside the render root.
130
- expect( container ).toContainElement( box );
48
+ return screen.getByTestId( 'xy-chart-tooltip-crosshair-vertical' );
49
+ };
50
+
51
+ describe( 'XYChartTooltip', () => {
52
+ it( 'keeps AccessibleTooltip as an alias', () => {
53
+ expect( AccessibleTooltip ).toBe( XYChartTooltip );
131
54
  } );
132
55
 
133
- test( 'places the box at the pointer position when snapping is off', async () => {
134
- renderChart();
56
+ // The stroke is read at the scope element, not inherited through the DOM; see TOKENS.md#the-svg-bridge.
57
+ it( 'reads the grid role from the scope element', async () => {
58
+ const scope = document.createElement( 'div' );
59
+ scope.style.setProperty( '--a8c-charts-color-grid', 'rgb(1, 2, 3)' );
60
+ document.body.appendChild( scope );
135
61
 
136
- // TooltipWithBounds moves the box through a transform from (0, 0), after its 10px offsets.
137
- await expect( screen.findByTestId( 'tooltip-box' ) ).resolves.toHaveStyle( {
138
- transform: 'translate(133px, 55px)',
139
- } );
140
- } );
62
+ renderChart( scope );
63
+
64
+ await expect( openTooltip() ).resolves.toHaveAttribute( 'stroke', 'rgb(1, 2, 3)' );
141
65
 
142
- test( 'pins beside placement to the explicit SVG top anchor', async () => {
143
- renderChart( { tooltipPlacement: 'beside', tooltipAnchorTop: 20, snapTooltipToDatumY: true } );
144
- await expect( screen.findByTestId( 'tooltip-box' ) ).resolves.toHaveStyle( {
145
- transform: 'translate(133px, 20px)',
146
- } );
66
+ document.body.removeChild( scope );
147
67
  } );
148
68
 
149
- test( 'snaps the box to the nearest datum', async () => {
150
- renderChart( { snapTooltipToDatumX: true, snapTooltipToDatumY: true } );
69
+ it( 'keeps the existing focus scrolling for automatic tooltips', async () => {
70
+ const focus = jest.spyOn( HTMLElement.prototype, 'focus' );
71
+ try {
72
+ renderChart();
73
+ await openTooltip();
151
74
 
152
- // Datum (5, 50) sits at (100px, 50px); the default 10px offsets apply after snapping.
153
- await waitFor( () =>
154
- expect( screen.getByTestId( 'tooltip-box' ) ).toHaveStyle( {
155
- transform: 'translate(110px, 60px)',
156
- } )
157
- );
75
+ expect( screen.getByTestId( 'chart-tooltip-0' ) ).toHaveFocus();
76
+ expect( focus ).toHaveBeenLastCalledWith();
77
+ } finally {
78
+ focus.mockRestore();
79
+ }
158
80
  } );
159
81
 
160
- test( 'anchors below the x-axis label band without moving datum glyphs or crosshairs', async () => {
161
- const originalRect = Element.prototype.getBoundingClientRect;
162
- const rectSpy = jest
163
- .spyOn( Element.prototype, 'getBoundingClientRect' )
164
- .mockImplementation( function ( this: Element ) {
165
- const rect = originalRect.call( this );
166
- return this.classList.contains( 'visx-tooltip' )
167
- ? { ...rect, width: 80, height: 30, right: rect.left + 80, bottom: rect.top + 30 }
168
- : rect;
169
- } );
82
+ it( 'focuses below-axis keyboard tooltips without scrolling their ancestors', async () => {
83
+ const focus = jest.spyOn( HTMLElement.prototype, 'focus' );
84
+ try {
85
+ renderChart( undefined, 'below-axis' );
86
+ await openTooltip();
170
87
 
88
+ expect( screen.getByTestId( 'chart-tooltip-0' ) ).toHaveFocus();
89
+ expect( focus ).toHaveBeenCalledWith( { preventScroll: true } );
90
+ } finally {
91
+ focus.mockRestore();
92
+ }
93
+ } );
94
+
95
+ it.each( [
96
+ [ 'Tab', '{Tab}' ],
97
+ [ 'Escape', '{Escape}' ],
98
+ ] )( 'requests scroll suppression when returning focus after %s', async ( _name, keys ) => {
99
+ const user = userEvent.setup();
100
+ renderChart( undefined, 'below-axis' );
101
+ await openTooltip();
102
+ const focus = jest.spyOn( screen.getByRole( 'grid' ), 'focus' );
171
103
  try {
172
- renderChart(
173
- {
174
- tooltipPlacement: 'below-axis',
175
- snapTooltipToDatumY: true,
176
- showDatumGlyph: true,
177
- showVerticalCrosshair: true,
178
- showHorizontalCrosshair: true,
179
- },
180
- undefined,
181
- { top: 10, right: 20, bottom: 30, left: 40 }
182
- );
183
-
184
- const box = await screen.findByTestId( 'tooltip-box' );
185
- expect( box ).toHaveStyle( { transform: 'translate(70px, 106px)' } );
186
- expect( screen.getByTestId( 'wrapper' ) ).toContainElement( box );
187
- expect( screen.getByTestId( 'tooltip-axis-pointer' ) ).toHaveStyle( {
188
- left: '34px',
189
- top: '-6px',
190
- } );
191
- expect( screen.getByTestId( 'xy-chart-tooltip-glyph-group-A' ) ).toHaveAttribute(
192
- 'transform',
193
- 'translate(110, 40)'
194
- );
195
- expect( screen.getByTestId( 'xy-chart-tooltip-crosshair-vertical' ) ).toHaveAttribute(
196
- 'y2',
197
- '70'
198
- );
199
- expect( screen.getByTestId( 'xy-chart-tooltip-crosshair-horizontal' ) ).toHaveAttribute(
200
- 'y1',
201
- '40'
202
- );
104
+ await user.keyboard( keys );
105
+ expect( focus ).toHaveBeenCalledWith( { preventScroll: true } );
203
106
  } finally {
204
- rectSpy.mockRestore();
107
+ focus.mockRestore();
205
108
  }
206
109
  } );
207
110
 
208
- test( 'draws one glyph per series in the SVG at the datum position', async () => {
209
- renderChart( { showSeriesGlyphs: true }, BOTH_SERIES );
210
-
211
- const glyphA = await screen.findByTestId( 'xy-chart-tooltip-glyph-A' );
212
- const glyphB = await screen.findByTestId( 'xy-chart-tooltip-glyph-B' );
213
-
214
- // The group is placed at the datum; the glyph itself draws at the origin.
215
- expect( screen.getByTestId( 'xy-chart-tooltip-glyph-group-A' ) ).toHaveAttribute(
216
- 'transform',
217
- 'translate(100, 50)'
218
- );
219
- expect( screen.getByTestId( 'xy-chart-tooltip-glyph-group-B' ) ).toHaveAttribute(
220
- 'transform',
221
- 'translate(100, 75)'
222
- );
223
- expect( glyphA ).toHaveAttribute( 'cx', '0' );
224
- expect( glyphA ).toHaveAttribute( 'cy', '0' );
225
- expect( glyphB ).toHaveAttribute( 'cx', '0' );
226
- expect( glyphB ).toHaveAttribute( 'cy', '0' );
227
- // Drawn into the chart SVG, not portaled out as HTML.
228
- expect( glyphA ).toBeInstanceOf( SVGElement );
111
+ it.each( [
112
+ [ 'Tab', '{Tab}' ],
113
+ [ 'Escape', '{Escape}' ],
114
+ ] )( 'keeps default focus scrolling when returning focus after %s', async ( _name, keys ) => {
115
+ const user = userEvent.setup();
116
+ renderChart();
117
+ await openTooltip();
118
+ const focus = jest.spyOn( screen.getByRole( 'grid' ), 'focus' );
119
+ try {
120
+ await user.keyboard( keys );
121
+ expect( focus ).toHaveBeenCalledWith();
122
+ } finally {
123
+ focus.mockRestore();
124
+ }
229
125
  } );
230
126
 
231
- test( 'hands the glyph renderer the origin, like visx, and marks the nearest datum', async () => {
232
- const renderGlyph = jest.fn( () => null );
233
- renderChart( { showSeriesGlyphs: true, renderGlyph }, BOTH_SERIES );
234
-
235
- await waitFor( () => expect( renderGlyph ).toHaveBeenCalledTimes( 2 ) );
236
-
237
- const calls = renderGlyph.mock.calls as unknown as Array<
238
- [ { key: string; x: number; y: number; isNearestDatum: boolean; datum: Datum } ]
239
- >;
240
- const byKey = Object.fromEntries( calls.map( ( [ p ] ) => [ p.key, p ] ) );
241
- // A renderer written against visx's Tooltip ignores x and y, so both stay 0.
242
- expect( byKey.A ).toMatchObject( { x: 0, y: 0, datum: SERIES_A[ 1 ] } );
243
- expect( byKey.B ).toMatchObject( { x: 0, y: 0, datum: SERIES_B[ 1 ] } );
244
- expect( byKey.A.isNearestDatum ).toBe( true );
245
- expect( byKey.B.isNearestDatum ).toBe( false );
127
+ it( 'falls back to the catalog default when the role is unset', async () => {
128
+ renderChart();
129
+
130
+ await expect( openTooltip() ).resolves.toHaveAttribute( 'stroke', '#dbdbdb' );
246
131
  } );
132
+ } );
247
133
 
248
- test( 'centres a band-scale datum in its band', async () => {
249
- render(
250
- <div style={ { position: 'relative' } }>
251
- <XYChart
252
- width={ 200 }
253
- height={ 100 }
254
- margin={ NO_MARGIN }
255
- xScale={ { type: 'band', domain: [ 'a', 'b' ], paddingInner: 0, paddingOuter: 0 } }
256
- yScale={ { type: 'linear', domain: [ 0, 100 ] } }
257
- >
258
- <BarSeries
259
- dataKey="bars"
260
- data={ BAND_DATA }
261
- xAccessor={ bandXAccessor }
262
- yAccessor={ bandYAccessor }
263
- />
264
- <XyChartTooltip
265
- renderTooltip={ renderBarTooltip }
266
- data-testid="tooltip-box"
267
- snapTooltipToDatumX
268
- snapTooltipToDatumY
269
- showDatumGlyph
270
- />
271
- <OpenTooltip params={ BAND_PARAMS } />
272
- </XYChart>
134
+ // Mirrors the charts' markup: the focusable grid wraps the element `chartRef` points at.
135
+ const NavigationHarness = ( {
136
+ totalPoints,
137
+ trackBlur = false,
138
+ }: {
139
+ totalPoints: number;
140
+ trackBlur?: boolean;
141
+ } ) => {
142
+ const [ selectedIndex, setSelectedIndex ] = useState< number | undefined >();
143
+ const [ isNavigating, setIsNavigating ] = useState( false );
144
+ const chartRef = useRef< HTMLDivElement >( null );
145
+ const { onChartKeyDown, onChartBlur, onChartPointerMove } = useKeyboardNavigation( {
146
+ selectedIndex,
147
+ setSelectedIndex,
148
+ isNavigating,
149
+ setIsNavigating,
150
+ chartRef,
151
+ totalPoints,
152
+ } );
153
+ const moveToFour = useCallback( () => onChartPointerMove( 4 ), [ onChartPointerMove ] );
154
+ const moveToOne = useCallback( () => onChartPointerMove( 1 ), [ onChartPointerMove ] );
155
+
156
+ return (
157
+ <>
158
+ <div
159
+ role="grid"
160
+ aria-label="Harness"
161
+ tabIndex={ 0 }
162
+ onKeyDown={ onChartKeyDown }
163
+ onBlur={ trackBlur ? onChartBlur : undefined }
164
+ >
165
+ <div ref={ chartRef } data-testid="selected-index">
166
+ { selectedIndex ?? 'none' }
167
+ <button type="button">Inside</button>
168
+ </div>
169
+ <div data-testid="point-4" onPointerMove={ moveToFour } />
170
+ <div data-testid="point-1" onPointerMove={ moveToOne } />
273
171
  </div>
274
- );
275
-
276
- // Band 'a' spans 0..100px; the datum sits at its centre, 50px, not its start.
277
- await waitFor( () =>
278
- expect( screen.getByTestId( 'xy-chart-tooltip-glyph-group-bars' ) ).toHaveAttribute(
279
- 'transform',
280
- 'translate(50, 50)'
281
- )
282
- );
283
- expect( screen.getByTestId( 'tooltip-box' ) ).toHaveStyle( {
284
- transform: 'translate(60px, 60px)',
285
- } );
172
+ <button type="button">Outside</button>
173
+ </>
174
+ );
175
+ };
176
+
177
+ describe( 'useKeyboardNavigation', () => {
178
+ const navigate = async ( presses: number ) => {
179
+ const user = userEvent.setup();
180
+ const view = render( <NavigationHarness totalPoints={ 6 } /> );
181
+
182
+ screen.getByRole( 'grid', { name: 'Harness' } ).focus();
183
+ for ( let i = 0; i < presses; i++ ) {
184
+ await user.keyboard( '{ArrowRight}' );
185
+ }
186
+ expect( screen.getByTestId( 'selected-index' ) ).toHaveTextContent( String( presses - 1 ) );
187
+
188
+ return { user, view };
189
+ };
190
+
191
+ it( 'moves the selection to the last point when the count shrinks while the grid has focus', async () => {
192
+ const { view } = await navigate( 6 );
193
+
194
+ view.rerender( <NavigationHarness totalPoints={ 3 } /> );
195
+
196
+ expect( screen.getByTestId( 'selected-index' ) ).toHaveTextContent( '2' );
197
+ expect( screen.getByRole( 'grid', { name: 'Harness' } ) ).toHaveFocus();
286
198
  } );
287
199
 
288
- test( 'draws the crosshairs across the plot area, inside the margins, at the snapped position', async () => {
289
- renderChart(
290
- {
291
- snapTooltipToDatumX: true,
292
- snapTooltipToDatumY: true,
293
- showVerticalCrosshair: true,
294
- showHorizontalCrosshair: true,
295
- },
296
- undefined,
297
- { top: 10, right: 20, bottom: 30, left: 40 }
298
- );
299
-
300
- const vertical = await screen.findByTestId( 'xy-chart-tooltip-crosshair-vertical' );
301
- const horizontal = await screen.findByTestId( 'xy-chart-tooltip-crosshair-horizontal' );
302
-
303
- // Plot area is 140x60 at (40, 10); datum (5, 50) sits at its centre, (110, 40).
304
- expect( vertical ).toHaveAttribute( 'x1', '110' );
305
- expect( vertical ).toHaveAttribute( 'y1', '10' );
306
- expect( vertical ).toHaveAttribute( 'y2', '70' );
307
- expect( horizontal ).toHaveAttribute( 'y1', '40' );
308
- expect( horizontal ).toHaveAttribute( 'x1', '40' );
309
- expect( horizontal ).toHaveAttribute( 'x2', '180' );
200
+ // In range rather than past the end: the effect reconciles on any count change, not only an overflow.
201
+ it( 'clears an in-range selection when the count changes after focus has left the chart', async () => {
202
+ const { view } = await navigate( 2 );
203
+
204
+ screen.getByRole( 'button', { name: 'Outside' } ).focus();
205
+ view.rerender( <NavigationHarness totalPoints={ 3 } /> );
206
+
207
+ expect( screen.getByTestId( 'selected-index' ) ).toHaveTextContent( 'none' );
310
208
  } );
311
209
 
312
- test( 'applies crosshair paint without allowing geometry overrides', async () => {
313
- const consumerStyle = {
314
- stroke: 'purple',
315
- strokeWidth: 8,
316
- className: 'custom-crosshair',
317
- x1: 999,
318
- transform: 'translate(100 0)',
319
- style: { strokeOpacity: 0.25, transform: 'translateX(100px)' },
320
- };
321
- renderChart( {
322
- snapTooltipToDatumX: true,
323
- snapTooltipToDatumY: true,
324
- showVerticalCrosshair: true,
325
- showHorizontalCrosshair: true,
326
- verticalCrosshairStyle: consumerStyle,
327
- horizontalCrosshairStyle: consumerStyle,
328
- } );
329
-
330
- for ( const direction of [ 'vertical', 'horizontal' ] ) {
331
- const guide = await screen.findByTestId( `xy-chart-tooltip-crosshair-${ direction }` );
332
- expect( guide ).toHaveAttribute( 'stroke', 'purple' );
333
- expect( guide ).toHaveAttribute( 'stroke-width', '8' );
334
- expect( guide ).toHaveClass( 'custom-crosshair' );
335
- expect( guide ).toHaveStyle( { 'stroke-opacity': '0.25', transform: 'none' } );
336
- expect( guide ).not.toHaveAttribute( 'transform' );
337
- expect( guide ).toHaveAttribute( 'x1', direction === 'vertical' ? '100' : '0' );
338
- expect( guide ).toHaveAttribute( 'x2', direction === 'vertical' ? '100' : '200' );
339
- expect( guide ).toHaveAttribute( 'y1', direction === 'vertical' ? '0' : '50' );
340
- expect( guide ).toHaveAttribute( 'y2', direction === 'vertical' ? '100' : '50' );
341
- }
210
+ it( 'returns focus to the grid on Escape when there are no points', async () => {
211
+ const user = userEvent.setup();
212
+ render( <NavigationHarness totalPoints={ 0 } /> );
213
+
214
+ screen.getByRole( 'button', { name: 'Inside' } ).focus();
215
+ await user.keyboard( '{Escape}' );
216
+
217
+ expect( screen.getByRole( 'grid', { name: 'Harness' } ) ).toHaveFocus();
218
+ } );
219
+
220
+ it( 'returns focus to the grid when the count drops to zero while focus is in the chart', async () => {
221
+ const { view } = await navigate( 2 );
222
+
223
+ screen.getByRole( 'button', { name: 'Inside' } ).focus();
224
+ view.rerender( <NavigationHarness totalPoints={ 0 } /> );
225
+
226
+ expect( screen.getByTestId( 'selected-index' ) ).toHaveTextContent( 'none' );
227
+ expect( screen.getByRole( 'grid', { name: 'Harness' } ) ).toHaveFocus();
342
228
  } );
343
229
 
344
- test( 'stacks the box above the chart overlays, with zIndex as the override', async () => {
345
- const { unmount } = renderChart();
346
- await expect( screen.findByTestId( 'tooltip-box' ) ).resolves.toHaveStyle( { zIndex: '3' } );
347
- unmount();
230
+ it( 'hands a keyboard selection to the pointer and continues from where the pointer is', async () => {
231
+ const { user } = await navigate( 2 );
232
+
233
+ screen.getByRole( 'button', { name: 'Inside' } ).focus();
234
+ await user.hover( screen.getByTestId( 'point-4' ) );
235
+
236
+ expect( screen.getByTestId( 'selected-index' ) ).toHaveTextContent( 'none' );
237
+ expect( screen.getByRole( 'grid', { name: 'Harness' } ) ).toHaveFocus();
348
238
 
349
- renderChart( { zIndex: 9 } );
350
- await expect( screen.findByTestId( 'tooltip-box' ) ).resolves.toHaveStyle( { zIndex: '9' } );
239
+ await user.keyboard( '{ArrowRight}' );
240
+
241
+ expect( screen.getByTestId( 'selected-index' ) ).toHaveTextContent( '5' );
351
242
  } );
352
243
 
353
- test.each( [ 'auto', 'below-axis' ] as const )(
354
- 'preserves %s background and stacking with a partial style override',
355
- async tooltipPlacement => {
356
- const { unmount } = renderChart( { tooltipPlacement } );
357
- const defaultBox = await screen.findByTestId( 'tooltip-box' );
358
- const background = defaultBox.style.backgroundColor;
359
- expect( background ).not.toBe( '' );
360
- expect( background ).not.toBe( 'transparent' );
361
- unmount();
362
-
363
- renderChart( { tooltipPlacement, style: { color: 'red' } } );
364
-
365
- await expect( screen.findByTestId( 'tooltip-box' ) ).resolves.toHaveStyle( {
366
- backgroundColor: background,
367
- zIndex: '3',
368
- color: 'rgb(255, 0, 0)',
369
- } );
370
- }
371
- );
244
+ it( 'continues from the last point the pointer reached after taking over', async () => {
245
+ const { user } = await navigate( 2 );
246
+
247
+ await user.hover( screen.getByTestId( 'point-4' ) );
248
+ await user.hover( screen.getByTestId( 'point-1' ) );
249
+ await user.keyboard( '{ArrowRight}' );
372
250
 
373
- test( 'accepts the portal-era options without passing them to the box', async () => {
374
- renderChart( { scroll: true, debounce: 50, resizeObserverPolyfill: undefined } );
251
+ expect( screen.getByTestId( 'selected-index' ) ).toHaveTextContent( '2' );
252
+ } );
253
+
254
+ it( 'restarts from the first point once focus leaves after the pointer took over', async () => {
255
+ const user = userEvent.setup();
256
+ render( <NavigationHarness totalPoints={ 6 } trackBlur /> );
257
+ const grid = screen.getByRole( 'grid', { name: 'Harness' } );
375
258
 
376
- const box = await screen.findByTestId( 'tooltip-box' );
259
+ act( () => grid.focus() );
260
+ await user.keyboard( '{ArrowRight}{ArrowRight}' );
261
+ await user.hover( screen.getByTestId( 'point-4' ) );
262
+ act( () => screen.getByRole( 'button', { name: 'Outside' } ).focus() );
263
+ act( () => grid.focus() );
264
+ await user.keyboard( '{ArrowRight}' );
377
265
 
378
- expect( box ).not.toHaveAttribute( 'scroll' );
379
- expect( box ).not.toHaveAttribute( 'debounce' );
266
+ expect( screen.getByTestId( 'selected-index' ) ).toHaveTextContent( '0' );
380
267
  } );
381
268
 
382
- test( 'renders no box when there is no tooltip renderer', async () => {
383
- renderChart( { renderTooltip: undefined } );
269
+ it( 'leaves focus outside the chart when the pointer ends a selection', async () => {
270
+ const { user } = await navigate( 2 );
271
+ const outside = screen.getByRole( 'button', { name: 'Outside' } );
272
+
273
+ outside.focus();
274
+ await user.hover( screen.getByTestId( 'point-4' ) );
384
275
 
385
- await expect( screen.findByTestId( 'xy-chart-tooltip-anchor' ) ).resolves.toBeInTheDocument();
386
- expect( screen.queryByTestId( 'tooltip-box' ) ).not.toBeInTheDocument();
276
+ expect( screen.getByTestId( 'selected-index' ) ).toHaveTextContent( 'none' );
277
+ expect( outside ).toHaveFocus();
387
278
  } );
388
279
 
389
- test( 'renders nothing when the tooltip content is empty', async () => {
390
- renderChart( { renderTooltip: () => null, showSeriesGlyphs: true }, BOTH_SERIES );
280
+ it( 'ignores the pointer when there is no keyboard selection', async () => {
281
+ const user = userEvent.setup();
282
+ render( <NavigationHarness totalPoints={ 6 } /> );
283
+
284
+ screen.getByRole( 'grid', { name: 'Harness' } ).focus();
285
+ await user.hover( screen.getByTestId( 'point-4' ) );
286
+ await user.keyboard( '{ArrowRight}' );
287
+
288
+ expect( screen.getByTestId( 'selected-index' ) ).toHaveTextContent( '0' );
289
+ } );
290
+
291
+ // The page sees the event after the handler, so this is what a surrounding scroll or Modal gets.
292
+ const recordPageKeyDown = () => {
293
+ const onKeyDown = jest.fn< void, [ KeyboardEvent ] >();
294
+ document.addEventListener( 'keydown', onKeyDown );
295
+ return { onKeyDown, stop: () => document.removeEventListener( 'keydown', onKeyDown ) };
296
+ };
297
+
298
+ it( 'leaves keys it does not handle available to the page', async () => {
299
+ const user = userEvent.setup();
300
+ render( <NavigationHarness totalPoints={ 6 } /> );
301
+ const { onKeyDown, stop } = recordPageKeyDown();
302
+
303
+ try {
304
+ screen.getByRole( 'grid', { name: 'Harness' } ).focus();
305
+ await user.keyboard( '{ArrowDown}{PageDown}[Space]' );
391
306
 
392
- // The anchor is the only thing rendered while there is nothing to show.
393
- await expect( screen.findByTestId( 'xy-chart-tooltip-anchor' ) ).resolves.toBeInTheDocument();
394
- expect( screen.queryByTestId( 'tooltip-box' ) ).not.toBeInTheDocument();
395
- expect( screen.queryByTestId( 'xy-chart-tooltip-glyph-A' ) ).not.toBeInTheDocument();
307
+ expect( onKeyDown ).toHaveBeenCalledTimes( 3 );
308
+ for ( const [ event ] of onKeyDown.mock.calls ) {
309
+ expect( event.defaultPrevented ).toBe( false );
310
+ }
311
+ } finally {
312
+ stop();
313
+ }
396
314
  } );
397
315
 
398
- test( 'renders nothing while the tooltip is closed', () => {
399
- renderChart( { showSeriesGlyphs: true, showVerticalCrosshair: true }, [] );
316
+ // `@wordpress/components` Modal skips its own close-on-Escape once the event is defaultPrevented.
317
+ it( 'leaves Escape to the page when there is no selection to dismiss', async () => {
318
+ const user = userEvent.setup();
319
+ render( <NavigationHarness totalPoints={ 6 } /> );
320
+ const { onKeyDown, stop } = recordPageKeyDown();
321
+
322
+ try {
323
+ screen.getByRole( 'grid', { name: 'Harness' } ).focus();
324
+ await user.keyboard( '{Escape}' );
400
325
 
401
- expect( screen.queryByTestId( 'tooltip-box' ) ).not.toBeInTheDocument();
402
- expect( screen.queryByTestId( 'xy-chart-tooltip-glyph-A' ) ).not.toBeInTheDocument();
403
- expect( screen.queryByTestId( 'xy-chart-tooltip-crosshair-vertical' ) ).not.toBeInTheDocument();
326
+ expect( onKeyDown.mock.calls[ 0 ][ 0 ].defaultPrevented ).toBe( false );
327
+
328
+ await user.keyboard( '{ArrowRight}{Escape}' );
329
+
330
+ expect( onKeyDown.mock.calls.at( -1 )?.[ 0 ].defaultPrevented ).toBe( true );
331
+ } finally {
332
+ stop();
333
+ }
404
334
  } );
405
335
  } );