@svgrid/grid 2.6.20 → 2.6.22

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 (110) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +22 -0
  3. package/dist/GridMenus.svelte +17 -12
  4. package/dist/SvGrid.controller.svelte.d.ts +14 -8
  5. package/dist/SvGrid.controller.svelte.js +214 -74
  6. package/dist/SvGrid.css +1 -1
  7. package/dist/SvGrid.svelte +112 -57
  8. package/dist/SvGrid.types.d.ts +191 -1
  9. package/dist/ai.d.ts +28 -0
  10. package/dist/ai.js +6 -0
  11. package/dist/cdn/{GridMenus-B0F9iBrG.js → GridMenus-BuoBPqxx.js} +137 -132
  12. package/dist/cdn/GridMenus-n4llxoOI.js +494 -0
  13. package/dist/cdn/column-resize-DsfNXMom.js +102 -0
  14. package/dist/cdn/row-resize-BRcimkUT.js +95 -0
  15. package/dist/cdn/{src-Cd0tearp.js → src-C9Hihx1W.js} +3497 -3487
  16. package/dist/cdn/{src-B1TdiyS8.js → src-D1lXwq1l.js} +8258 -8248
  17. package/dist/cdn/svgrid.js +10 -8
  18. package/dist/cdn/svgrid.svelte-external.js +10 -8
  19. package/dist/cdn/validate-_CDJzgIo.js +75 -0
  20. package/dist/cell-formatting.d.ts +2 -0
  21. package/dist/cell-formatting.js +2 -0
  22. package/dist/chart-export.d.ts +1 -0
  23. package/dist/chart.d.ts +31 -5
  24. package/dist/chart.js +9 -3
  25. package/dist/column-groups.js +1 -1
  26. package/dist/column-resize.d.ts +46 -0
  27. package/dist/column-resize.js +205 -0
  28. package/dist/columns.d.ts +0 -3
  29. package/dist/columns.js +0 -57
  30. package/dist/core.d.ts +216 -4
  31. package/dist/core.js +532 -119
  32. package/dist/createTree.svelte.d.ts +3 -0
  33. package/dist/createTree.svelte.js +1 -0
  34. package/dist/datetime/date-core.d.ts +2 -0
  35. package/dist/datetime/date-restrict.d.ts +1 -0
  36. package/dist/datetime/timezone.d.ts +1 -0
  37. package/dist/dock-manager-model.d.ts +3 -0
  38. package/dist/dock-manager-model.js +1 -0
  39. package/dist/dock-model.d.ts +6 -0
  40. package/dist/dock-model.js +3 -0
  41. package/dist/editor-contract.d.ts +1 -0
  42. package/dist/filtering/excel-filters.js +28 -0
  43. package/dist/group-display.d.ts +1 -1
  44. package/dist/index.d.ts +2 -1
  45. package/dist/index.js +6 -0
  46. package/dist/list-option.d.ts +1 -0
  47. package/dist/menus.js +1 -1
  48. package/dist/positioning.d.ts +2 -0
  49. package/dist/row-resize.d.ts +11 -0
  50. package/dist/row-resize.js +7 -1
  51. package/dist/scheduler-ical.d.ts +1 -0
  52. package/dist/scheduler-model.d.ts +1 -0
  53. package/dist/selection.js +9 -0
  54. package/dist/spreadsheet.d.ts +1 -1
  55. package/dist/spreadsheet.js +1 -1
  56. package/dist/summaries.js +22 -0
  57. package/dist/svgrid-wrapper.types.d.ts +5 -0
  58. package/dist/toast-store.svelte.d.ts +4 -0
  59. package/dist/validate.d.ts +50 -0
  60. package/dist/validate.js +187 -0
  61. package/package.json +4 -1
  62. package/src/GridMenus.svelte +17 -12
  63. package/src/SvGrid.controller.svelte.ts +223 -76
  64. package/src/SvGrid.css +1 -1
  65. package/src/SvGrid.svelte +112 -57
  66. package/src/SvGrid.types.ts +191 -1
  67. package/src/ai.ts +28 -0
  68. package/src/cell-formatting.ts +2 -0
  69. package/src/chart-export.ts +1 -0
  70. package/src/chart.ts +31 -5
  71. package/src/column-groups.ts +1 -1
  72. package/src/column-resize.test.ts +381 -0
  73. package/src/column-resize.ts +227 -0
  74. package/src/columns.test.ts +0 -103
  75. package/src/columns.ts +0 -58
  76. package/src/core.aggregate.test.ts +134 -0
  77. package/src/core.filter.test.ts +156 -0
  78. package/src/core.grouping.test.ts +146 -0
  79. package/src/core.row-shape.test.ts +119 -0
  80. package/src/core.rowmodel-cache.test.ts +121 -0
  81. package/src/core.sort.test.ts +293 -0
  82. package/src/core.ts +723 -119
  83. package/src/createTree.svelte.ts +3 -0
  84. package/src/datetime/date-core.ts +2 -0
  85. package/src/datetime/date-restrict.ts +1 -0
  86. package/src/datetime/timezone.ts +1 -0
  87. package/src/dock-manager-model.ts +3 -0
  88. package/src/dock-model.ts +6 -0
  89. package/src/editor-contract.ts +1 -0
  90. package/src/filtering/excel-filters.ts +30 -0
  91. package/src/filtering/normalize-fast-path.test.ts +104 -0
  92. package/src/group-display.ts +1 -1
  93. package/src/index.ts +12 -1
  94. package/src/list-option.ts +1 -0
  95. package/src/menus.ts +1 -1
  96. package/src/positioning.ts +2 -0
  97. package/src/resize-props.test.ts +361 -0
  98. package/src/row-resize.test.ts +31 -0
  99. package/src/row-resize.ts +21 -3
  100. package/src/scheduler-ical.ts +1 -0
  101. package/src/scheduler-model.ts +1 -0
  102. package/src/selection.ts +9 -0
  103. package/src/spreadsheet.ts +1 -1
  104. package/src/summaries.ts +21 -0
  105. package/src/svgrid-wrapper.types.ts +5 -0
  106. package/src/svgrid.summaries.test.ts +217 -0
  107. package/src/toast-store.svelte.ts +4 -0
  108. package/src/validate.test.ts +207 -0
  109. package/src/validate.ts +269 -0
  110. package/dist/cdn/GridMenus-IHK_l7m6.js +0 -489
@@ -424,109 +424,6 @@ describe('getColumnWidth', () => {
424
424
  })
425
425
  })
426
426
 
427
- describe('column resize lifecycle', () => {
428
- let rafCb: FrameRequestCallback | null
429
- beforeEach(() => {
430
- rafCb = null
431
- vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
432
- rafCb = cb
433
- return 1
434
- })
435
- vi.stubGlobal('cancelAnimationFrame', vi.fn())
436
- })
437
-
438
- it('startColumnResize seeds the resize state and registers listeners', () => {
439
- const ctx = makeCtx({ columnWidths: { a: 150 } })
440
- const h = createColumns(ctx)
441
- const addSpy = vi.spyOn(document, 'addEventListener')
442
- const e: any = {
443
- stopPropagation: vi.fn(),
444
- preventDefault: vi.fn(),
445
- clientX: 500,
446
- }
447
- h.startColumnResize(e, 'a')
448
- expect(ctx.resizingColumnId).toBe('a')
449
- expect(ctx.resizeStartX).toBe(500)
450
- expect(ctx.resizeStartWidth).toBe(150)
451
- expect(addSpy).toHaveBeenCalledWith('pointermove', expect.any(Function))
452
- addSpy.mockRestore()
453
- })
454
-
455
- it('onColumnResizeMove bails when no column is resizing', () => {
456
- const ctx = makeCtx({ resizingColumnId: null })
457
- const h = createColumns(ctx)
458
- h.onColumnResizeMove({ clientX: 100 } as any)
459
- expect(ctx.resizePendingWidth).toBe(0)
460
- })
461
-
462
- it('onColumnResizeMove clamps to MIN_COLUMN_WIDTH and commits on the frame', () => {
463
- const ctx = makeCtx({
464
- resizingColumnId: 'a',
465
- resizeStartX: 100,
466
- resizeStartWidth: 120,
467
- })
468
- const h = createColumns(ctx)
469
- // moving far left should clamp at MIN_COLUMN_WIDTH (40)
470
- h.onColumnResizeMove({ clientX: -1000 } as any)
471
- expect(ctx.resizePendingWidth).toBe(40)
472
- expect(rafCb).not.toBeNull()
473
- rafCb!(0)
474
- expect(ctx.columnWidths.a).toBe(40)
475
- })
476
-
477
- it('onColumnResizeMove grows the column and coalesces multiple moves into one frame', () => {
478
- const ctx = makeCtx({
479
- resizingColumnId: 'a',
480
- resizeStartX: 100,
481
- resizeStartWidth: 120,
482
- })
483
- const h = createColumns(ctx)
484
- h.onColumnResizeMove({ clientX: 150 } as any) // +50 -> 170, schedules raf
485
- const firstCb = rafCb
486
- h.onColumnResizeMove({ clientX: 200 } as any) // +100 -> 220, raf already pending
487
- expect(ctx.resizePendingWidth).toBe(220)
488
- expect(rafCb).toBe(firstCb) // not rescheduled
489
- rafCb!(0)
490
- expect(ctx.columnWidths.a).toBe(220)
491
- })
492
-
493
- it('onColumnResizeMove skips the commit if the column stopped resizing mid-frame', () => {
494
- const ctx = makeCtx({
495
- resizingColumnId: 'a',
496
- resizeStartX: 100,
497
- resizeStartWidth: 120,
498
- })
499
- const h = createColumns(ctx)
500
- h.onColumnResizeMove({ clientX: 150 } as any)
501
- ctx.resizingColumnId = null // resize ended before the frame ran
502
- rafCb!(0)
503
- expect(ctx.columnWidths.a).toBeUndefined()
504
- })
505
-
506
- it('endColumnResize commits the final pending width and tears down listeners', () => {
507
- const ctx = makeCtx({
508
- resizingColumnId: 'a',
509
- resizePendingWidth: 222,
510
- resizeRaf: 9,
511
- })
512
- const h = createColumns(ctx)
513
- const removeSpy = vi.spyOn(document, 'removeEventListener')
514
- h.endColumnResize()
515
- expect(ctx.columnWidths.a).toBe(222)
516
- expect(ctx.resizingColumnId).toBeNull()
517
- expect(ctx.resizeRaf).toBeNull()
518
- expect(removeSpy).toHaveBeenCalledWith('pointermove', expect.any(Function))
519
- removeSpy.mockRestore()
520
- })
521
-
522
- it('endColumnResize is safe when nothing was resizing', () => {
523
- const ctx = makeCtx()
524
- const h = createColumns(ctx)
525
- expect(() => h.endColumnResize()).not.toThrow()
526
- expect(ctx.columnWidths).toEqual({})
527
- })
528
- })
529
-
530
427
  describe('measureText', () => {
531
428
  it('returns 0 for empty text', () => {
532
429
  const h = createColumns(makeCtx())
package/src/columns.ts CHANGED
@@ -167,61 +167,6 @@ export function createColumns<
167
167
  return getColumnBaseWidth(columnId);
168
168
  }
169
169
 
170
- function startColumnResize(event: PointerEvent, columnId: string) {
171
- event.stopPropagation();
172
- event.preventDefault();
173
- ctx.resizingColumnId = columnId;
174
- ctx.resizeStartX = event.clientX;
175
- ctx.resizeStartWidth = getColumnWidth(columnId);
176
- // Capture the pointer so the drag keeps tracking when it leaves the 4px
177
- // handle - without this, touch (and fast mouse) drags drop mid-resize (#59).
178
- try {
179
- (event.currentTarget as HTMLElement | null)?.setPointerCapture?.(event.pointerId);
180
- } catch { /* capture is best-effort */ }
181
- document.addEventListener("pointermove", onColumnResizeMove);
182
- document.addEventListener("pointerup", endColumnResize);
183
- document.addEventListener("pointercancel", endColumnResize);
184
- }
185
-
186
- function onColumnResizeMove(event: PointerEvent) {
187
- if (!ctx.resizingColumnId) return;
188
- // Coalesce updates onto the animation frame: pointermove can fire many
189
- // times per frame, and each $state mutation triggers a full reactive
190
- // recompute of the column-layout pipeline. Without rAF coalescing the
191
- // grid stutters during the drag.
192
- ctx.resizePendingWidth = Math.max(
193
- ctx.MIN_COLUMN_WIDTH,
194
- ctx.resizeStartWidth + (event.clientX - ctx.resizeStartX),
195
- );
196
- if (ctx.resizeRaf !== null) return;
197
- ctx.resizeRaf = requestAnimationFrame(() => {
198
- ctx.resizeRaf = null;
199
- if (!ctx.resizingColumnId) return;
200
- ctx.columnWidths = {
201
- ...ctx.columnWidths,
202
- [ctx.resizingColumnId]: ctx.resizePendingWidth,
203
- };
204
- });
205
- }
206
-
207
- function endColumnResize() {
208
- if (ctx.resizeRaf !== null) {
209
- cancelAnimationFrame(ctx.resizeRaf);
210
- ctx.resizeRaf = null;
211
- }
212
- if (ctx.resizingColumnId && ctx.resizePendingWidth) {
213
- // Make sure the final width is committed even if the last rAF was
214
- // canceled mid-flight.
215
- ctx.columnWidths = {
216
- ...ctx.columnWidths,
217
- [ctx.resizingColumnId]: ctx.resizePendingWidth,
218
- };
219
- }
220
- ctx.resizingColumnId = null;
221
- document.removeEventListener("pointermove", onColumnResizeMove);
222
- document.removeEventListener("pointerup", endColumnResize);
223
- document.removeEventListener("pointercancel", endColumnResize);
224
- }
225
170
 
226
171
  function measureText(text: string, font: string): number {
227
172
  if (!text) return 0;
@@ -304,9 +249,6 @@ export function createColumns<
304
249
  toggleGroupInPanel,
305
250
  getColumnBaseWidth,
306
251
  getColumnWidth,
307
- startColumnResize,
308
- onColumnResizeMove,
309
- endColumnResize,
310
252
  measureText,
311
253
  autosizeColumn,
312
254
  autosizeAllColumns,
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Equivalence tests for `applyGroupAggregate`.
3
+ *
4
+ * Grouping 100k rows by two columns with three aggregators took 213ms, of which
5
+ * ~132ms was this function: each aggregated column of each group allocated a
6
+ * `raw` array, then a mapped array, then a filtered one, and `min`/`max`/
7
+ * `extent` finished by spreading the whole group into `Math.min(...)`.
8
+ * Measured by varying the aggregator count - 9 aggregated columns cost 823ms
9
+ * against 81ms for none.
10
+ *
11
+ * The rewrite is a single pass with no intermediate arrays. `reference` below
12
+ * is the original, verbatim, and every case asserts the two agree - including
13
+ * the awkward ones: empty groups, all-non-numeric values, -0, and the
14
+ * float-addition ORDER, since `reduce` and a loop must accumulate identically
15
+ * for the sums to match bit for bit.
16
+ *
17
+ * The spread also had a latent failure mode this fixes: `Math.min(...nums)`
18
+ * throws RangeError once a group is large enough to exhaust the argument
19
+ * stack, so `min` on a big single-bucket group could crash the grid. The last
20
+ * test pins that.
21
+ */
22
+ import { describe, expect, it } from 'vitest'
23
+ import { applyGroupAggregate, type GroupAggregator, type Row } from './core'
24
+
25
+ /** Minimal Row stand-in: the function only ever calls getCellValueByColumnId. */
26
+ function rowsOf(values: unknown[]): Array<Row<Record<string, unknown>>> {
27
+ return values.map(
28
+ (v, i) =>
29
+ ({
30
+ id: String(i),
31
+ index: i,
32
+ original: { v },
33
+ depth: 0,
34
+ getCanExpand: () => false,
35
+ getIsExpanded: () => false,
36
+ toggleExpanded: () => {},
37
+ getIsSelected: () => false,
38
+ toggleSelected: () => {},
39
+ getAllCells: () => [],
40
+ getCellValueByColumnId: () => v,
41
+ }) as unknown as Row<Record<string, unknown>>,
42
+ )
43
+ }
44
+
45
+ /** The original implementation, verbatim, as the oracle. */
46
+ function reference<TData extends Record<string, unknown>>(
47
+ agg: GroupAggregator<TData>,
48
+ columnId: string,
49
+ rows: ReadonlyArray<Row<TData>>,
50
+ ): unknown {
51
+ const raw = rows.map((r) => r.getCellValueByColumnId(columnId))
52
+ if (typeof agg === 'function') {
53
+ const nums = raw.map((v) => Number(v)).filter((n) => Number.isFinite(n))
54
+ return agg(nums, rows.map((r) => r.original))
55
+ }
56
+ if (agg === 'count') return rows.length
57
+ if (agg === 'countDistinct') return new Set(raw.map((v) => String(v ?? ''))).size
58
+ if (agg === 'first') return raw[0]
59
+ const nums = raw.map((v) => Number(v)).filter((n) => Number.isFinite(n))
60
+ if (!nums.length) return undefined
61
+ switch (agg) {
62
+ case 'sum':
63
+ return nums.reduce((a, b) => a + b, 0)
64
+ case 'avg':
65
+ return nums.reduce((a, b) => a + b, 0) / nums.length
66
+ case 'min':
67
+ return Math.min(...nums)
68
+ case 'max':
69
+ return Math.max(...nums)
70
+ case 'extent':
71
+ return `${Math.min(...nums)} – ${Math.max(...nums)}`
72
+ default:
73
+ return undefined
74
+ }
75
+ }
76
+
77
+ const AGGS: GroupAggregator[] = ['sum', 'avg', 'min', 'max', 'count', 'countDistinct', 'extent', 'first']
78
+
79
+ const DATASETS: Array<[string, unknown[]]> = [
80
+ ['empty', []],
81
+ ['single value', [5]],
82
+ ['plain integers', [3, 1, 2, 10, -4]],
83
+ ['floats that expose accumulation order', [0.1, 0.2, 0.3, 0.7, 1e-16, 1e16]],
84
+ ['all non-numeric', ['a', 'b', {}, [], true]],
85
+ ['mixed numeric and not', [1, 'x', 2, null, 3, undefined, NaN, Infinity, -Infinity]],
86
+ ['nulls and undefined only', [null, undefined]],
87
+ ['numeric strings', ['1', '2', '10']],
88
+ ['duplicates for countDistinct', ['a', 'a', 'b', null, undefined, '']],
89
+ ['negative zero', [-0, 0, 1]],
90
+ ['very large and small', [Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER, 0]],
91
+ ['booleans', [true, false, true]],
92
+ ]
93
+
94
+ describe('applyGroupAggregate - equivalence with the original', () => {
95
+ for (const [name, values] of DATASETS) {
96
+ for (const agg of AGGS) {
97
+ it(`${agg} over ${name}`, () => {
98
+ const rows = rowsOf(values)
99
+ const expected = reference(agg, 'v', rows)
100
+ const actual = applyGroupAggregate(agg, 'v', rows)
101
+ // Object.is so NaN matches NaN and -0 does not silently pass as 0.
102
+ expect(Object.is(actual, expected) || actual === expected).toBe(true)
103
+ })
104
+ }
105
+ }
106
+
107
+ it('passes finite numbers and originals to a custom aggregator, unchanged', () => {
108
+ const seen: Array<{ nums: number[]; count: number }> = []
109
+ const custom: GroupAggregator = (nums, originals) => {
110
+ seen.push({ nums: [...nums], count: originals.length })
111
+ return nums.length
112
+ }
113
+ const rows = rowsOf([1, 'x', 2, null, NaN, 3])
114
+ const expected = reference(custom, 'v', rows)
115
+ const actual = applyGroupAggregate(custom, 'v', rows)
116
+ expect(actual).toBe(expected)
117
+ // Both calls saw identical arguments.
118
+ expect(seen[0]).toEqual(seen[1])
119
+ // `null` is included: Number(null) is 0, which is finite. `'x'` and NaN are
120
+ // not. Worth pinning - it is the kind of coercion a rewrite silently drops.
121
+ expect(seen[0]!.nums).toEqual([1, 2, 0, 3])
122
+ expect(seen[0]!.count).toBe(6)
123
+ })
124
+
125
+ it('handles a group larger than the argument-spread limit', () => {
126
+ // The original did `Math.min(...nums)`, which throws RangeError once the
127
+ // group exceeds the engine's argument cap. A single bucket holding this
128
+ // many rows is ordinary on a large grid grouped by a low-cardinality field.
129
+ const rows = rowsOf(Array.from({ length: 200_000 }, (_, i) => i))
130
+ expect(applyGroupAggregate('min', 'v', rows)).toBe(0)
131
+ expect(applyGroupAggregate('max', 'v', rows)).toBe(199_999)
132
+ expect(applyGroupAggregate('extent', 'v', rows)).toBe('0 – 199999')
133
+ })
134
+ })
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Equivalence + work-budget tests for `createFilteredRowModel`.
3
+ *
4
+ * The filter path used to read a cell with
5
+ * `row.getAllCells().find((c) => c.column.id === id)?.getValue()`. That builds
6
+ * and caches the row's ENTIRE `Cell[]` just to read one field, which defeats
7
+ * the lazy-cell design the row factory goes out of its way to provide - a
8
+ * one-operator filter over 100k rows materialised 100,000 cell arrays
9
+ * (measured; `pnpm bench --case=filter-1op`).
10
+ *
11
+ * `getCellValueByColumnId` reads the same `cachedValues` array those cells read
12
+ * from, so the swap is a pure win - but "same array" is a claim about today's
13
+ * implementation, so the equivalence half of this file pins the observable
14
+ * behaviour rather than trusting it.
15
+ */
16
+ import { describe, expect, it } from 'vitest'
17
+ import {
18
+ createCoreRowModel,
19
+ createFilteredRowModel,
20
+ createSvGridCore,
21
+ filterFns,
22
+ tableFeatures,
23
+ type ColumnDef,
24
+ type ColumnFiltersState,
25
+ } from './core'
26
+
27
+ type Row = Record<string, unknown>
28
+
29
+ const COLUMNS = [
30
+ { field: 'text' },
31
+ { field: 'num' },
32
+ { field: 'flag' },
33
+ // A computed column: `fieldFn` rather than `field`, to prove the value path
34
+ // is the same one the cell objects use.
35
+ { field: 'derived', fieldFn: (r: Row) => `${String(r.text).toUpperCase()}!` },
36
+ ]
37
+
38
+ /** The original implementation, verbatim, as the oracle. */
39
+ function referenceFilter(rows: Row[], columns: typeof COLUMNS, filters: ColumnFiltersState): Row[] {
40
+ const value = (row: Row, id: string) => {
41
+ const col = columns.find((c) => c.field === id)
42
+ if (!col) return undefined
43
+ return col.fieldFn ? col.fieldFn(row) : row[col.field]
44
+ }
45
+ return rows.filter((row) =>
46
+ filters.every((filter) => {
47
+ const fn = filter.fn ? filterFns[filter.fn] : filterFns.includesString
48
+ return fn(value(row, filter.id), filter.value as never)
49
+ }),
50
+ )
51
+ }
52
+
53
+ function actualFilter(rows: Row[], filters: ColumnFiltersState): Row[] {
54
+ const grid = createSvGridCore({
55
+ _features: tableFeatures({}),
56
+ _rowModels: {
57
+ coreRowModel: createCoreRowModel(),
58
+ filteredRowModel: createFilteredRowModel(),
59
+ },
60
+ columns: COLUMNS as unknown as Array<ColumnDef<ReturnType<typeof tableFeatures>, Row>>,
61
+ data: rows,
62
+ state: { columnFilters: filters },
63
+ })
64
+ return grid.getRowModel().rows.map((r) => r.original as Row)
65
+ }
66
+
67
+ const ROWS: Row[] = [
68
+ { text: 'banana', num: 2, flag: true },
69
+ { text: 'Apple', num: 10, flag: false },
70
+ { text: 'apple', num: -3, flag: true },
71
+ { text: null, num: null, flag: null },
72
+ { text: undefined, num: undefined, flag: undefined },
73
+ { text: '', num: 0, flag: '' },
74
+ { text: 'APPLE pie', num: NaN, flag: 'yes' },
75
+ ]
76
+
77
+ describe('createFilteredRowModel - equivalence with the original', () => {
78
+ const cases: Array<[string, ColumnFiltersState]> = [
79
+ ['no filters', []],
80
+ ['substring, case-insensitive', [{ id: 'text', value: 'app' }]],
81
+ ['substring matching nothing', [{ id: 'text', value: 'zzz' }]],
82
+ ['empty needle matches everything', [{ id: 'text', value: '' }]],
83
+ ['equals operator', [{ id: 'num', value: 10, fn: 'equals' }]],
84
+ ['equals against null', [{ id: 'num', value: null, fn: 'equals' }]],
85
+ ['two filters ANDed', [{ id: 'text', value: 'a' }, { id: 'flag', value: 'true' }]],
86
+ ['unknown column id', [{ id: 'nope', value: 'x' }]],
87
+ ['computed column via fieldFn', [{ id: 'derived', value: 'APPLE' }]],
88
+ ['filter on undefined values', [{ id: 'flag', value: 'undefined' }]],
89
+ ]
90
+
91
+ for (const [name, filters] of cases) {
92
+ it(`matches: ${name}`, () => {
93
+ const actual = actualFilter(ROWS, filters)
94
+ const expected = referenceFilter(ROWS, COLUMNS, filters)
95
+ expect(actual.length).toBe(expected.length)
96
+ // Identity, so row order and object identity are both checked.
97
+ for (let i = 0; i < actual.length; i++) expect(actual[i]).toBe(expected[i])
98
+ })
99
+ }
100
+ })
101
+
102
+ describe('createFilteredRowModel - work budget', () => {
103
+ /**
104
+ * Count how many rows materialise their full `Cell[]` during filtering.
105
+ *
106
+ * Wrapping each row in a proxy that tallies `getAllCells` is the same
107
+ * technique tools/bench uses, kept in-process here so the invariant is
108
+ * enforced by the unit suite rather than only by the bench.
109
+ */
110
+ function countCellMaterialisations(rowCount: number, filters: ColumnFiltersState): number {
111
+ const rows: Row[] = Array.from({ length: rowCount }, (_, i) => ({
112
+ text: `row-${i % 7}`,
113
+ num: i,
114
+ flag: i % 2 === 0,
115
+ }))
116
+ let calls = 0
117
+ const grid = createSvGridCore({
118
+ _features: tableFeatures({}),
119
+ _rowModels: {
120
+ coreRowModel: createCoreRowModel(),
121
+ filteredRowModel: (args) =>
122
+ createFilteredRowModel<Row>()({
123
+ ...args,
124
+ rows: args.rows.map(
125
+ (row) =>
126
+ new Proxy(row, {
127
+ get(obj, prop, recv) {
128
+ if (prop === 'getAllCells') calls++
129
+ return Reflect.get(obj, prop, recv)
130
+ },
131
+ }) as typeof row,
132
+ ),
133
+ }),
134
+ },
135
+ columns: COLUMNS as unknown as Array<ColumnDef<ReturnType<typeof tableFeatures>, Row>>,
136
+ data: rows,
137
+ state: { columnFilters: filters },
138
+ })
139
+ grid.getRowModel()
140
+ return calls
141
+ }
142
+
143
+ it('never materialises a row\'s cell array to read one field', () => {
144
+ expect(countCellMaterialisations(2_000, [{ id: 'text', value: 'row-1' }])).toBe(0)
145
+ })
146
+
147
+ it('stays at zero with several filters', () => {
148
+ expect(
149
+ countCellMaterialisations(2_000, [
150
+ { id: 'text', value: 'row' },
151
+ { id: 'num', value: '1' },
152
+ { id: 'flag', value: 'true' },
153
+ ]),
154
+ ).toBe(0)
155
+ })
156
+ })
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Grouping: the ancestor short-circuit in `resolveColumnValue`.
3
+ *
4
+ * A group row shows, for each non-aggregated column, the value its children
5
+ * agree on - or `undefined` when they disagree. That used to be found by
6
+ * scanning every child, even for a column an ANCESTOR level had already grouped
7
+ * by, where the answer is fixed by construction. On a 100k x 9 two-level group
8
+ * that was ~100,000 reads for a value already in hand.
9
+ *
10
+ * The shortcut has one genuinely sharp edge, which is what most of this file is
11
+ * about: buckets are keyed by `String(value ?? '')`, so `null`, `undefined` and
12
+ * `''` all land in the SAME bucket. A scan of that bucket reports disagreement,
13
+ * so the shortcut has to report disagreement too rather than picking whichever
14
+ * raw value happened to arrive first.
15
+ */
16
+ import { describe, expect, it } from 'vitest'
17
+ import {
18
+ createCoreRowModel,
19
+ createGroupedRowModel,
20
+ createSvGridCore,
21
+ columnGroupingFeature,
22
+ tableFeatures,
23
+ type ColumnDef,
24
+ type Row,
25
+ } from './core'
26
+
27
+ type Data = Record<string, unknown>
28
+
29
+ function grouped(data: Data[], fields: string[], grouping: string[]) {
30
+ const grid = createSvGridCore({
31
+ _features: tableFeatures({ columnGroupingFeature }),
32
+ _rowModels: { coreRowModel: createCoreRowModel(), groupedRowModel: createGroupedRowModel() },
33
+ columns: fields.map((f) => ({ field: f })) as unknown as Array<
34
+ ColumnDef<ReturnType<typeof tableFeatures>, Data>
35
+ >,
36
+ data,
37
+ state: { grouping },
38
+ onGroupingChange: () => {},
39
+ })
40
+ return grid.getRowModel().rows
41
+ }
42
+
43
+ /** Walk to the group rows at a given depth. */
44
+ function atDepth(rows: Array<Row<Data>>, depth: number): Array<Row<Data>> {
45
+ const out: Array<Row<Data>> = []
46
+ const visit = (rs: Array<Row<Data>>) => {
47
+ for (const r of rs) {
48
+ if (r.depth === depth) out.push(r)
49
+ if (r.subRows?.length) visit(r.subRows as Array<Row<Data>>)
50
+ }
51
+ }
52
+ visit(rows)
53
+ return out
54
+ }
55
+
56
+ describe('createGroupedRowModel - ancestor value resolution', () => {
57
+ const FIELDS = ['region', 'status', 'owner', 'amount']
58
+
59
+ it('a second-level group still reports the first level value', () => {
60
+ const data: Data[] = [
61
+ { region: 'EMEA', status: 'open', owner: 'ada', amount: 1 },
62
+ { region: 'EMEA', status: 'open', owner: 'ada', amount: 2 },
63
+ { region: 'EMEA', status: 'shut', owner: 'bob', amount: 3 },
64
+ { region: 'APAC', status: 'open', owner: 'cy', amount: 4 },
65
+ ]
66
+ const inner = atDepth(grouped(data, FIELDS, ['region', 'status']), 1)
67
+ expect(inner.length).toBe(3)
68
+ for (const g of inner) {
69
+ // `region` is fixed by the ancestor bucket, so every inner group must
70
+ // report it rather than undefined.
71
+ expect(['EMEA', 'APAC']).toContain(g.getCellValueByColumnId('region'))
72
+ }
73
+ // And the columns that genuinely vary still resolve the old way.
74
+ const emeaOpen = inner.find((g) => g.getCellValueByColumnId('status') === 'open')!
75
+ expect(emeaOpen.getCellValueByColumnId('owner')).toBe('ada')
76
+ })
77
+
78
+ it('reports disagreement when a bucket mixed null, undefined and empty string', () => {
79
+ // All three key to '' and share one bucket. A scan would find they disagree,
80
+ // so the shortcut must not report whichever arrived first.
81
+ const data: Data[] = [
82
+ { region: null, status: 'x', owner: 'a', amount: 1 },
83
+ { region: undefined, status: 'y', owner: 'b', amount: 2 },
84
+ { region: '', status: 'z', owner: 'c', amount: 3 },
85
+ ]
86
+ const inner = atDepth(grouped(data, FIELDS, ['region', 'status']), 1)
87
+ expect(inner.length).toBe(3)
88
+ for (const g of inner) {
89
+ // Each inner bucket holds exactly one row, so `region` is whatever that
90
+ // row had - not a value borrowed from a sibling.
91
+ const status = g.getCellValueByColumnId('status')
92
+ const expected = data.find((d) => d.status === status)!.region
93
+ expect(g.getCellValueByColumnId('region')).toBe(expected)
94
+ }
95
+ })
96
+
97
+ it('a mixed ancestor bucket resolves to undefined at the deeper level', () => {
98
+ // One inner bucket spanning rows whose raw region values differ but key the
99
+ // same. `status` is identical so they stay together at level two.
100
+ const data: Data[] = [
101
+ { region: null, status: 'same', owner: 'a', amount: 1 },
102
+ { region: '', status: 'same', owner: 'a', amount: 2 },
103
+ ]
104
+ const inner = atDepth(grouped(data, FIELDS, ['region', 'status']), 1)
105
+ expect(inner.length).toBe(1)
106
+ // A scan of [null, ''] disagrees, so this must be undefined.
107
+ expect(inner[0]!.getCellValueByColumnId('region')).toBeUndefined()
108
+ })
109
+
110
+ it('preserves the raw type of an ancestor value rather than its bucket key', () => {
111
+ // Buckets are keyed by String(value), so a numeric grouping column would
112
+ // report '2024' instead of 2024 if the shortcut returned the key.
113
+ const data: Data[] = [
114
+ { region: 2024, status: 'a', owner: 'x', amount: 1 },
115
+ { region: 2024, status: 'b', owner: 'y', amount: 2 },
116
+ ]
117
+ const inner = atDepth(grouped(data, FIELDS, ['region', 'status']), 1)
118
+ expect(inner.length).toBe(2)
119
+ for (const g of inner) {
120
+ expect(g.getCellValueByColumnId('region')).toBe(2024)
121
+ }
122
+ })
123
+
124
+ it('handles three levels', () => {
125
+ const data: Data[] = [
126
+ { region: 'EMEA', status: 'open', owner: 'ada', amount: 1 },
127
+ { region: 'EMEA', status: 'open', owner: 'ada', amount: 2 },
128
+ { region: 'EMEA', status: 'open', owner: 'bob', amount: 3 },
129
+ ]
130
+ const deepest = atDepth(grouped(data, FIELDS, ['region', 'status', 'owner']), 2)
131
+ expect(deepest.length).toBe(2)
132
+ for (const g of deepest) {
133
+ expect(g.getCellValueByColumnId('region')).toBe('EMEA')
134
+ expect(g.getCellValueByColumnId('status')).toBe('open')
135
+ }
136
+ })
137
+
138
+ it('still returns undefined for a non-grouping column whose children disagree', () => {
139
+ const data: Data[] = [
140
+ { region: 'EMEA', status: 'open', owner: 'ada', amount: 1 },
141
+ { region: 'EMEA', status: 'open', owner: 'bob', amount: 2 },
142
+ ]
143
+ const inner = atDepth(grouped(data, FIELDS, ['region', 'status']), 1)
144
+ expect(inner[0]!.getCellValueByColumnId('owner')).toBeUndefined()
145
+ })
146
+ })