@svgrid/grid 2.2.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/dist/FlexRender.svelte +96 -96
  2. package/dist/GridFooter.svelte +178 -178
  3. package/dist/SvCarousel.svelte +141 -141
  4. package/dist/SvColorInput.svelte +187 -187
  5. package/dist/SvContextMenu.svelte +116 -116
  6. package/dist/SvDrawer.svelte +250 -250
  7. package/dist/SvGrid.svelte +3131 -3131
  8. package/dist/SvGridBoard.svelte +2339 -2339
  9. package/dist/SvGridChart.svelte +1724 -1724
  10. package/dist/SvGridChartPanel.svelte +485 -485
  11. package/dist/SvGridDropdown.svelte +689 -689
  12. package/dist/SvGroupCell.svelte +109 -109
  13. package/dist/SvMenu.svelte +124 -124
  14. package/dist/SvMenuList.svelte +117 -117
  15. package/dist/SvNumberInput.svelte +131 -131
  16. package/dist/SvOtpInput.svelte +158 -158
  17. package/dist/SvPopover.svelte +139 -139
  18. package/dist/SvRowGroupPanel.svelte +170 -170
  19. package/dist/SvScrollArea.svelte +61 -61
  20. package/dist/SvTooltip.svelte +127 -127
  21. package/dist/SvTour.svelte +204 -204
  22. package/dist/SvTree.svelte +377 -377
  23. package/dist/SvTreeSelect.svelte +230 -230
  24. package/dist/cdn/svgrid.js +8 -8
  25. package/dist/cdn/svgrid.svelte-external.js +8 -8
  26. package/dist/chart-export.js +8 -8
  27. package/package.json +10 -10
  28. package/src/FlexRender.svelte +96 -96
  29. package/src/GridFooter.svelte +178 -178
  30. package/src/SvCarousel.svelte +141 -141
  31. package/src/SvColorInput.svelte +187 -187
  32. package/src/SvContextMenu.svelte +116 -116
  33. package/src/SvDrawer.svelte +250 -250
  34. package/src/SvGrid.controller.svelte.ts +3158 -3158
  35. package/src/SvGrid.svelte +3131 -3131
  36. package/src/SvGrid.types.ts +1489 -1489
  37. package/src/SvGridBoard.svelte +2339 -2339
  38. package/src/SvGridChart.svelte +1724 -1724
  39. package/src/SvGridChartPanel.svelte +485 -485
  40. package/src/SvGridDropdown.svelte +689 -689
  41. package/src/SvGroupCell.svelte +109 -109
  42. package/src/SvMenu.svelte +124 -124
  43. package/src/SvMenu.test.ts +97 -97
  44. package/src/SvMenuList.svelte +117 -117
  45. package/src/SvNumberInput.svelte +131 -131
  46. package/src/SvOtpInput.svelte +158 -158
  47. package/src/SvPopover.svelte +139 -139
  48. package/src/SvRowGroupPanel.svelte +170 -170
  49. package/src/SvScrollArea.svelte +61 -61
  50. package/src/SvTooltip.svelte +127 -127
  51. package/src/SvTour.svelte +204 -204
  52. package/src/SvTree.svelte +377 -377
  53. package/src/SvTreeSelect.svelte +230 -230
  54. package/src/a11y.contract.test.ts +49 -49
  55. package/src/a11y.test.ts +59 -59
  56. package/src/a11y.ts +61 -61
  57. package/src/build-api.ts +870 -870
  58. package/src/cell-formatting.ts +169 -169
  59. package/src/cell-render.ts +469 -469
  60. package/src/chart-export.ts +201 -201
  61. package/src/chart.ts +2296 -2296
  62. package/src/collaboration.test.ts +104 -104
  63. package/src/collaboration.ts +167 -167
  64. package/src/core.performance.test.ts +30 -30
  65. package/src/core.ts +1111 -1111
  66. package/src/createAutocomplete.svelte.ts +132 -132
  67. package/src/createCombobox.svelte.ts +179 -179
  68. package/src/createCountryInput.svelte.ts +157 -157
  69. package/src/createDropdownList.svelte.ts +162 -162
  70. package/src/createGrid.svelte.ts +42 -42
  71. package/src/createGrid.test.ts +10 -10
  72. package/src/createGridState.svelte.ts +17 -17
  73. package/src/createMenu.svelte.ts +202 -202
  74. package/src/createPopoverSelect.svelte.ts +206 -206
  75. package/src/createTree.svelte.ts +319 -319
  76. package/src/editing.test.ts +859 -859
  77. package/src/editing.ts +675 -675
  78. package/src/export-data-api.test.ts +126 -126
  79. package/src/export-format.test.ts +107 -107
  80. package/src/export-format.ts +598 -598
  81. package/src/flex-render.ts +3 -3
  82. package/src/index.ts +623 -623
  83. package/src/keyboard.test.ts +59 -59
  84. package/src/keyboard.ts +97 -97
  85. package/src/list-nav.test.ts +49 -49
  86. package/src/list-nav.ts +29 -29
  87. package/src/menus.ts +639 -639
  88. package/src/merge-objects.ts +48 -48
  89. package/src/overlays.test.ts +90 -90
  90. package/src/render-component.ts +28 -28
  91. package/src/selection.test.ts +754 -754
  92. package/src/selection.ts +600 -600
  93. package/src/server-data-source.test.ts +289 -289
  94. package/src/server-data-source.ts +413 -413
  95. package/src/sparkline.test.ts +68 -68
  96. package/src/sparkline.ts +169 -169
  97. package/src/spreadsheet.test.ts +489 -489
  98. package/src/spreadsheet.ts +312 -312
  99. package/src/static-functions.ts +11 -11
  100. package/src/subscribe.ts +38 -38
  101. package/src/svgrid-wrapper.types.ts +501 -501
  102. package/src/svgrid.behavior.test.ts +706 -706
  103. package/src/svgrid.charting.test.ts +527 -527
  104. package/src/svgrid.features.test.ts +157 -157
  105. package/src/svgrid.new-features.wrapper.test.ts +251 -251
  106. package/src/svgrid.wrapper.test.ts +40 -40
  107. package/src/test-setup.ts +62 -62
  108. package/src/themes/index.ts +159 -159
  109. package/src/virtualization/column-virtualizer.test.ts +27 -27
  110. package/src/virtualization/column-virtualizer.ts +30 -30
  111. package/src/virtualization/svelte-virtualizer.svelte.ts +26 -26
  112. package/src/virtualization/types.ts +30 -30
  113. package/src/virtualization/virtualizer.test.ts +47 -47
  114. package/src/virtualization/virtualizer.ts +296 -296
@@ -1,527 +1,527 @@
1
- /**
2
- * Built-in integrated charting (`charting` prop on <SvGrid>): the docked chart
3
- * panel, its live derivation from displayed rows + selection, and the
4
- * chart-click -> grid cross-filter loop.
5
- */
6
- import { describe, expect, it } from 'vitest'
7
- import { mount, unmount } from 'svelte'
8
- import SvGrid from './SvGrid.svelte'
9
- import {
10
- columnFilteringFeature,
11
- createCoreRowModel,
12
- createFilteredRowModel,
13
- createSortedRowModel,
14
- rowSelectionFeature,
15
- rowSortingFeature,
16
- sortFns,
17
- tableFeatures,
18
- chartSpecToCsv,
19
- formatChartValue,
20
- buildChart,
21
- } from './index'
22
- import type { ColumnDef, SvGridApi } from './index'
23
-
24
- type Person = { id: number; name: string; team: string; age: number; salary: number }
25
-
26
- const features = tableFeatures({ columnFilteringFeature, rowSelectionFeature, rowSortingFeature })
27
-
28
- const people: Person[] = [
29
- { id: 1, name: 'Ada', team: 'Research', age: 38, salary: 120 },
30
- { id: 2, name: 'Grace', team: 'Compilers', age: 42, salary: 150 },
31
- { id: 3, name: 'Alan', team: 'Research', age: 41, salary: 130 },
32
- { id: 4, name: 'Margaret', team: 'Apollo', age: 35, salary: 160 },
33
- { id: 5, name: 'Linus', team: 'Kernel', age: 54, salary: 175 },
34
- { id: 6, name: 'Donald', team: 'Research', age: 86, salary: 110 },
35
- ]
36
-
37
- const columns: ColumnDef<typeof features, Person>[] = [
38
- { field: 'name', header: 'Name', width: 160 },
39
- { field: 'team', header: 'Team', width: 160 },
40
- { field: 'age', header: 'Age', width: 100, cellDataType: 'number' },
41
- { field: 'salary', header: 'Salary', width: 100, cellDataType: 'number' },
42
- ]
43
-
44
- type MountResult = { api: SvGridApi<typeof features, Person>; target: HTMLElement; destroy: () => void }
45
-
46
- function mountGrid(overrides: Record<string, unknown> = {}): Promise<MountResult> {
47
- return new Promise((resolve, reject) => {
48
- const target = document.createElement('div')
49
- target.style.width = '1000px'
50
- target.style.height = '600px'
51
- document.body.appendChild(target)
52
- const app = mount(SvGrid, {
53
- target,
54
- props: {
55
- data: people,
56
- columns,
57
- features,
58
- _rowModels: {
59
- coreRowModel: createCoreRowModel(),
60
- filteredRowModel: createFilteredRowModel(),
61
- sortedRowModel: createSortedRowModel(sortFns),
62
- },
63
- rowHeight: 36,
64
- containerHeight: 480,
65
- virtualization: false,
66
- onApiReady(api: SvGridApi<typeof features, Person>) {
67
- resolve({ api, target, destroy: () => { unmount(app); target.remove() } })
68
- },
69
- ...overrides,
70
- } as any,
71
- })
72
- queueMicrotask(() => reject(new Error('onApiReady never fired')))
73
- })
74
- }
75
-
76
- const tick = () => Promise.resolve()
77
-
78
- describe('SvGrid built-in charting', () => {
79
- it('derives a chart spec from all displayed rows (default dimension + measure)', async () => {
80
- const { api, destroy } = await mountGrid({ charting: true })
81
- try {
82
- const spec = api.getChartSpec()
83
- expect(spec).not.toBeNull()
84
- expect(spec!.type).toBe('bar')
85
- // Default dimension is the first text column (name), one category per row.
86
- expect(spec!.categories.length).toBe(people.length)
87
- } finally {
88
- destroy()
89
- }
90
- })
91
-
92
- it('re-derives the chart when the grid is filtered (auto-refresh)', async () => {
93
- const { api, destroy } = await mountGrid({ charting: true })
94
- try {
95
- // Filter to the Research team (3 people) via the same facet-filter state
96
- // the chart's own cross-filter writes.
97
- api.setFacetFilter('team', ['Research'])
98
- await tick()
99
- const spec = api.getChartSpec()
100
- expect(spec!.categories.length).toBe(3)
101
- } finally {
102
- destroy()
103
- }
104
- })
105
-
106
- it('scopes the chart to the selected cell range', async () => {
107
- const { api, destroy } = await mountGrid({ charting: true })
108
- try {
109
- // Select the first two rows across all columns.
110
- api.selectCells([[0, 0, 1, 2]])
111
- await tick()
112
- const spec = api.getChartSpec()
113
- expect(spec!.categories.length).toBe(2)
114
- } finally {
115
- destroy()
116
- }
117
- })
118
-
119
- it('renders the docked panel with an <svg> when open', async () => {
120
- const { target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
121
- try {
122
- await tick()
123
- const panel = target.querySelector('.sv-grid-chart-panel')
124
- expect(panel).toBeTruthy()
125
- expect(panel!.querySelector('svg')).toBeTruthy()
126
- } finally {
127
- destroy()
128
- }
129
- })
130
-
131
- it('pops the docked panel out into a floating window, maximizes, and docks back', async () => {
132
- const { target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
133
- try {
134
- await tick()
135
- const panel = () => target.querySelector('.sv-grid-chart-panel')!
136
- const click = (label: string) => {
137
- const btn = target.querySelector<HTMLButtonElement>(`[aria-label="${label}"]`)
138
- expect(btn).toBeTruthy()
139
- btn!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
140
- }
141
- // Starts docked.
142
- expect(panel().classList.contains('is-floating')).toBe(false)
143
- // Pop out -> floating window.
144
- click('Pop out chart')
145
- await tick()
146
- expect(panel().classList.contains('is-floating')).toBe(true)
147
- // Maximize -> fills the grid.
148
- click('Maximize')
149
- await tick()
150
- expect(panel().classList.contains('is-maximized')).toBe(true)
151
- // Dock back -> re-docked, not floating, not maximized.
152
- click('Dock chart')
153
- await tick()
154
- expect(panel().classList.contains('is-floating')).toBe(false)
155
- expect(panel().classList.contains('is-maximized')).toBe(false)
156
- } finally {
157
- destroy()
158
- }
159
- })
160
-
161
- it('adds a second chart, shows a tab strip, and persists both charts in view state', async () => {
162
- const { api, target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
163
- try {
164
- await tick()
165
- // One chart, no tab strip yet.
166
- expect(target.querySelectorAll('.sv-grid-chart-tab').length).toBe(0)
167
- // Add a chart.
168
- const add = target.querySelector<HTMLButtonElement>('[aria-label="Add chart"]')
169
- expect(add).toBeTruthy()
170
- add!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
171
- await tick()
172
- // Now two tabs; the second is active.
173
- const tabs = target.querySelectorAll('.sv-grid-chart-tab')
174
- expect(tabs.length).toBe(2)
175
- expect(tabs[1]!.classList.contains('is-active')).toBe(true)
176
- // View state carries both charts + the active index.
177
- const state = api.getState() as any
178
- expect(state.charts.length).toBe(2)
179
- expect(state.chartActive).toBe(1)
180
- // Removing a chart drops back to a single chart (tab strip disappears).
181
- target.querySelector<HTMLButtonElement>('.sv-grid-chart-tab.is-active .sv-grid-chart-tab-x')!
182
- .dispatchEvent(new MouseEvent('click', { bubbles: true }))
183
- await tick()
184
- expect(target.querySelectorAll('.sv-grid-chart-tab').length).toBe(0)
185
- expect((api.getState() as any).charts.length).toBe(1)
186
- } finally {
187
- destroy()
188
- }
189
- })
190
-
191
- it('keeps each chart\'s own type when switching tabs', async () => {
192
- const { api, target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
193
- try {
194
- await tick()
195
- // Chart 1 -> line.
196
- const typeSel = () => target.querySelector<HTMLSelectElement>('.sv-grid-chart-controls select')!
197
- typeSel().value = 'line'
198
- typeSel().dispatchEvent(new Event('change', { bubbles: true }))
199
- await tick()
200
- expect(api.getChartSpec()!.type).toBe('line')
201
- // Add Chart 2 (defaults to bar).
202
- target.querySelector<HTMLButtonElement>('[aria-label="Add chart"]')!
203
- .dispatchEvent(new MouseEvent('click', { bubbles: true }))
204
- await tick()
205
- expect(api.getChartSpec()!.type).toBe('bar')
206
- // Switch back to Chart 1 -> still line.
207
- target.querySelectorAll<HTMLButtonElement>('.sv-grid-chart-tab-label')[0]!
208
- .dispatchEvent(new MouseEvent('click', { bubbles: true }))
209
- await tick()
210
- expect(api.getChartSpec()!.type).toBe('line')
211
- } finally {
212
- destroy()
213
- }
214
- })
215
-
216
- it('configureChart applies a config to the active chart (resolving field names)', async () => {
217
- const { api, destroy } = await mountGrid({ charting: { defaultOpen: true } })
218
- try {
219
- api.configureChart({ type: 'line', dimension: 'team', measure: 'salary', reduce: 'avg' })
220
- await tick()
221
- const spec = api.getChartSpec()
222
- expect(spec!.type).toBe('line')
223
- // salary aggregated by team -> one category per distinct team.
224
- expect(spec!.categories.length).toBeGreaterThan(0)
225
- } finally {
226
- destroy()
227
- }
228
- })
229
-
230
- it('shows an AI button only when a chart-AI handler is registered, and applies its result', async () => {
231
- const { api, target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
232
- try {
233
- await tick()
234
- // No handler -> no AI button.
235
- expect(target.querySelector('[aria-label="Chart with AI"]')).toBeFalsy()
236
- // Register a deterministic handler (stands in for enterprise's aiChart).
237
- api.setChartAiHandler(async () => ({
238
- type: 'line',
239
- dimension: 'team',
240
- series: null,
241
- measure: 'salary',
242
- reduce: 'avg',
243
- stacked: false,
244
- rationale: 'line of avg salary by team',
245
- }))
246
- await tick()
247
- const aiBtn = target.querySelector<HTMLButtonElement>('[aria-label="Chart with AI"]')
248
- expect(aiBtn).toBeTruthy()
249
- // Open the prompt row, type a query, submit.
250
- aiBtn!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
251
- await tick()
252
- const input = target.querySelector<HTMLInputElement>('.sv-grid-chart-ai-input')!
253
- input.value = 'average salary by team as a line'
254
- input.dispatchEvent(new Event('input', { bubbles: true }))
255
- const form = target.querySelector<HTMLFormElement>('.sv-grid-chart-ai-row')!
256
- form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
257
- // Let the async handler resolve.
258
- await new Promise((r) => setTimeout(r, 0))
259
- await tick()
260
- expect(api.getChartSpec()!.type).toBe('line')
261
- } finally {
262
- destroy()
263
- }
264
- })
265
-
266
- it('toggles a logarithmic value axis (configureChart + panel toggle present)', async () => {
267
- const { api, target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
268
- try {
269
- api.configureChart({ dimension: 'team', measure: 'salary' })
270
- await tick()
271
- expect(api.getChartSpec()!.yScale).not.toBe('log')
272
- api.configureChart({ logScale: true })
273
- await tick()
274
- expect(api.getChartSpec()!.yScale).toBe('log')
275
- const labels = [...target.querySelectorAll('.sv-grid-chart-toggle')].map((l) => l.textContent?.trim())
276
- expect(labels).toContain('Log scale')
277
- } finally {
278
- destroy()
279
- }
280
- })
281
-
282
- it('offers a date axis only when the group-by column is date-like', async () => {
283
- // Non-date dimension -> no Date axis toggle.
284
- const a = await mountGrid({ charting: { defaultOpen: true } })
285
- try {
286
- await tick()
287
- const labels = [...a.target.querySelectorAll('.sv-grid-chart-toggle')].map((l) => l.textContent?.trim())
288
- expect(labels).not.toContain('Date axis')
289
- } finally {
290
- a.destroy()
291
- }
292
- // Date dimension -> Date axis toggle appears and drives xType: 'time'.
293
- const dateColumns = [
294
- { field: 'day', header: 'Day', width: 120, cellDataType: 'date' },
295
- { field: 'channel', header: 'Channel', width: 120 },
296
- { field: 'signups', header: 'Signups', width: 100, cellDataType: 'number' },
297
- ]
298
- const dateData = [
299
- { id: 1, day: '2026-01-01', channel: 'Organic', signups: 10 },
300
- { id: 2, day: '2026-01-02', channel: 'Organic', signups: 20 },
301
- { id: 3, day: '2026-01-03', channel: 'Paid', signups: 30 },
302
- ]
303
- const b = await mountGrid({
304
- data: dateData,
305
- columns: dateColumns,
306
- charting: { defaultOpen: true, dimension: 'day', measures: 'signups' },
307
- })
308
- try {
309
- await tick()
310
- const labels = [...b.target.querySelectorAll('.sv-grid-chart-toggle')].map((l) => l.textContent?.trim())
311
- expect(labels).toContain('Date axis')
312
- b.api.configureChart({ timeAxis: true })
313
- await tick()
314
- expect(b.api.getChartSpec()!.xType).toBe('time')
315
- } finally {
316
- b.destroy()
317
- }
318
- })
319
-
320
- it('serializes chart data to CSV and shows an Export menu (PNG/SVG/CSV/Copy)', async () => {
321
- const { api, target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
322
- try {
323
- api.configureChart({ dimension: 'team', series: 'name', measure: 'salary' })
324
- await tick()
325
- const csv = chartSpecToCsv(api.getChartSpec()!)
326
- const [header, ...rows] = csv.split('\n')
327
- expect(header.startsWith('Category,')).toBe(true)
328
- expect(rows.length).toBeGreaterThan(0)
329
- // Export button + menu.
330
- const btn = target.querySelector<HTMLButtonElement>('[aria-label="Export chart"]')
331
- expect(btn).toBeTruthy()
332
- btn!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
333
- await tick()
334
- const items = [...target.querySelectorAll('.sv-grid-chart-export-menu button')].map((b) => b.textContent)
335
- expect(items).toEqual(['PNG image', 'SVG vector', 'CSV data', 'Copy to clipboard'])
336
- } finally {
337
- destroy()
338
- }
339
- })
340
-
341
- it('buildChart emits a grouped category-axis tier from categoryGroups', () => {
342
- const geo = buildChart({
343
- type: 'bar',
344
- categories: ['USA', 'Canada', 'Japan', 'India'],
345
- series: [{ label: 'Rev', values: [10, 20, 30, 40] }],
346
- categoryGroups: [{ label: 'Americas', span: 2 }, { label: 'APAC', span: 2 }],
347
- })
348
- expect(geo.categoryGroupTicks.map((g) => g.label)).toEqual(['Americas', 'APAC'])
349
- // Groups tile the axis edge-to-edge (first group's right = second's left).
350
- expect(geo.categoryGroupTicks[0]!.x1).toBe(geo.categoryGroupTicks[1]!.x0)
351
- // Ignored when the spans don't cover every leaf.
352
- const bad = buildChart({
353
- type: 'bar',
354
- categories: ['A', 'B', 'C'],
355
- series: [{ label: 'x', values: [1, 2, 3] }],
356
- categoryGroups: [{ label: 'G', span: 2 }],
357
- })
358
- expect(bad.categoryGroupTicks.length).toBe(0)
359
- })
360
-
361
- it('formatChartValue renders currency / percent / compact', () => {
362
- expect(formatChartValue(1500, 'currency')).toBe('$1.5k')
363
- expect(formatChartValue(-2_000_000, 'currency')).toBe('-$2M')
364
- expect(formatChartValue(0.25, 'percent')).toBe('25%')
365
- expect(formatChartValue(1500)).toBe('1.5k')
366
- expect(formatChartValue(1500, 'number')).toBe('1.5k')
367
- })
368
-
369
- it('applies a value format and an auto y-axis title to the spec', async () => {
370
- const { api, destroy } = await mountGrid({ charting: { defaultOpen: true } })
371
- try {
372
- api.configureChart({ dimension: 'team', measure: 'salary', reduce: 'sum', valueFormat: 'currency' })
373
- await tick()
374
- const spec = api.getChartSpec()!
375
- expect(spec.valueFormat).toBe('currency')
376
- expect(spec.yAxisTitle).toBe('Sum of Salary')
377
- } finally {
378
- destroy()
379
- }
380
- })
381
-
382
- it('defaults the value format from the measure column format', async () => {
383
- const cols = [
384
- { field: 'team', header: 'Team', width: 120 },
385
- { field: 'salary', header: 'Salary', width: 120, cellDataType: 'number', format: { type: 'currency', currency: 'USD' } },
386
- ]
387
- const { api, destroy } = await mountGrid({
388
- columns: cols,
389
- charting: { defaultOpen: true, dimension: 'team', measures: 'salary' },
390
- })
391
- try {
392
- await tick()
393
- expect(api.getChartSpec()!.valueFormat).toBe('currency')
394
- } finally {
395
- destroy()
396
- }
397
- })
398
-
399
- it('splits into one series per distinct value of the `series` field', async () => {
400
- const { api, destroy } = await mountGrid({ charting: { dimension: 'team', series: 'name', measures: 'age' } })
401
- try {
402
- const spec = api.getChartSpec()
403
- // categories = distinct teams (4); one series per distinct name (6).
404
- expect(spec!.series.length).toBe(6)
405
- } finally {
406
- destroy()
407
- }
408
- })
409
-
410
- it('plots one series per measure with `measures[]`', async () => {
411
- const { api, destroy } = await mountGrid({ charting: { dimension: 'team', measures: ['age', 'salary'] } })
412
- try {
413
- const spec = api.getChartSpec()
414
- expect(spec!.series.length).toBe(2)
415
- } finally {
416
- destroy()
417
- }
418
- })
419
-
420
- it('marks the spec stacked when config.stacked is set', async () => {
421
- const { api, destroy } = await mountGrid({ charting: { dimension: 'team', series: 'name', measures: 'age', stacked: true } })
422
- try {
423
- expect(api.getChartSpec()!.stacked).toBe(true)
424
- } finally {
425
- destroy()
426
- }
427
- })
428
-
429
- it('renders a custom `buildSpec` chart that stays live with the grid', async () => {
430
- const { api, destroy } = await mountGrid({
431
- charting: { defaultOpen: true, buildSpec: (rows) => ({ type: 'bar', categories: ['All'], series: [{ label: 'Count', values: [rows.length] }] }) },
432
- })
433
- try {
434
- await tick()
435
- // The custom spec reflects all displayed rows...
436
- expect(api.getChartSpec()!.series[0]!.values[0]).toBe(people.length)
437
- // ...and re-derives when the grid is filtered (auto-refresh through buildSpec).
438
- api.setFacetFilter('team', ['Research'])
439
- await tick()
440
- expect(api.getChartSpec()!.series[0]!.values[0]).toBe(3)
441
- } finally {
442
- destroy()
443
- }
444
- })
445
-
446
- it('maps a multi-column cell selection to dimension + split-by + measures (column-exact)', async () => {
447
- const { api, destroy } = await mountGrid({ charting: true })
448
- try {
449
- // Select columns 1..3 (team, age, salary) across the first two rows:
450
- // team -> dimension, no 2nd text col, age+salary -> measures.
451
- api.selectCells([[0, 1, 1, 3]])
452
- await tick()
453
- const spec = api.getChartSpec()
454
- // Two numeric columns in the span -> two series.
455
- expect(spec!.series.length).toBe(2)
456
- } finally {
457
- destroy()
458
- }
459
- })
460
-
461
- it('round-trips the chart config through getState / setState', async () => {
462
- const a = await mountGrid({ charting: true })
463
- try {
464
- a.api.openChart()
465
- a.api.setState({ ...a.api.getState(), chart: { open: true, type: 'line', dimension: 'team', series: null, measure: 'salary', reduce: 'avg', stacked: false } } as any)
466
- await tick()
467
- const state = a.api.getState() as any
468
- expect(state.chart).toBeTruthy()
469
- expect(state.chart.type).toBe('line')
470
- expect(state.chart.reduce).toBe('avg')
471
- const spec = a.api.getChartSpec()
472
- expect(spec!.type).toBe('line')
473
- } finally {
474
- a.destroy()
475
- }
476
- })
477
-
478
- it('charts server-side buckets from getAggregate and refetches on filter change', async () => {
479
- let calls = 0
480
- let lastFilter: any = null
481
- const { api, destroy } = await mountGrid({
482
- charting: {
483
- getAggregate: async (req) => {
484
- calls += 1
485
- lastFilter = req.filterModel
486
- return [
487
- { category: 'A', value: 10 },
488
- { category: 'B', value: 20 },
489
- ]
490
- },
491
- },
492
- })
493
- try {
494
- await new Promise((r) => setTimeout(r, 15))
495
- const spec = api.getChartSpec()
496
- expect(spec).not.toBeNull()
497
- expect(spec!.categories).toEqual(['A', 'B'])
498
- expect(spec!.series[0]!.values).toEqual([10, 20])
499
- expect(calls).toBeGreaterThan(0)
500
- // A filter change re-runs the server aggregation with the new filter.
501
- const before = calls
502
- api.setFacetFilter('team', ['Research'])
503
- await new Promise((r) => setTimeout(r, 15))
504
- expect(calls).toBeGreaterThan(before)
505
- expect(lastFilter.facets.team).toEqual(['Research'])
506
- } finally {
507
- destroy()
508
- }
509
- })
510
-
511
- it('cross-filters the grid when a chart category is clicked', async () => {
512
- const { api, target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
513
- try {
514
- await tick()
515
- expect(api.getDisplayedRows().length).toBe(people.length)
516
- // The full-height hit rect for the first category carries data-cat-index=0.
517
- const hit = target.querySelector<SVGElement>('.sv-grid-chart-panel svg [data-cat-index="0"]')
518
- expect(hit).toBeTruthy()
519
- hit!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
520
- await tick()
521
- // Clicking one category (a distinct name) filters the grid to that row.
522
- expect(api.getDisplayedRows().length).toBe(1)
523
- } finally {
524
- destroy()
525
- }
526
- })
527
- })
1
+ /**
2
+ * Built-in integrated charting (`charting` prop on <SvGrid>): the docked chart
3
+ * panel, its live derivation from displayed rows + selection, and the
4
+ * chart-click -> grid cross-filter loop.
5
+ */
6
+ import { describe, expect, it } from 'vitest'
7
+ import { mount, unmount } from 'svelte'
8
+ import SvGrid from './SvGrid.svelte'
9
+ import {
10
+ columnFilteringFeature,
11
+ createCoreRowModel,
12
+ createFilteredRowModel,
13
+ createSortedRowModel,
14
+ rowSelectionFeature,
15
+ rowSortingFeature,
16
+ sortFns,
17
+ tableFeatures,
18
+ chartSpecToCsv,
19
+ formatChartValue,
20
+ buildChart,
21
+ } from './index'
22
+ import type { ColumnDef, SvGridApi } from './index'
23
+
24
+ type Person = { id: number; name: string; team: string; age: number; salary: number }
25
+
26
+ const features = tableFeatures({ columnFilteringFeature, rowSelectionFeature, rowSortingFeature })
27
+
28
+ const people: Person[] = [
29
+ { id: 1, name: 'Ada', team: 'Research', age: 38, salary: 120 },
30
+ { id: 2, name: 'Grace', team: 'Compilers', age: 42, salary: 150 },
31
+ { id: 3, name: 'Alan', team: 'Research', age: 41, salary: 130 },
32
+ { id: 4, name: 'Margaret', team: 'Apollo', age: 35, salary: 160 },
33
+ { id: 5, name: 'Linus', team: 'Kernel', age: 54, salary: 175 },
34
+ { id: 6, name: 'Donald', team: 'Research', age: 86, salary: 110 },
35
+ ]
36
+
37
+ const columns: ColumnDef<typeof features, Person>[] = [
38
+ { field: 'name', header: 'Name', width: 160 },
39
+ { field: 'team', header: 'Team', width: 160 },
40
+ { field: 'age', header: 'Age', width: 100, cellDataType: 'number' },
41
+ { field: 'salary', header: 'Salary', width: 100, cellDataType: 'number' },
42
+ ]
43
+
44
+ type MountResult = { api: SvGridApi<typeof features, Person>; target: HTMLElement; destroy: () => void }
45
+
46
+ function mountGrid(overrides: Record<string, unknown> = {}): Promise<MountResult> {
47
+ return new Promise((resolve, reject) => {
48
+ const target = document.createElement('div')
49
+ target.style.width = '1000px'
50
+ target.style.height = '600px'
51
+ document.body.appendChild(target)
52
+ const app = mount(SvGrid, {
53
+ target,
54
+ props: {
55
+ data: people,
56
+ columns,
57
+ features,
58
+ _rowModels: {
59
+ coreRowModel: createCoreRowModel(),
60
+ filteredRowModel: createFilteredRowModel(),
61
+ sortedRowModel: createSortedRowModel(sortFns),
62
+ },
63
+ rowHeight: 36,
64
+ containerHeight: 480,
65
+ virtualization: false,
66
+ onApiReady(api: SvGridApi<typeof features, Person>) {
67
+ resolve({ api, target, destroy: () => { unmount(app); target.remove() } })
68
+ },
69
+ ...overrides,
70
+ } as any,
71
+ })
72
+ queueMicrotask(() => reject(new Error('onApiReady never fired')))
73
+ })
74
+ }
75
+
76
+ const tick = () => Promise.resolve()
77
+
78
+ describe('SvGrid built-in charting', () => {
79
+ it('derives a chart spec from all displayed rows (default dimension + measure)', async () => {
80
+ const { api, destroy } = await mountGrid({ charting: true })
81
+ try {
82
+ const spec = api.getChartSpec()
83
+ expect(spec).not.toBeNull()
84
+ expect(spec!.type).toBe('bar')
85
+ // Default dimension is the first text column (name), one category per row.
86
+ expect(spec!.categories.length).toBe(people.length)
87
+ } finally {
88
+ destroy()
89
+ }
90
+ })
91
+
92
+ it('re-derives the chart when the grid is filtered (auto-refresh)', async () => {
93
+ const { api, destroy } = await mountGrid({ charting: true })
94
+ try {
95
+ // Filter to the Research team (3 people) via the same facet-filter state
96
+ // the chart's own cross-filter writes.
97
+ api.setFacetFilter('team', ['Research'])
98
+ await tick()
99
+ const spec = api.getChartSpec()
100
+ expect(spec!.categories.length).toBe(3)
101
+ } finally {
102
+ destroy()
103
+ }
104
+ })
105
+
106
+ it('scopes the chart to the selected cell range', async () => {
107
+ const { api, destroy } = await mountGrid({ charting: true })
108
+ try {
109
+ // Select the first two rows across all columns.
110
+ api.selectCells([[0, 0, 1, 2]])
111
+ await tick()
112
+ const spec = api.getChartSpec()
113
+ expect(spec!.categories.length).toBe(2)
114
+ } finally {
115
+ destroy()
116
+ }
117
+ })
118
+
119
+ it('renders the docked panel with an <svg> when open', async () => {
120
+ const { target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
121
+ try {
122
+ await tick()
123
+ const panel = target.querySelector('.sv-grid-chart-panel')
124
+ expect(panel).toBeTruthy()
125
+ expect(panel!.querySelector('svg')).toBeTruthy()
126
+ } finally {
127
+ destroy()
128
+ }
129
+ })
130
+
131
+ it('pops the docked panel out into a floating window, maximizes, and docks back', async () => {
132
+ const { target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
133
+ try {
134
+ await tick()
135
+ const panel = () => target.querySelector('.sv-grid-chart-panel')!
136
+ const click = (label: string) => {
137
+ const btn = target.querySelector<HTMLButtonElement>(`[aria-label="${label}"]`)
138
+ expect(btn).toBeTruthy()
139
+ btn!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
140
+ }
141
+ // Starts docked.
142
+ expect(panel().classList.contains('is-floating')).toBe(false)
143
+ // Pop out -> floating window.
144
+ click('Pop out chart')
145
+ await tick()
146
+ expect(panel().classList.contains('is-floating')).toBe(true)
147
+ // Maximize -> fills the grid.
148
+ click('Maximize')
149
+ await tick()
150
+ expect(panel().classList.contains('is-maximized')).toBe(true)
151
+ // Dock back -> re-docked, not floating, not maximized.
152
+ click('Dock chart')
153
+ await tick()
154
+ expect(panel().classList.contains('is-floating')).toBe(false)
155
+ expect(panel().classList.contains('is-maximized')).toBe(false)
156
+ } finally {
157
+ destroy()
158
+ }
159
+ })
160
+
161
+ it('adds a second chart, shows a tab strip, and persists both charts in view state', async () => {
162
+ const { api, target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
163
+ try {
164
+ await tick()
165
+ // One chart, no tab strip yet.
166
+ expect(target.querySelectorAll('.sv-grid-chart-tab').length).toBe(0)
167
+ // Add a chart.
168
+ const add = target.querySelector<HTMLButtonElement>('[aria-label="Add chart"]')
169
+ expect(add).toBeTruthy()
170
+ add!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
171
+ await tick()
172
+ // Now two tabs; the second is active.
173
+ const tabs = target.querySelectorAll('.sv-grid-chart-tab')
174
+ expect(tabs.length).toBe(2)
175
+ expect(tabs[1]!.classList.contains('is-active')).toBe(true)
176
+ // View state carries both charts + the active index.
177
+ const state = api.getState() as any
178
+ expect(state.charts.length).toBe(2)
179
+ expect(state.chartActive).toBe(1)
180
+ // Removing a chart drops back to a single chart (tab strip disappears).
181
+ target.querySelector<HTMLButtonElement>('.sv-grid-chart-tab.is-active .sv-grid-chart-tab-x')!
182
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }))
183
+ await tick()
184
+ expect(target.querySelectorAll('.sv-grid-chart-tab').length).toBe(0)
185
+ expect((api.getState() as any).charts.length).toBe(1)
186
+ } finally {
187
+ destroy()
188
+ }
189
+ })
190
+
191
+ it('keeps each chart\'s own type when switching tabs', async () => {
192
+ const { api, target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
193
+ try {
194
+ await tick()
195
+ // Chart 1 -> line.
196
+ const typeSel = () => target.querySelector<HTMLSelectElement>('.sv-grid-chart-controls select')!
197
+ typeSel().value = 'line'
198
+ typeSel().dispatchEvent(new Event('change', { bubbles: true }))
199
+ await tick()
200
+ expect(api.getChartSpec()!.type).toBe('line')
201
+ // Add Chart 2 (defaults to bar).
202
+ target.querySelector<HTMLButtonElement>('[aria-label="Add chart"]')!
203
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }))
204
+ await tick()
205
+ expect(api.getChartSpec()!.type).toBe('bar')
206
+ // Switch back to Chart 1 -> still line.
207
+ target.querySelectorAll<HTMLButtonElement>('.sv-grid-chart-tab-label')[0]!
208
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }))
209
+ await tick()
210
+ expect(api.getChartSpec()!.type).toBe('line')
211
+ } finally {
212
+ destroy()
213
+ }
214
+ })
215
+
216
+ it('configureChart applies a config to the active chart (resolving field names)', async () => {
217
+ const { api, destroy } = await mountGrid({ charting: { defaultOpen: true } })
218
+ try {
219
+ api.configureChart({ type: 'line', dimension: 'team', measure: 'salary', reduce: 'avg' })
220
+ await tick()
221
+ const spec = api.getChartSpec()
222
+ expect(spec!.type).toBe('line')
223
+ // salary aggregated by team -> one category per distinct team.
224
+ expect(spec!.categories.length).toBeGreaterThan(0)
225
+ } finally {
226
+ destroy()
227
+ }
228
+ })
229
+
230
+ it('shows an AI button only when a chart-AI handler is registered, and applies its result', async () => {
231
+ const { api, target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
232
+ try {
233
+ await tick()
234
+ // No handler -> no AI button.
235
+ expect(target.querySelector('[aria-label="Chart with AI"]')).toBeFalsy()
236
+ // Register a deterministic handler (stands in for enterprise's aiChart).
237
+ api.setChartAiHandler(async () => ({
238
+ type: 'line',
239
+ dimension: 'team',
240
+ series: null,
241
+ measure: 'salary',
242
+ reduce: 'avg',
243
+ stacked: false,
244
+ rationale: 'line of avg salary by team',
245
+ }))
246
+ await tick()
247
+ const aiBtn = target.querySelector<HTMLButtonElement>('[aria-label="Chart with AI"]')
248
+ expect(aiBtn).toBeTruthy()
249
+ // Open the prompt row, type a query, submit.
250
+ aiBtn!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
251
+ await tick()
252
+ const input = target.querySelector<HTMLInputElement>('.sv-grid-chart-ai-input')!
253
+ input.value = 'average salary by team as a line'
254
+ input.dispatchEvent(new Event('input', { bubbles: true }))
255
+ const form = target.querySelector<HTMLFormElement>('.sv-grid-chart-ai-row')!
256
+ form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
257
+ // Let the async handler resolve.
258
+ await new Promise((r) => setTimeout(r, 0))
259
+ await tick()
260
+ expect(api.getChartSpec()!.type).toBe('line')
261
+ } finally {
262
+ destroy()
263
+ }
264
+ })
265
+
266
+ it('toggles a logarithmic value axis (configureChart + panel toggle present)', async () => {
267
+ const { api, target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
268
+ try {
269
+ api.configureChart({ dimension: 'team', measure: 'salary' })
270
+ await tick()
271
+ expect(api.getChartSpec()!.yScale).not.toBe('log')
272
+ api.configureChart({ logScale: true })
273
+ await tick()
274
+ expect(api.getChartSpec()!.yScale).toBe('log')
275
+ const labels = [...target.querySelectorAll('.sv-grid-chart-toggle')].map((l) => l.textContent?.trim())
276
+ expect(labels).toContain('Log scale')
277
+ } finally {
278
+ destroy()
279
+ }
280
+ })
281
+
282
+ it('offers a date axis only when the group-by column is date-like', async () => {
283
+ // Non-date dimension -> no Date axis toggle.
284
+ const a = await mountGrid({ charting: { defaultOpen: true } })
285
+ try {
286
+ await tick()
287
+ const labels = [...a.target.querySelectorAll('.sv-grid-chart-toggle')].map((l) => l.textContent?.trim())
288
+ expect(labels).not.toContain('Date axis')
289
+ } finally {
290
+ a.destroy()
291
+ }
292
+ // Date dimension -> Date axis toggle appears and drives xType: 'time'.
293
+ const dateColumns = [
294
+ { field: 'day', header: 'Day', width: 120, cellDataType: 'date' },
295
+ { field: 'channel', header: 'Channel', width: 120 },
296
+ { field: 'signups', header: 'Signups', width: 100, cellDataType: 'number' },
297
+ ]
298
+ const dateData = [
299
+ { id: 1, day: '2026-01-01', channel: 'Organic', signups: 10 },
300
+ { id: 2, day: '2026-01-02', channel: 'Organic', signups: 20 },
301
+ { id: 3, day: '2026-01-03', channel: 'Paid', signups: 30 },
302
+ ]
303
+ const b = await mountGrid({
304
+ data: dateData,
305
+ columns: dateColumns,
306
+ charting: { defaultOpen: true, dimension: 'day', measures: 'signups' },
307
+ })
308
+ try {
309
+ await tick()
310
+ const labels = [...b.target.querySelectorAll('.sv-grid-chart-toggle')].map((l) => l.textContent?.trim())
311
+ expect(labels).toContain('Date axis')
312
+ b.api.configureChart({ timeAxis: true })
313
+ await tick()
314
+ expect(b.api.getChartSpec()!.xType).toBe('time')
315
+ } finally {
316
+ b.destroy()
317
+ }
318
+ })
319
+
320
+ it('serializes chart data to CSV and shows an Export menu (PNG/SVG/CSV/Copy)', async () => {
321
+ const { api, target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
322
+ try {
323
+ api.configureChart({ dimension: 'team', series: 'name', measure: 'salary' })
324
+ await tick()
325
+ const csv = chartSpecToCsv(api.getChartSpec()!)
326
+ const [header, ...rows] = csv.split('\n')
327
+ expect(header.startsWith('Category,')).toBe(true)
328
+ expect(rows.length).toBeGreaterThan(0)
329
+ // Export button + menu.
330
+ const btn = target.querySelector<HTMLButtonElement>('[aria-label="Export chart"]')
331
+ expect(btn).toBeTruthy()
332
+ btn!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
333
+ await tick()
334
+ const items = [...target.querySelectorAll('.sv-grid-chart-export-menu button')].map((b) => b.textContent)
335
+ expect(items).toEqual(['PNG image', 'SVG vector', 'CSV data', 'Copy to clipboard'])
336
+ } finally {
337
+ destroy()
338
+ }
339
+ })
340
+
341
+ it('buildChart emits a grouped category-axis tier from categoryGroups', () => {
342
+ const geo = buildChart({
343
+ type: 'bar',
344
+ categories: ['USA', 'Canada', 'Japan', 'India'],
345
+ series: [{ label: 'Rev', values: [10, 20, 30, 40] }],
346
+ categoryGroups: [{ label: 'Americas', span: 2 }, { label: 'APAC', span: 2 }],
347
+ })
348
+ expect(geo.categoryGroupTicks.map((g) => g.label)).toEqual(['Americas', 'APAC'])
349
+ // Groups tile the axis edge-to-edge (first group's right = second's left).
350
+ expect(geo.categoryGroupTicks[0]!.x1).toBe(geo.categoryGroupTicks[1]!.x0)
351
+ // Ignored when the spans don't cover every leaf.
352
+ const bad = buildChart({
353
+ type: 'bar',
354
+ categories: ['A', 'B', 'C'],
355
+ series: [{ label: 'x', values: [1, 2, 3] }],
356
+ categoryGroups: [{ label: 'G', span: 2 }],
357
+ })
358
+ expect(bad.categoryGroupTicks.length).toBe(0)
359
+ })
360
+
361
+ it('formatChartValue renders currency / percent / compact', () => {
362
+ expect(formatChartValue(1500, 'currency')).toBe('$1.5k')
363
+ expect(formatChartValue(-2_000_000, 'currency')).toBe('-$2M')
364
+ expect(formatChartValue(0.25, 'percent')).toBe('25%')
365
+ expect(formatChartValue(1500)).toBe('1.5k')
366
+ expect(formatChartValue(1500, 'number')).toBe('1.5k')
367
+ })
368
+
369
+ it('applies a value format and an auto y-axis title to the spec', async () => {
370
+ const { api, destroy } = await mountGrid({ charting: { defaultOpen: true } })
371
+ try {
372
+ api.configureChart({ dimension: 'team', measure: 'salary', reduce: 'sum', valueFormat: 'currency' })
373
+ await tick()
374
+ const spec = api.getChartSpec()!
375
+ expect(spec.valueFormat).toBe('currency')
376
+ expect(spec.yAxisTitle).toBe('Sum of Salary')
377
+ } finally {
378
+ destroy()
379
+ }
380
+ })
381
+
382
+ it('defaults the value format from the measure column format', async () => {
383
+ const cols = [
384
+ { field: 'team', header: 'Team', width: 120 },
385
+ { field: 'salary', header: 'Salary', width: 120, cellDataType: 'number', format: { type: 'currency', currency: 'USD' } },
386
+ ]
387
+ const { api, destroy } = await mountGrid({
388
+ columns: cols,
389
+ charting: { defaultOpen: true, dimension: 'team', measures: 'salary' },
390
+ })
391
+ try {
392
+ await tick()
393
+ expect(api.getChartSpec()!.valueFormat).toBe('currency')
394
+ } finally {
395
+ destroy()
396
+ }
397
+ })
398
+
399
+ it('splits into one series per distinct value of the `series` field', async () => {
400
+ const { api, destroy } = await mountGrid({ charting: { dimension: 'team', series: 'name', measures: 'age' } })
401
+ try {
402
+ const spec = api.getChartSpec()
403
+ // categories = distinct teams (4); one series per distinct name (6).
404
+ expect(spec!.series.length).toBe(6)
405
+ } finally {
406
+ destroy()
407
+ }
408
+ })
409
+
410
+ it('plots one series per measure with `measures[]`', async () => {
411
+ const { api, destroy } = await mountGrid({ charting: { dimension: 'team', measures: ['age', 'salary'] } })
412
+ try {
413
+ const spec = api.getChartSpec()
414
+ expect(spec!.series.length).toBe(2)
415
+ } finally {
416
+ destroy()
417
+ }
418
+ })
419
+
420
+ it('marks the spec stacked when config.stacked is set', async () => {
421
+ const { api, destroy } = await mountGrid({ charting: { dimension: 'team', series: 'name', measures: 'age', stacked: true } })
422
+ try {
423
+ expect(api.getChartSpec()!.stacked).toBe(true)
424
+ } finally {
425
+ destroy()
426
+ }
427
+ })
428
+
429
+ it('renders a custom `buildSpec` chart that stays live with the grid', async () => {
430
+ const { api, destroy } = await mountGrid({
431
+ charting: { defaultOpen: true, buildSpec: (rows) => ({ type: 'bar', categories: ['All'], series: [{ label: 'Count', values: [rows.length] }] }) },
432
+ })
433
+ try {
434
+ await tick()
435
+ // The custom spec reflects all displayed rows...
436
+ expect(api.getChartSpec()!.series[0]!.values[0]).toBe(people.length)
437
+ // ...and re-derives when the grid is filtered (auto-refresh through buildSpec).
438
+ api.setFacetFilter('team', ['Research'])
439
+ await tick()
440
+ expect(api.getChartSpec()!.series[0]!.values[0]).toBe(3)
441
+ } finally {
442
+ destroy()
443
+ }
444
+ })
445
+
446
+ it('maps a multi-column cell selection to dimension + split-by + measures (column-exact)', async () => {
447
+ const { api, destroy } = await mountGrid({ charting: true })
448
+ try {
449
+ // Select columns 1..3 (team, age, salary) across the first two rows:
450
+ // team -> dimension, no 2nd text col, age+salary -> measures.
451
+ api.selectCells([[0, 1, 1, 3]])
452
+ await tick()
453
+ const spec = api.getChartSpec()
454
+ // Two numeric columns in the span -> two series.
455
+ expect(spec!.series.length).toBe(2)
456
+ } finally {
457
+ destroy()
458
+ }
459
+ })
460
+
461
+ it('round-trips the chart config through getState / setState', async () => {
462
+ const a = await mountGrid({ charting: true })
463
+ try {
464
+ a.api.openChart()
465
+ a.api.setState({ ...a.api.getState(), chart: { open: true, type: 'line', dimension: 'team', series: null, measure: 'salary', reduce: 'avg', stacked: false } } as any)
466
+ await tick()
467
+ const state = a.api.getState() as any
468
+ expect(state.chart).toBeTruthy()
469
+ expect(state.chart.type).toBe('line')
470
+ expect(state.chart.reduce).toBe('avg')
471
+ const spec = a.api.getChartSpec()
472
+ expect(spec!.type).toBe('line')
473
+ } finally {
474
+ a.destroy()
475
+ }
476
+ })
477
+
478
+ it('charts server-side buckets from getAggregate and refetches on filter change', async () => {
479
+ let calls = 0
480
+ let lastFilter: any = null
481
+ const { api, destroy } = await mountGrid({
482
+ charting: {
483
+ getAggregate: async (req) => {
484
+ calls += 1
485
+ lastFilter = req.filterModel
486
+ return [
487
+ { category: 'A', value: 10 },
488
+ { category: 'B', value: 20 },
489
+ ]
490
+ },
491
+ },
492
+ })
493
+ try {
494
+ await new Promise((r) => setTimeout(r, 15))
495
+ const spec = api.getChartSpec()
496
+ expect(spec).not.toBeNull()
497
+ expect(spec!.categories).toEqual(['A', 'B'])
498
+ expect(spec!.series[0]!.values).toEqual([10, 20])
499
+ expect(calls).toBeGreaterThan(0)
500
+ // A filter change re-runs the server aggregation with the new filter.
501
+ const before = calls
502
+ api.setFacetFilter('team', ['Research'])
503
+ await new Promise((r) => setTimeout(r, 15))
504
+ expect(calls).toBeGreaterThan(before)
505
+ expect(lastFilter.facets.team).toEqual(['Research'])
506
+ } finally {
507
+ destroy()
508
+ }
509
+ })
510
+
511
+ it('cross-filters the grid when a chart category is clicked', async () => {
512
+ const { api, target, destroy } = await mountGrid({ charting: { defaultOpen: true } })
513
+ try {
514
+ await tick()
515
+ expect(api.getDisplayedRows().length).toBe(people.length)
516
+ // The full-height hit rect for the first category carries data-cat-index=0.
517
+ const hit = target.querySelector<SVGElement>('.sv-grid-chart-panel svg [data-cat-index="0"]')
518
+ expect(hit).toBeTruthy()
519
+ hit!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
520
+ await tick()
521
+ // Clicking one category (a distinct name) filters the grid to that row.
522
+ expect(api.getDisplayedRows().length).toBe(1)
523
+ } finally {
524
+ destroy()
525
+ }
526
+ })
527
+ })