@svgrid/grid 1.0.2 → 1.1.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 (216) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +137 -39
  3. package/dist/GridFooter.svelte +164 -0
  4. package/dist/GridFooter.svelte.d.ts +29 -0
  5. package/dist/GridMenus.svelte +648 -0
  6. package/dist/GridMenus.svelte.d.ts +31 -0
  7. package/dist/SvGrid.controller.svelte.d.ts +472 -0
  8. package/dist/SvGrid.controller.svelte.js +1917 -0
  9. package/dist/SvGrid.css +2012 -0
  10. package/dist/SvGrid.helpers.d.ts +35 -0
  11. package/dist/SvGrid.helpers.js +160 -0
  12. package/dist/SvGrid.helpers.test.d.ts +1 -0
  13. package/dist/SvGrid.helpers.test.js +298 -0
  14. package/dist/SvGrid.svelte +2346 -8742
  15. package/dist/SvGrid.svelte.d.ts +4 -357
  16. package/dist/SvGrid.types.d.ts +523 -0
  17. package/dist/SvGrid.types.js +1 -0
  18. package/dist/SvGridChart.svelte +1060 -23
  19. package/dist/SvGridChart.svelte.d.ts +17 -0
  20. package/dist/aligned-grids.d.ts +6 -0
  21. package/dist/aligned-grids.js +84 -0
  22. package/dist/aligned-grids.test.d.ts +1 -0
  23. package/dist/aligned-grids.test.js +75 -0
  24. package/dist/build-api.coverage.test.d.ts +20 -0
  25. package/dist/build-api.coverage.test.js +505 -0
  26. package/dist/build-api.d.ts +5 -0
  27. package/dist/build-api.js +557 -0
  28. package/dist/cell-render.d.ts +15 -0
  29. package/dist/cell-render.js +246 -0
  30. package/dist/cell-render.test.d.ts +1 -0
  31. package/dist/cell-render.test.js +338 -0
  32. package/dist/cell-values.d.ts +28 -0
  33. package/dist/cell-values.js +89 -0
  34. package/dist/chart-export.test.d.ts +1 -0
  35. package/dist/chart-export.test.js +302 -0
  36. package/dist/chart.coverage.test.d.ts +1 -0
  37. package/dist/chart.coverage.test.js +748 -0
  38. package/dist/chart.d.ts +370 -3
  39. package/dist/chart.js +1135 -42
  40. package/dist/clipboard.d.ts +15 -0
  41. package/dist/clipboard.js +420 -0
  42. package/dist/clipboard.test.d.ts +1 -0
  43. package/dist/clipboard.test.js +700 -0
  44. package/dist/collaboration.coverage.test.d.ts +1 -0
  45. package/dist/collaboration.coverage.test.js +200 -0
  46. package/dist/column-groups.d.ts +19 -0
  47. package/dist/column-groups.js +62 -0
  48. package/dist/column-groups.test.d.ts +1 -0
  49. package/dist/column-groups.test.js +56 -0
  50. package/dist/column-types.d.ts +10 -0
  51. package/dist/column-types.js +63 -0
  52. package/dist/column-types.test.d.ts +1 -0
  53. package/dist/column-types.test.js +62 -0
  54. package/dist/columns.d.ts +30 -0
  55. package/dist/columns.js +277 -0
  56. package/dist/columns.test.d.ts +1 -0
  57. package/dist/columns.test.js +625 -0
  58. package/dist/core.d.ts +86 -1
  59. package/dist/css.d.ts +3 -0
  60. package/dist/editing.d.ts +31 -0
  61. package/dist/editing.js +529 -0
  62. package/dist/editing.test.d.ts +1 -0
  63. package/dist/editing.test.js +732 -0
  64. package/dist/editors/cell-editors.coverage.test.d.ts +1 -0
  65. package/dist/editors/cell-editors.coverage.test.js +139 -0
  66. package/dist/editors/cell-editors.d.ts +1 -1
  67. package/dist/facet-buckets.d.ts +13 -0
  68. package/dist/facet-buckets.js +54 -0
  69. package/dist/facet-buckets.test.d.ts +1 -0
  70. package/dist/facet-buckets.test.js +296 -0
  71. package/dist/features.d.ts +5 -0
  72. package/dist/features.js +30 -0
  73. package/dist/filter-operators.d.ts +16 -0
  74. package/dist/filter-operators.js +69 -0
  75. package/dist/filter-operators.test.d.ts +1 -0
  76. package/dist/filter-operators.test.js +135 -0
  77. package/dist/hyperformula-adapter.d.ts +82 -0
  78. package/dist/hyperformula-adapter.js +73 -0
  79. package/dist/hyperformula-adapter.test.d.ts +1 -0
  80. package/dist/hyperformula-adapter.test.js +205 -0
  81. package/dist/index.d.ts +9 -3
  82. package/dist/index.js +8 -2
  83. package/dist/keyboard-handlers.coverage.test.d.ts +1 -0
  84. package/dist/keyboard-handlers.coverage.test.js +495 -0
  85. package/dist/keyboard-handlers.d.ts +7 -0
  86. package/dist/keyboard-handlers.js +202 -0
  87. package/dist/menus.d.ts +40 -0
  88. package/dist/menus.js +390 -0
  89. package/dist/menus.test.d.ts +1 -0
  90. package/dist/menus.test.js +560 -0
  91. package/dist/named-views.coverage.test.d.ts +1 -0
  92. package/dist/named-views.coverage.test.js +180 -0
  93. package/dist/named-views.d.ts +27 -0
  94. package/dist/named-views.js +39 -0
  95. package/dist/row-drag.d.ts +49 -0
  96. package/dist/row-drag.js +221 -0
  97. package/dist/row-drag.test.d.ts +1 -0
  98. package/dist/row-drag.test.js +142 -0
  99. package/dist/row-resize.d.ts +43 -0
  100. package/dist/row-resize.js +158 -0
  101. package/dist/row-resize.test.d.ts +1 -0
  102. package/dist/row-resize.test.js +329 -0
  103. package/dist/scroll-sync.d.ts +9 -0
  104. package/dist/scroll-sync.js +89 -0
  105. package/dist/scroll-sync.test.d.ts +1 -0
  106. package/dist/scroll-sync.test.js +290 -0
  107. package/dist/selection.d.ts +32 -0
  108. package/dist/selection.js +427 -0
  109. package/dist/selection.multi-range.test.d.ts +1 -0
  110. package/dist/selection.multi-range.test.js +55 -0
  111. package/dist/selection.test.d.ts +1 -0
  112. package/dist/selection.test.js +647 -0
  113. package/dist/server-data-source.coverage.test.d.ts +1 -0
  114. package/dist/server-data-source.coverage.test.js +154 -0
  115. package/dist/spreadsheet.d.ts +110 -0
  116. package/dist/spreadsheet.js +242 -0
  117. package/dist/spreadsheet.test.d.ts +1 -0
  118. package/dist/spreadsheet.test.js +446 -0
  119. package/dist/summaries.d.ts +12 -0
  120. package/dist/summaries.js +65 -0
  121. package/dist/sv-grid-scrollbar.js +13 -1
  122. package/dist/svgrid-wrapper.types.d.ts +31 -1
  123. package/dist/svgrid.behavior.test.js +20 -0
  124. package/dist/svgrid.comments-autocomplete.test.d.ts +1 -0
  125. package/dist/svgrid.comments-autocomplete.test.js +96 -0
  126. package/dist/svgrid.context-menu.test.d.ts +1 -0
  127. package/dist/svgrid.context-menu.test.js +102 -0
  128. package/dist/svgrid.interaction.test.js +31 -0
  129. package/dist/svgrid.new-features.wrapper.test.js +64 -6
  130. package/dist/svgrid.wrapper.test.js +27 -1
  131. package/dist/test-setup.js +9 -3
  132. package/dist/virtualization/column-virtualizer.d.ts +2 -0
  133. package/dist/virtualization/scroll-scaling.d.ts +45 -0
  134. package/dist/virtualization/scroll-scaling.js +99 -0
  135. package/dist/virtualization/scroll-scaling.test.d.ts +1 -0
  136. package/dist/virtualization/scroll-scaling.test.js +127 -0
  137. package/dist/virtualization/svelte-virtualizer.svelte.d.ts +2 -0
  138. package/dist/virtualization/svelte-virtualizer.svelte.js +2 -0
  139. package/dist/virtualization/virtualizer.d.ts +7 -0
  140. package/dist/virtualization/virtualizer.js +30 -0
  141. package/package.json +2 -1
  142. package/src/GridFooter.svelte +164 -0
  143. package/src/GridMenus.svelte +648 -0
  144. package/src/SvGrid.controller.svelte.ts +2352 -0
  145. package/src/SvGrid.css +2012 -0
  146. package/src/SvGrid.helpers.test.ts +415 -0
  147. package/src/SvGrid.helpers.ts +185 -0
  148. package/src/SvGrid.svelte +2346 -8742
  149. package/src/SvGrid.types.ts +537 -0
  150. package/src/SvGridChart.svelte +1060 -23
  151. package/src/aligned-grids.test.ts +80 -0
  152. package/src/aligned-grids.ts +87 -0
  153. package/src/build-api.coverage.test.ts +532 -0
  154. package/src/build-api.ts +683 -0
  155. package/src/cell-render.test.ts +451 -0
  156. package/src/cell-render.ts +426 -0
  157. package/src/cell-values.ts +114 -0
  158. package/src/chart-export.test.ts +370 -0
  159. package/src/chart.coverage.test.ts +814 -0
  160. package/src/chart.ts +1352 -47
  161. package/src/clipboard.test.ts +780 -0
  162. package/src/clipboard.ts +552 -0
  163. package/src/collaboration.coverage.test.ts +220 -0
  164. package/src/column-groups.test.ts +59 -0
  165. package/src/column-groups.ts +80 -0
  166. package/src/column-types.test.ts +68 -0
  167. package/src/column-types.ts +82 -0
  168. package/src/columns.test.ts +702 -0
  169. package/src/columns.ts +419 -0
  170. package/src/core.ts +86 -0
  171. package/src/css.d.ts +3 -0
  172. package/src/editing.test.ts +837 -0
  173. package/src/editing.ts +669 -0
  174. package/src/editors/cell-editors.coverage.test.ts +156 -0
  175. package/src/editors/cell-editors.ts +1 -0
  176. package/src/facet-buckets.test.ts +353 -0
  177. package/src/facet-buckets.ts +67 -0
  178. package/src/features.ts +128 -0
  179. package/src/filter-operators.test.ts +174 -0
  180. package/src/filter-operators.ts +87 -0
  181. package/src/hyperformula-adapter.test.ts +256 -0
  182. package/src/hyperformula-adapter.ts +124 -0
  183. package/src/index.ts +49 -0
  184. package/src/keyboard-handlers.coverage.test.ts +560 -0
  185. package/src/keyboard-handlers.ts +353 -0
  186. package/src/keyboard.ts +97 -97
  187. package/src/menus.test.ts +620 -0
  188. package/src/menus.ts +555 -0
  189. package/src/named-views.coverage.test.ts +210 -0
  190. package/src/named-views.ts +48 -0
  191. package/src/row-drag.test.ts +168 -0
  192. package/src/row-drag.ts +255 -0
  193. package/src/row-resize.test.ts +369 -0
  194. package/src/row-resize.ts +171 -0
  195. package/src/scroll-sync.test.ts +330 -0
  196. package/src/scroll-sync.ts +218 -0
  197. package/src/selection.multi-range.test.ts +61 -0
  198. package/src/selection.test.ts +722 -0
  199. package/src/selection.ts +579 -0
  200. package/src/server-data-source.coverage.test.ts +180 -0
  201. package/src/spreadsheet.test.ts +489 -0
  202. package/src/spreadsheet.ts +304 -0
  203. package/src/summaries.ts +204 -0
  204. package/src/sv-grid-scrollbar.ts +13 -1
  205. package/src/svgrid-wrapper.types.ts +31 -1
  206. package/src/svgrid.behavior.test.ts +22 -0
  207. package/src/svgrid.comments-autocomplete.test.ts +112 -0
  208. package/src/svgrid.context-menu.test.ts +126 -0
  209. package/src/svgrid.interaction.test.ts +30 -0
  210. package/src/svgrid.new-features.wrapper.test.ts +67 -6
  211. package/src/svgrid.wrapper.test.ts +27 -1
  212. package/src/test-setup.ts +9 -6
  213. package/src/virtualization/scroll-scaling.test.ts +148 -0
  214. package/src/virtualization/scroll-scaling.ts +121 -0
  215. package/src/virtualization/svelte-virtualizer.svelte.ts +2 -0
  216. package/src/virtualization/virtualizer.ts +26 -0
@@ -0,0 +1,683 @@
1
+ // build-api handlers extracted from the controller. Imperative event handlers
2
+ // reading/writing controller state via the `ctx` handle; the reactive core
3
+ // ($state/$derived/$effect) stays in the controller.
4
+ import {
5
+ applyExcelFilter,
6
+ normalizeForFilter,
7
+ createColumnVirtualizer,
8
+ createCoreRowModel,
9
+ createExpandedRowModel,
10
+ createFilteredRowModel,
11
+ createGroupedRowModel,
12
+ createPaginatedRowModel,
13
+ createSvelteVirtualizer,
14
+ createSortedRowModel,
15
+ createSvGrid,
16
+ filterFns,
17
+ getGridCellA11yProps,
18
+ getGridCellDomId,
19
+ getGridHeaderA11yProps,
20
+ getGridRootA11yProps,
21
+ getGridRowA11yProps,
22
+ parseEditorValue,
23
+ normalizeEditorOptions,
24
+ sortFns,
25
+ tableFeatures,
26
+ rowSortingFeature,
27
+ columnFilteringFeature,
28
+ columnGroupingFeature,
29
+ type CellContext,
30
+ type EditorContext,
31
+ type CellEditorOption,
32
+ type CellEditorType,
33
+ type CellFormatter,
34
+ type CellFormatConfig,
35
+ type Column,
36
+ type ColumnDef,
37
+ type Row,
38
+ type RowData,
39
+ type SvGridApi,
40
+ type TableFeatures,
41
+ } from "./index";
42
+ import "./sv-grid-scrollbar";
43
+ import type { Snippet } from "svelte";
44
+ import { getKeyboardIntent, getNextActiveCell } from "./keyboard";
45
+ import {
46
+ formatNumericWithConfig,
47
+ getDateFormatter,
48
+ resolveDatePattern,
49
+ } from "./cell-formatting";
50
+ import {
51
+ RenderSnippetConfig,
52
+ RenderComponentConfig,
53
+ } from "./render-component";
54
+ import { buildFillPattern } from "./fill-patterns";
55
+ import { buildSparkline, toSparklineValues } from "./sparkline";
56
+ import {
57
+ resolveCellFormat,
58
+ computeColumnStat,
59
+ formatsNeedingStats,
60
+ type ColumnStat,
61
+ type ResolvedCellFormat,
62
+ } from "./conditional-formatting";
63
+ import SvGridDropdown from "./SvGridDropdown.svelte";
64
+ import type {
65
+ Props,
66
+ SelectionPoint,
67
+ SelectionRange,
68
+ CellEditState,
69
+ FilterOperator,
70
+ FilterOption,
71
+ MenuPosition,
72
+ } from "./SvGrid.types";
73
+ import {
74
+ cfTextStyle,
75
+ fmtStat,
76
+ getCellKey,
77
+ resolveClassList,
78
+ toDateInputValue,
79
+ toDateTimeLocalInputValue,
80
+ getEditableInputValue,
81
+ getEditorInputType,
82
+ toValueArray,
83
+ getOptionLabel,
84
+ getOptionColor,
85
+ colorfulChipStyle,
86
+ getEditorClass,
87
+ asDate,
88
+ clampMenuX,
89
+ cssEscape,
90
+ rawToNumber,
91
+ formatFacetNumber,
92
+ formatFacetDate,
93
+ } from "./SvGrid.helpers";
94
+ import { createClipboard } from "./clipboard";
95
+ import {
96
+ filterOperatorOptions,
97
+ fallbackOperatorOption,
98
+ TEXT_OPERATORS,
99
+ NUMBER_OPERATORS,
100
+ DATE_OPERATORS,
101
+ CHECKBOX_OPERATORS,
102
+ operatorOption,
103
+ operatorsForColumn,
104
+ defaultOperatorFor,
105
+ operatorLabelFor,
106
+ } from "./filter-operators";
107
+ import {
108
+ type FacetBucket,
109
+ isBucketableColumn,
110
+ buildBuckets,
111
+ isInBucket,
112
+ } from "./facet-buckets";
113
+ import {
114
+ getColumnBaseValue,
115
+ isGroupRow,
116
+ toolPanelHeaderLabel,
117
+ formatSummaryNumeric,
118
+ getColumnAlign,
119
+ getPinnedCellValue,
120
+ getColumnAccessorValue,
121
+ columnDefMatchesId,
122
+ } from "./cell-values";
123
+
124
+ export function createGridApi<
125
+ TFeatures extends TableFeatures = TableFeatures,
126
+ TData extends RowData = RowData,
127
+ >(ctx: any) {
128
+ function buildApi(): SvGridApi<TFeatures, TData> {
129
+ const findColumn = (columnId: string) =>
130
+ ctx.grid.getAllColumns().find((column: any) => column.id === columnId);
131
+ return {
132
+ getCellValue(rowIndex, columnId) {
133
+ const row = ctx.internalData[rowIndex];
134
+ const column = findColumn(columnId);
135
+ if (!row || !column) return undefined;
136
+ if (column.columnDef.accessorFn)
137
+ return column.columnDef.accessorFn(row);
138
+ if (column.columnDef.field)
139
+ return (row as Record<string, unknown>)[column.columnDef.field];
140
+ return undefined;
141
+ },
142
+ setCellValue(rowIndex, columnId, value) {
143
+ const row = ctx.internalData[rowIndex];
144
+ const column = findColumn(columnId);
145
+ if (!row || !column?.columnDef.field) return;
146
+ const next = ctx.internalData.slice() as Array<TData>;
147
+ next[rowIndex] = { ...row, [column.columnDef.field]: value } as TData;
148
+ ctx.internalData = next;
149
+ },
150
+ startEditing(rowIndex, columnId) {
151
+ return ctx.startEditing(rowIndex, columnId);
152
+ },
153
+ stopEditing(cancel) {
154
+ return ctx.stopEditing(cancel ?? false);
155
+ },
156
+ selectCells(ranges) {
157
+ // Multiple rectangles are supported. Empty array clears everything.
158
+ if (!ranges || ranges.length === 0) {
159
+ ctx.selectionRange = { anchor: null, focus: null };
160
+ ctx.selectionRanges = [];
161
+ return;
162
+ }
163
+ const rowCount = ctx.internalData.length;
164
+ const colCount = ctx.allColumns.length;
165
+ if (rowCount === 0 || colCount === 0) return;
166
+ // Clamp to the visible grid bounds so callers can pass open-ended
167
+ // values like `[0, 0, Infinity, Infinity]` to mean "select all".
168
+ const toRange = ([r1, c1, r2, c2]: readonly [number, number, number, number]) => ({
169
+ anchor: {
170
+ rowIndex: Math.max(0, Math.min(rowCount - 1, Math.min(r1, r2))),
171
+ colIndex: Math.max(0, Math.min(colCount - 1, Math.min(c1, c2))),
172
+ },
173
+ focus: {
174
+ rowIndex: Math.max(0, Math.min(rowCount - 1, Math.max(r1, r2))),
175
+ colIndex: Math.max(0, Math.min(colCount - 1, Math.max(c1, c2))),
176
+ },
177
+ });
178
+ const built = ranges.map(toRange);
179
+ // Last range is the active one; the rest are committed extras.
180
+ ctx.selectionRanges = built.slice(0, -1);
181
+ const active = built[built.length - 1]!;
182
+ ctx.selectionRange = active;
183
+ // Move the active cell to the last range's top-left so keyboard
184
+ // navigation continues from there.
185
+ ctx.setActiveCell(active.anchor.rowIndex, active.anchor.colIndex);
186
+ },
187
+ getSelected() {
188
+ return ctx
189
+ .getSelectionRects()
190
+ .map((r: { minRow: number; minCol: number; maxRow: number; maxCol: number }) =>
191
+ [r.minRow, r.minCol, r.maxRow, r.maxCol] as [number, number, number, number],
192
+ );
193
+ },
194
+ addRow(row, position = "bottom") {
195
+ this.addRows([row], position);
196
+ },
197
+ addRows(rows, position = "bottom") {
198
+ const next = ctx.internalData.slice() as Array<TData>;
199
+ if (position === "top") next.unshift(...rows);
200
+ else if (position === "bottom") next.push(...rows);
201
+ else if (typeof position === "number")
202
+ next.splice(Math.max(0, Math.min(position, next.length)), 0, ...rows);
203
+ ctx.internalData = next;
204
+ },
205
+ removeRow(rowIndex) {
206
+ this.removeRows([rowIndex]);
207
+ },
208
+ removeRows(rowIndices) {
209
+ const drop = new Set(rowIndices);
210
+ ctx.internalData = ctx.internalData.filter((_: any, i: any) => !drop.has(i));
211
+ },
212
+ applyTransaction(tx) {
213
+ const getId = ctx.props.getRowId;
214
+ let next = ctx.internalData.slice() as Array<TData>;
215
+ let added = 0;
216
+ let updated = 0;
217
+ let removed = 0;
218
+
219
+ if (tx.remove?.length) {
220
+ const removeIds = new Set<string>();
221
+ const removeRefs = new Set<TData>();
222
+ for (const r of tx.remove) {
223
+ if (typeof r === "string") removeIds.add(r);
224
+ else removeRefs.add(r as TData);
225
+ }
226
+ next = next.filter((row, i) => {
227
+ const hit =
228
+ removeRefs.has(row) ||
229
+ (getId ? removeIds.has(getId(row, i)) : false);
230
+ if (hit) removed += 1;
231
+ return !hit;
232
+ });
233
+ }
234
+
235
+ if (tx.update?.length && getId) {
236
+ const byId = new Map<string, TData>();
237
+ for (const u of tx.update) byId.set(getId(u, 0), u);
238
+ next = next.map((row, i) => {
239
+ const u = byId.get(getId(row, i));
240
+ if (u) {
241
+ updated += 1;
242
+ return u;
243
+ }
244
+ return row;
245
+ });
246
+ }
247
+
248
+ if (tx.add?.length) {
249
+ next.push(...(tx.add as Array<TData>));
250
+ added += tx.add.length;
251
+ }
252
+
253
+ ctx.internalData = next;
254
+ return { added, updated, removed };
255
+ },
256
+ addColumn(column, position = "right") {
257
+ this.addColumns([column], position);
258
+ },
259
+ addColumns(columns, position = "right") {
260
+ const next = ctx.internalColumns.slice();
261
+ if (position === "left") next.unshift(...columns);
262
+ else if (position === "right") next.push(...columns);
263
+ else if (typeof position === "number")
264
+ next.splice(
265
+ Math.max(0, Math.min(position, next.length)),
266
+ 0,
267
+ ...columns,
268
+ );
269
+ ctx.internalColumns = next;
270
+ },
271
+ removeColumn(columnId) {
272
+ ctx.internalColumns = ctx.internalColumns.filter(
273
+ (def: any) => !columnDefMatchesId(def, columnId),
274
+ );
275
+ },
276
+ setColumnVisible(columnId, visible) {
277
+ if (visible) {
278
+ const next = { ...ctx.hiddenColumns };
279
+ delete next[columnId];
280
+ ctx.hiddenColumns = next;
281
+ } else {
282
+ ctx.hiddenColumns = { ...ctx.hiddenColumns, [columnId]: true };
283
+ }
284
+ },
285
+ isColumnVisible(columnId) {
286
+ return !ctx.hiddenColumns[columnId];
287
+ },
288
+ setSort(columnId, direction) {
289
+ // Honour the column's `sortable` opt-out. Asking the engine
290
+ // whether the column can sort folds in both the feature toggle
291
+ // AND the per-column flag.
292
+ const col = ctx.allColumns.find((c: any) => c.id === columnId);
293
+ if (col && !col.getCanSort?.()) return;
294
+ const clauses = direction
295
+ ? [{ id: columnId, desc: direction === "desc" }]
296
+ : (ctx.grid.getState().sorting ?? []).filter(
297
+ (entry: { id: string }) => entry.id !== columnId,
298
+ );
299
+ ctx.grid.store.setState((prev: any) => ({ ...prev, sorting: clauses }));
300
+ },
301
+ clearSort() {
302
+ ctx.grid.store.setState((prev: any) => ({ ...prev, sorting: [] }));
303
+ },
304
+ setGroupBy(columnIds) {
305
+ ctx.grid.setGrouping([...columnIds]);
306
+ },
307
+ setFilter(columnId, filter) {
308
+ // Honour the column's `filterable` opt-out. Same approach as
309
+ // `setSort` - `getCanFilter()` already combines the feature flag
310
+ // and the per-column field.
311
+ const col = ctx.allColumns.find((c: any) => c.id === columnId);
312
+ if (col && !col.getCanFilter?.()) return;
313
+ if (!filter) {
314
+ this.clearFilter(columnId);
315
+ return;
316
+ }
317
+ ctx.filterMenuValues = {
318
+ ...ctx.filterMenuValues,
319
+ [columnId]: {
320
+ operator: filter.operator,
321
+ value: filter.value ?? "",
322
+ ...(filter.operator === "between"
323
+ ? { valueTo: filter.valueTo ?? "" }
324
+ : {}),
325
+ // Optional second condition + join (multi-condition filtering).
326
+ ...(filter.operator2
327
+ ? {
328
+ operator2: filter.operator2,
329
+ value2: filter.value2 ?? "",
330
+ join: filter.join ?? "AND",
331
+ ...(filter.operator2 === "between"
332
+ ? { valueTo2: filter.valueTo2 ?? "" }
333
+ : {}),
334
+ }
335
+ : {}),
336
+ },
337
+ };
338
+ },
339
+ setFacetFilter(columnId, values) {
340
+ // Empty array OR null both mean "clear this column's facet" -
341
+ // mirrors how the column menu treats unchecking the last value.
342
+ if (!values || values.length === 0) {
343
+ if (ctx.valueFilters[columnId]) {
344
+ const next = { ...ctx.valueFilters };
345
+ delete next[columnId];
346
+ ctx.valueFilters = next;
347
+ }
348
+ return;
349
+ }
350
+ ctx.valueFilters = {
351
+ ...ctx.valueFilters,
352
+ [columnId]: new Set(values),
353
+ };
354
+ },
355
+ clearFilter(columnId) {
356
+ ctx.clearColumnFilter(columnId);
357
+ },
358
+ clearAllFilters() {
359
+ // Wipe every filter surface in one go: column-menu, filter-row, set
360
+ // filters, and the global search box.
361
+ ctx.filterMenuValues = {};
362
+ ctx.filterRowValues = {};
363
+ ctx.valueFilters = {};
364
+ if (ctx.globalFilter !== "") ctx.globalFilter = "";
365
+ },
366
+ getFilters() {
367
+ // Return a defensive copy so callers can't mutate internal state.
368
+ const out: Record<
369
+ string,
370
+ { operator: FilterOperator; value: string; valueTo?: string }
371
+ > = {};
372
+ for (const [columnId, filter] of Object.entries(ctx.filterMenuValues as Record<string, { operator: FilterOperator; value: string; valueTo?: string }>)) {
373
+ out[columnId] = {
374
+ operator: filter.operator,
375
+ value: filter.value,
376
+ ...(filter.operator === "between" && filter.valueTo
377
+ ? { valueTo: filter.valueTo }
378
+ : {}),
379
+ };
380
+ }
381
+ return out;
382
+ },
383
+ getDisplayedRows() {
384
+ // `allRows` is the final, post-filter, post-sort, post-group,
385
+ // post-pagination list - exactly what the body renders. Skip group
386
+ // header rows (they wrap an aggregate, not a TData row).
387
+ const out: TData[] = [];
388
+ for (const row of ctx.allRows) {
389
+ if (row.subRows && row.subRows.length > 0) continue;
390
+ out.push(row.original as TData);
391
+ }
392
+ return out;
393
+ },
394
+ getData() {
395
+ return ctx.internalData;
396
+ },
397
+ getColumns() {
398
+ // Snapshot every column with its human-readable label and
399
+ // visibility flag. Used by external code (exporters, column
400
+ // pickers) so they don't have to re-walk the columnDef tree.
401
+ // Hidden columns ARE included (with `visible: false`) so a column
402
+ // picker can re-enable them - callers that only want what's
403
+ // rendered filter by `.visible` (e.g. the exporter does).
404
+ const describe = (c: any, visible: boolean) => ({
405
+ id: c.id,
406
+ field: (c.columnDef as { field?: string }).field,
407
+ header:
408
+ typeof c.columnDef.header === "string"
409
+ ? c.columnDef.header
410
+ : c.id,
411
+ visible,
412
+ });
413
+ // Visible columns first, in their current visual order...
414
+ const out = ctx.allColumns.map((c: any) => describe(c, true));
415
+ // ...then any column hidden via `visible: false` / setColumnVisible.
416
+ // Those aren't in `allColumns` (that list is visible-only), so pull
417
+ // them straight from the engine's leaf set.
418
+ const visibleIds = new Set(out.map((c: { id: string }) => c.id));
419
+ for (const c of ctx.grid.getAllColumns() as any[]) {
420
+ if (!visibleIds.has(c.id)) out.push(describe(c, false));
421
+ }
422
+ return out;
423
+ },
424
+ clearRowSelection() {
425
+ // Wipe the internal selection map AND emit the change so any
426
+ // consumer holding a derived `selectedRows` resets too.
427
+ ctx.grid.setRowSelection(() => ({}));
428
+ ctx.props.onRowSelectionChange?.({}, []);
429
+ },
430
+ setColumnWidth(columnId: string, width: number) {
431
+ const clamped = Math.max(ctx.MIN_COLUMN_WIDTH, Math.floor(width));
432
+ ctx.columnWidths = { ...ctx.columnWidths, [columnId]: clamped };
433
+ },
434
+ getColumnWidths() {
435
+ // Resolve every column's effective width by consulting both the
436
+ // resize overrides (`columnWidths`) AND the columnDef defaults,
437
+ // so the snapshot is round-trippable through setColumnWidth.
438
+ const out: Record<string, number> = {};
439
+ for (const c of ctx.allColumns) out[c.id] = ctx.getColumnWidth(c.id);
440
+ return out;
441
+ },
442
+ autosizeColumn(columnId: string) {
443
+ ctx.autosizeColumn(columnId);
444
+ },
445
+ autosizeAllColumns() {
446
+ ctx.autosizeAllColumns();
447
+ },
448
+ setColumnPinning(pinning) {
449
+ // Defensive copy + dedupe so callers can't mutate our state.
450
+ const left = Array.from(new Set(pinning.left ?? []));
451
+ const right = Array.from(new Set(pinning.right ?? []));
452
+ ctx.columnPinning = { left, right };
453
+ },
454
+ getColumnPinning() {
455
+ return {
456
+ left: ctx.columnPinning.left.slice(),
457
+ right: ctx.columnPinning.right.slice(),
458
+ };
459
+ },
460
+ // ---- Column reorder
461
+ setColumnOrder(order) {
462
+ ctx.setColumnOrderInternal(order);
463
+ },
464
+ getColumnOrder() {
465
+ return ctx.getCurrentColumnOrder();
466
+ },
467
+ setRowExpanded(id, expanded) {
468
+ ctx.grid.setExpanded((prev: any) => ({ ...prev, [id]: !!expanded }));
469
+ },
470
+ expandAllGroups() {
471
+ // Walk the current grouped row model and flip every group node on.
472
+ const next: Record<string, boolean> = {};
473
+ const walk = (rows: ReadonlyArray<{ id: string; getCanExpand?: () => boolean; subRows?: ReadonlyArray<unknown> }>) => {
474
+ for (const row of rows) {
475
+ if (row.getCanExpand?.()) next[row.id] = true;
476
+ const sub = row.subRows as ReadonlyArray<{ id: string; getCanExpand?: () => boolean; subRows?: ReadonlyArray<unknown> }> | undefined;
477
+ if (sub && sub.length > 0) walk(sub);
478
+ }
479
+ };
480
+ walk(ctx.grid.getRowModel().rows as unknown as ReadonlyArray<{ id: string; getCanExpand?: () => boolean; subRows?: ReadonlyArray<unknown> }>);
481
+ ctx.grid.setExpanded(() => next);
482
+ },
483
+ collapseAllGroups() {
484
+ ctx.grid.setExpanded(() => ({}));
485
+ },
486
+ // ---- Undo / redo (history + pointer)
487
+ undo() {
488
+ if (ctx.historyPtr < 0) return false
489
+ const step = ctx.history[ctx.historyPtr]
490
+ if (!step) return false
491
+ ctx.applyHistoryStep(step, 'undo')
492
+ ctx.historyPtr -= 1
493
+ ctx.historyVersion += 1
494
+ return true
495
+ },
496
+ redo() {
497
+ if (ctx.historyPtr >= ctx.history.length - 1) return false
498
+ const step = ctx.history[ctx.historyPtr + 1]
499
+ if (!step) return false
500
+ ctx.applyHistoryStep(step, 'redo')
501
+ ctx.historyPtr += 1
502
+ ctx.historyVersion += 1
503
+ return true
504
+ },
505
+ canUndo() { void ctx.historyVersion; return ctx.historyPtr >= 0 },
506
+ canRedo() { void ctx.historyVersion; return ctx.historyPtr < ctx.history.length - 1 },
507
+ clearHistory() { ctx.history = []; ctx.historyPtr = -1; ctx.historyVersion += 1 },
508
+ // ---- Find
509
+ openFind() { ctx.findOpen = true },
510
+ closeFind() { ctx.findOpen = false; ctx.findQuery = '' },
511
+ setFindQuery(q: string) { ctx.findQuery = q; ctx.findHitIndex = 0 },
512
+ getFindHits() { return ctx.findHits.slice() },
513
+ // ---- Row selection (read + write)
514
+ getSelectedRows() {
515
+ const out: TData[] = [];
516
+ for (const row of ctx.allRows) {
517
+ if (isGroupRow(row)) continue;
518
+ if (ctx.rowSelectionState[row.id]) out.push(row.original as TData);
519
+ }
520
+ return out;
521
+ },
522
+ getSelectedRowIds() {
523
+ const out: string[] = [];
524
+ for (const row of ctx.allRows) {
525
+ if (!isGroupRow(row) && ctx.rowSelectionState[row.id]) out.push(row.id);
526
+ }
527
+ return out;
528
+ },
529
+ selectRows(ids, additive = false) {
530
+ const set = new Set(ids);
531
+ ctx.grid.setRowSelection((prev: any) => {
532
+ const next: Record<string, boolean> = additive ? { ...prev } : {};
533
+ for (const id of set) next[id] = true;
534
+ return next;
535
+ });
536
+ },
537
+ selectAllRows() {
538
+ const next: Record<string, boolean> = {};
539
+ for (const row of ctx.allRows) if (!isGroupRow(row)) next[row.id] = true;
540
+ ctx.grid.setRowSelection(() => next);
541
+ },
542
+ toggleRowSelected(id) {
543
+ ctx.toggleRowSelectionById(id);
544
+ },
545
+ // ---- Pagination
546
+ getPageInfo() {
547
+ const { pageIndex, pageSize } = ctx.paginationState;
548
+ const total = ctx.allRowsBeforePagination.length;
549
+ const pageCount = Math.max(1, Math.ceil(total / Math.max(1, pageSize)));
550
+ return { pageIndex, pageSize, pageCount, total };
551
+ },
552
+ setPage(pageIndex) {
553
+ const total = ctx.allRowsBeforePagination.length;
554
+ const pageCount = Math.max(
555
+ 1,
556
+ Math.ceil(total / Math.max(1, ctx.paginationState.pageSize)),
557
+ );
558
+ ctx.goToPage(Math.max(0, Math.min(pageIndex, pageCount - 1)));
559
+ },
560
+ nextPage() {
561
+ this.setPage(ctx.paginationState.pageIndex + 1);
562
+ },
563
+ prevPage() {
564
+ this.setPage(ctx.paginationState.pageIndex - 1);
565
+ },
566
+ firstPage() {
567
+ this.setPage(0);
568
+ },
569
+ lastPage() {
570
+ const total = ctx.allRowsBeforePagination.length;
571
+ const pageCount = Math.max(
572
+ 1,
573
+ Math.ceil(total / Math.max(1, ctx.paginationState.pageSize)),
574
+ );
575
+ this.setPage(pageCount - 1);
576
+ },
577
+ setPageSize(size) {
578
+ // Calls the component-level helper (lexical scope), not this method.
579
+ ctx.setPageSize(Math.max(1, Math.floor(size)));
580
+ },
581
+ // ---- Navigation / scrolling
582
+ scrollToRow(rowIndex) {
583
+ if (!ctx.scrollContainer) return;
584
+ const maxIndex = Math.max(0, ctx.allRows.length - 1);
585
+ const clamped = Math.max(0, Math.min(rowIndex, maxIndex));
586
+ // Logical offset from the virtualizer (honors uniform OR per-row
587
+ // sizing), then mapped into the capped DOM scroll space so it lands
588
+ // correctly on huge grids where the DOM height is scaled down.
589
+ const logical = ctx.virtualizer.getOffsetForIndex(clamped);
590
+ ctx.scrollContainer.scrollTop = ctx.logicalToDomRowOffset(logical);
591
+ ctx.scheduleScrollSync(
592
+ ctx.scrollContainer.scrollTop,
593
+ ctx.scrollContainer.scrollLeft,
594
+ );
595
+ },
596
+ getActiveCell() {
597
+ const a = ctx.activeCell;
598
+ if (!a || a.rowIndex < 0 || a.colIndex < 0) return null;
599
+ const col = ctx.allColumns[a.colIndex];
600
+ return {
601
+ rowIndex: a.rowIndex,
602
+ colIndex: a.colIndex,
603
+ columnId: col?.id ?? "",
604
+ };
605
+ },
606
+ setActiveCell(rowIndex, colIndex) {
607
+ const r = Math.max(0, Math.min(rowIndex, Math.max(0, ctx.allRows.length - 1)));
608
+ const c = Math.max(
609
+ 0,
610
+ Math.min(colIndex, Math.max(0, ctx.allColumns.length - 1)),
611
+ );
612
+ // Calls the component-level helper (lexical scope), not this method.
613
+ ctx.setActiveCell(r, c);
614
+ },
615
+ // ---- View state (save / restore)
616
+ getState() {
617
+ return {
618
+ sorting: (ctx.grid.getState().sorting ?? []).map(
619
+ (s: { id: string; desc: boolean }) => ({ id: s.id, desc: s.desc }),
620
+ ),
621
+ grouping: [...(ctx.grid.getState().grouping ?? [])],
622
+ pagination: {
623
+ pageIndex: ctx.paginationState.pageIndex,
624
+ pageSize: ctx.paginationState.pageSize,
625
+ },
626
+ columnWidths: this.getColumnWidths(),
627
+ columnPinning: this.getColumnPinning(),
628
+ columnOrder: ctx.getCurrentColumnOrder(),
629
+ hiddenColumns: Object.keys(ctx.hiddenColumns).filter(
630
+ (k) => ctx.hiddenColumns[k],
631
+ ),
632
+ globalFilter: ctx.globalFilter,
633
+ columnFilters: this.getFilters(),
634
+ facetFilters: Object.fromEntries(
635
+ Object.entries(ctx.valueFilters).map(([k, set]: [string, any]) => [
636
+ k,
637
+ Array.from(set),
638
+ ]),
639
+ ),
640
+ };
641
+ },
642
+ setState(state) {
643
+ if (state.sorting) {
644
+ const sorting = state.sorting.map((s) => ({ id: s.id, desc: s.desc }));
645
+ ctx.grid.store.setState((prev: any) => ({ ...prev, sorting }));
646
+ }
647
+ if (state.grouping) ctx.grid.setGrouping([...state.grouping]);
648
+ if (state.pagination) {
649
+ const p = state.pagination;
650
+ ctx.grid.setPagination((prev: any) => ({ ...prev, ...p }));
651
+ }
652
+ if (state.columnWidths) ctx.columnWidths = { ...state.columnWidths };
653
+ if (state.columnPinning)
654
+ ctx.columnPinning = {
655
+ left: [...(state.columnPinning.left ?? [])],
656
+ right: [...(state.columnPinning.right ?? [])],
657
+ };
658
+ if (state.columnOrder) ctx.setColumnOrderInternal(state.columnOrder);
659
+ if (state.hiddenColumns) {
660
+ const next: Record<string, boolean> = {};
661
+ for (const id of state.hiddenColumns) next[id] = true;
662
+ ctx.hiddenColumns = next;
663
+ }
664
+ if (state.globalFilter !== undefined) ctx.globalFilter = state.globalFilter;
665
+ if (state.columnFilters)
666
+ ctx.filterMenuValues = { ...state.columnFilters };
667
+ if (state.facetFilters) {
668
+ const next: Record<string, Set<string>> = {};
669
+ for (const [k, arr] of Object.entries(state.facetFilters))
670
+ next[k] = new Set(arr);
671
+ ctx.valueFilters = next;
672
+ }
673
+ },
674
+ refresh() {
675
+ ctx.grid.store.setState((prev: any) => ({ ...prev }));
676
+ },
677
+ };
678
+ }
679
+
680
+ return {
681
+ buildApi,
682
+ };
683
+ }