@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,1917 @@
1
+ import { applyExcelFilter, normalizeForFilter, createColumnVirtualizer, createCoreRowModel, createExpandedRowModel, createFilteredRowModel, createGroupedRowModel, createSvelteVirtualizer, createSortedRowModel, createSvGrid, getGridCellDomId, sortFns, } from "./index";
2
+ import { createRowScrollScaling, resolveMaxDomHeight, } from "./virtualization/scroll-scaling";
3
+ import "./sv-grid-scrollbar";
4
+ import { computeColumnStat, formatsNeedingStats, } from "./conditional-formatting";
5
+ import { rawToNumber, } from "./SvGrid.helpers";
6
+ import { createFeatures } from "./features";
7
+ import { createScrollSync, } from "./scroll-sync";
8
+ import { createKeyboard, } from "./keyboard-handlers";
9
+ import { createSummaries, } from "./summaries";
10
+ import { createMenus, } from "./menus";
11
+ import { createCellRender, } from "./cell-render";
12
+ import { createEditing, } from "./editing";
13
+ import { createSelection, } from "./selection";
14
+ import { createColumns, } from "./columns";
15
+ import { createRowDrag, } from "./row-drag";
16
+ import { createAlignedGrids, } from "./aligned-grids";
17
+ import { resolveColumnTypes, } from "./column-types";
18
+ import { computeColumnGroupMeta, hiddenLeavesForCollapse, } from "./column-groups";
19
+ import { createGridApi, } from "./build-api";
20
+ import { createClipboard, } from "./clipboard";
21
+ import { filterOperatorOptions, fallbackOperatorOption, TEXT_OPERATORS, NUMBER_OPERATORS, DATE_OPERATORS, CHECKBOX_OPERATORS, operatorOption, operatorsForColumn, defaultOperatorFor, operatorLabelFor, } from "./filter-operators";
22
+ import { isBucketableColumn, buildBuckets, isInBucket, } from "./facet-buckets";
23
+ import { getColumnBaseValue, isGroupRow, toolPanelHeaderLabel, formatSummaryNumeric, getColumnAlign, getPinnedCellValue, getColumnAccessorValue, columnDefMatchesId, } from "./cell-values";
24
+ /**
25
+ * Conservative fallback for the browser's max element height, used during SSR
26
+ * or if runtime detection fails. 8M is below every known engine cap (Firefox
27
+ * ~17.9M, Chrome/Safari ~33.5M) so it is always safe, if coarser than needed.
28
+ */
29
+ const MAX_DOM_SCROLL_HEIGHT_FALLBACK = 8000000;
30
+ /**
31
+ * The browser's actual maximum *scrollable* element height in CSS px. Browsers
32
+ * clamp how tall a single element may be, and the cap is lower on mobile /
33
+ * high-DPR devices (the physical limit is in device px, so a 3x-DPR phone has
34
+ * ~1/3 the CSS-px cap of a 1x desktop). Past that cap a scroll container
35
+ * silently clamps its `scrollHeight` and the tail rows of a huge virtualized
36
+ * grid become unreachable.
37
+ *
38
+ * We measure two signals from one offscreen probe and keep the smaller (see
39
+ * `resolveMaxDomHeight`): the probe's clamped `offsetHeight`, AND the
40
+ * `scrollHeight` a real `overflow:auto` container exposes for it. The second
41
+ * matters because mobile WebKit/Blink can report a generous `offsetHeight` yet
42
+ * expose a smaller scrollable range - trusting the layout height alone is what
43
+ * stranded the last rows on phones. Using a real scroll container also folds in
44
+ * DPR clamping for free. Cached for the page lifetime; constant per browser.
45
+ */
46
+ let detectedMaxDomHeight = null;
47
+ /**
48
+ * Seed the `hiddenColumns` map from any column def marked `visible: false`.
49
+ * Walks groups so a hidden group hides all of its leaf columns. Keyed by the
50
+ * same id `setColumnVisible` uses (`id ?? field`), so user toggles afterward
51
+ * stay consistent. Run once at mount; prop changes don't re-apply it.
52
+ */
53
+ function initialHiddenColumns(defs) {
54
+ const hidden = {};
55
+ const walk = (cols, inheritedHidden) => {
56
+ for (const def of cols) {
57
+ const hide = inheritedHidden || def.visible === false;
58
+ if (def.columns?.length) {
59
+ walk(def.columns, hide);
60
+ }
61
+ else if (hide) {
62
+ const id = def.id ?? def.field;
63
+ if (id)
64
+ hidden[id] = true;
65
+ }
66
+ }
67
+ };
68
+ walk(defs, false);
69
+ return hidden;
70
+ }
71
+ function getMaxDomScrollHeight() {
72
+ // Escape hatch: a page may pin the cap via `window.__svgridMaxDomHeight`.
73
+ // Checked before the cache so it always wins. Two uses: reproducing a
74
+ // phone's lower element-height limit on desktop (and our e2e coverage of
75
+ // the huge-list path), and overriding detection on a device where it reads
76
+ // wrong. A non-positive / non-finite value is ignored.
77
+ if (typeof window !== "undefined") {
78
+ const forced = window
79
+ .__svgridMaxDomHeight;
80
+ if (typeof forced === "number" && Number.isFinite(forced) && forced > 0) {
81
+ return forced;
82
+ }
83
+ }
84
+ if (detectedMaxDomHeight != null)
85
+ return detectedMaxDomHeight;
86
+ if (typeof document === "undefined" || !document.body) {
87
+ return MAX_DOM_SCROLL_HEIGHT_FALLBACK;
88
+ }
89
+ try {
90
+ // The wrapper is itself an `overflow:auto` scroll container (kept tiny and
91
+ // offscreen so it never affects page layout or scroll), so we can read the
92
+ // height it actually exposes as scrollable - not just the probe's layout
93
+ // height. On high-DPR mobile the two diverge and the scrollable one is the
94
+ // limit that matters.
95
+ const wrap = document.createElement("div");
96
+ wrap.style.cssText =
97
+ "position:fixed;top:0;left:-9999px;width:1px;height:100px;overflow:auto;visibility:hidden;pointer-events:none;";
98
+ const probe = document.createElement("div");
99
+ probe.style.cssText = "width:1px;height:1000000000px;";
100
+ wrap.appendChild(probe);
101
+ document.body.appendChild(wrap);
102
+ const layoutCap = probe.offsetHeight;
103
+ const scrollCap = wrap.scrollHeight;
104
+ document.body.removeChild(wrap);
105
+ detectedMaxDomHeight = resolveMaxDomHeight(layoutCap, scrollCap, MAX_DOM_SCROLL_HEIGHT_FALLBACK);
106
+ }
107
+ catch {
108
+ detectedMaxDomHeight = MAX_DOM_SCROLL_HEIGHT_FALLBACK;
109
+ }
110
+ return detectedMaxDomHeight;
111
+ }
112
+ export function createSvGridController(props) {
113
+ // Resolved capability gates. Capabilities are OFF by default - a bare
114
+ // grid is a plain read-only table, and each power feature is opted into
115
+ // via its shortcut (`editable` / `pageable` / `groupable`) or the matching
116
+ // fine-grained prop (`enableInlineEditing` / `showPagination` /
117
+ // `showGroupingControls`). The shortcut wins when set; otherwise the
118
+ // fine-grained prop wins; otherwise the capability is off. (Sorting and
119
+ // filtering follow the same opt-in model already - they require their
120
+ // feature, injected by `sortable` / `filterable`.)
121
+ const editingEnabled = $derived(props.editable ?? props.enableInlineEditing ?? false);
122
+ const paginationEnabled = $derived(props.pageable ?? props.showPagination ?? false);
123
+ const groupingControlsEnabled = $derived(props.groupable ?? props.showGroupingControls ?? false);
124
+ let globalFilter = $state("");
125
+ let scrollContainer = $state(null);
126
+ let gridRootEl = $state(null);
127
+ let filterRowValues = $state({});
128
+ let filterMenuValues = $state({});
129
+ let verticalScrollbarEl = $state(null);
130
+ let horizontalScrollbarEl = $state(null);
131
+ let scrollVersion = $state(0);
132
+ /**
133
+ * Separate state from `scrollVersion`: only bumped by the ResizeObserver
134
+ * when the shell's CSS size changes. The virtualizer effects below depend
135
+ * on this instead of `scrollVersion` so they DON'T re-run on every scroll
136
+ * event - `scrollVersion` fires constantly during a drag.
137
+ */
138
+ let viewportVersion = $state(0);
139
+ let lastResetSignature = "";
140
+ let pendingScrollTop = 0;
141
+ let pendingScrollLeft = 0;
142
+ let scrollSyncRaf = null;
143
+ let selectionRange = $state({ anchor: null, focus: null });
144
+ // Extra committed ranges for multi-range (Ctrl+drag) selection. The
145
+ // `selectionRange` above is always the ACTIVE range being manipulated; these
146
+ // are the finished ones. Full selection = these + the active range.
147
+ let selectionRanges = $state.raw([]);
148
+ let isDraggingSelection = $state(false);
149
+ /** Excel-style fill handle drag state. While non-null we paint a "fill
150
+ * preview" overlay on cells between the source range and the pointer
151
+ * cell; on pointerup we extrapolate the source pattern into them. */
152
+ let fillDrag = $state(null);
153
+ let activeAtPointerDown = null;
154
+ let editingCell = $state(null);
155
+ // Full-row editing: the row currently in whole-row edit + its per-column
156
+ // draft (keyed by column id). Null when not in full-row mode.
157
+ let fullRowEdit = $state(null);
158
+ let editedCellValues = $state({});
159
+ const UNDO_LIMIT = 200;
160
+ let history = $state([]);
161
+ /** Index in `history` of the LAST applied step. -1 means "nothing applied".
162
+ * undo() decrements; redo() increments. New edits truncate everything
163
+ * past the pointer (the classic "you can't redo after editing" rule). */
164
+ let historyPtr = $state(-1);
165
+ /** Bumps on every undo / redo / record so $derived consumers can
166
+ * observe via the api without subscribing to history directly. */
167
+ let historyVersion = $state(0);
168
+ let tooltip = $state(null);
169
+ let tooltipTimer = null;
170
+ // ---- Find-in-grid ----------------------------------------------------
171
+ let findOpen = $state(false);
172
+ let findQuery = $state('');
173
+ let findHitIndex = $state(0);
174
+ const findHits = $derived.by(() => {
175
+ const q = findQuery.trim().toLowerCase();
176
+ if (!q || !findOpen)
177
+ return [];
178
+ const out = [];
179
+ for (let r = 0; r < allRows.length; r += 1) {
180
+ const row = allRows[r];
181
+ if (!row)
182
+ continue;
183
+ for (let c = 0; c < allColumns.length; c += 1) {
184
+ const col = allColumns[c];
185
+ if (!col)
186
+ continue;
187
+ const v = row.getCellValueByColumnId(col.id);
188
+ if (v == null)
189
+ continue;
190
+ const s = String(v).toLowerCase();
191
+ if (s.includes(q))
192
+ out.push({ rowIndex: r, colIndex: c, columnId: col.id });
193
+ }
194
+ }
195
+ return out;
196
+ });
197
+ let theadEl = $state(null);
198
+ let headerHeight = $state(0);
199
+ /** When an edit starts: true selects all text, false places the caret at the end. */
200
+ let editorSelectAll = true;
201
+ /** Per-column width overrides set by the resize handles. */
202
+ let columnWidths = $state({});
203
+ let resizingColumnId = $state(null);
204
+ let resizeStartX = 0;
205
+ let resizeStartWidth = 0;
206
+ const MIN_COLUMN_WIDTH = 40;
207
+ /** Columns pinned to the left or right edge of the grid (sticky positioning).
208
+ * Seeded from `props.initialColumnPinning` so demos / tests can show the
209
+ * feature on first render without driving the column menu in JS. */
210
+ let columnPinning = $state({
211
+ left: [...(props.initialColumnPinning?.left ?? [])],
212
+ right: [...(props.initialColumnPinning?.right ?? [])],
213
+ });
214
+ let columnVirtualizerVersion = $state(0);
215
+ let gridStateVersion = $state(0);
216
+ const selectionColumnWidth = 44;
217
+ const rowNumberColumnWidth = $derived(props.rowNumberWidth ?? 56);
218
+ const showRowNumbersEffective = $derived(props.showRowNumbers ?? false);
219
+ let columnMenuFor = $state(null);
220
+ let columnMenuTab = $state("general");
221
+ let columnMenuPos = $state({ x: 0, y: 0 });
222
+ let columnMenuSearch = $state("");
223
+ let filterMenuFor = $state(null);
224
+ let filterMenuPos = $state({ x: 0, y: 0 });
225
+ let operatorMenuFor = $state(null);
226
+ let operatorMenuPos = $state({ x: 0, y: 0 });
227
+ let chooseColumnsPos = $state(null);
228
+ let contextMenuFor = $state(null);
229
+ let contextMenuPos = $state({ x: 0, y: 0 });
230
+ // Editable comments: internal overlay (rowId -> columnId -> note) merged on
231
+ // top of props.notes for immediate feedback, plus the open-editor state.
232
+ let noteOverrides = $state({});
233
+ let commentEditFor = $state(null);
234
+ let commentDraft = $state("");
235
+ let valueFilters = $state({});
236
+ const viewportWidth = $derived.by(() => {
237
+ viewportVersion;
238
+ return scrollContainer ? scrollContainer.clientWidth : 0;
239
+ });
240
+ const viewportHeight = $derived.by(() => {
241
+ viewportVersion;
242
+ return scrollContainer ? scrollContainer.clientHeight : 0;
243
+ });
244
+ const scrollMetrics = $derived.by(() => {
245
+ scrollVersion;
246
+ viewportVersion;
247
+ // Track the virtualizers' versions too so when data loads or row /
248
+ // column counts change, scrollMetrics re-reads the DOM's grown
249
+ // scrollHeight / scrollWidth. Without these deps the scrollbar
250
+ // receives a stale `content-size` ≈ 0, its hidden-check trips, it
251
+ // sets `pointer-events: none`, and the user can't drag it. The
252
+ // identifiers below are declared further down - derived callbacks
253
+ // run lazily, so by the time this fires they're in scope.
254
+ virtualizer.version;
255
+ columnVirtualizerVersion;
256
+ return {
257
+ scrollTop: scrollContainer?.scrollTop ?? 0,
258
+ scrollLeft: scrollContainer?.scrollLeft ?? 0,
259
+ clientHeight: scrollContainer?.clientHeight ?? 0,
260
+ clientWidth: scrollContainer?.clientWidth ?? 0,
261
+ scrollHeight: scrollContainer?.scrollHeight ?? 0,
262
+ scrollWidth: scrollContainer?.scrollWidth ?? 0,
263
+ };
264
+ });
265
+ /** Vertical overflow from the virtualizer's authoritative total size,
266
+ * NOT from `scrollMetrics.scrollHeight`. Reading DOM dimensions
267
+ * during a Svelte derived runs BEFORE the browser paints - the table
268
+ * hasn't laid out the new rows yet, so `scrollHeight` is briefly 0
269
+ * even after data loads. That made the overflow flag return false,
270
+ * hid the scrollbar, and broke dragging. */
271
+ const hasVerticalOverflow = $derived.by(() => {
272
+ virtualizer.version;
273
+ return virtualizer.getTotalSize() > viewportHeight + 1;
274
+ });
275
+ // Effective filter-UI flags. Each show* prop wins when explicitly set;
276
+ // otherwise the `filterMode` prop (default 'menu') picks exactly one surface.
277
+ const showGlobalFilterEffective = $derived(props.showGlobalFilter ?? (props.filterMode ?? "menu") === "global");
278
+ const showFilterRowEffective = $derived(props.showFilterRow ?? (props.filterMode ?? "menu") === "row");
279
+ const showColumnFiltersEffective = $derived(props.showColumnFilters ?? (props.filterMode ?? "menu") === "menu");
280
+ // The inline "floating filter" input under each header duplicates the
281
+ // column menu's funnel popover when both are active, so it requires an
282
+ // explicit opt-in via the `showColumnFilters` prop.
283
+ const showInlineColumnFilterEffective = $derived(props.showColumnFilters === true);
284
+ // Effective selection-surface flags. `selectionMode` defaults to 'both' so
285
+ // existing consumers keep their current behaviour.
286
+ const showRowSelectionEffective = $derived(props.showRowSelection ??
287
+ ((props.selectionMode ?? "both") === "row" ||
288
+ (props.selectionMode ?? "both") === "both"));
289
+ const enableCellSelectionEffective = $derived(props.enableCellSelection ??
290
+ ((props.selectionMode ?? "both") === "cell" ||
291
+ (props.selectionMode ?? "both") === "both"));
292
+ // Internal source-of-truth for data and column defs. Seeded from props and
293
+ // re-synced whenever the parent passes a new array; the imperative API
294
+ // mutates these so add/remove operations don't need a callback round-trip.
295
+ // svelte-ignore state_referenced_locally
296
+ let internalData = $state.raw(props.data);
297
+ // Resolve `cellDataType` / `inferColumnTypes` into concrete editorType +
298
+ // format defaults once, up front, so every downstream reader sees a normal
299
+ // column. Explicit fields on the ColumnDef always win.
300
+ // svelte-ignore state_referenced_locally
301
+ const resolveCols = (cols) => resolveColumnTypes(cols, props.data?.[0], props.inferColumnTypes === true);
302
+ // svelte-ignore state_referenced_locally
303
+ let internalColumns = $state.raw(resolveCols(props.columns));
304
+ // svelte-ignore state_referenced_locally
305
+ let hiddenColumns = $state(initialHiddenColumns(props.columns));
306
+ // Collapsible column groups (columnGroupShow). Meta is derived from the tree;
307
+ // `collapsedColumnGroups` is the live set of collapsed group ids, seeded once
308
+ // from each collapsible group's `openByDefault` (default: collapsed).
309
+ const columnGroupMeta = $derived(computeColumnGroupMeta(props.columns));
310
+ // svelte-ignore state_referenced_locally
311
+ let collapsedColumnGroups = $state((() => {
312
+ const meta = computeColumnGroupMeta(props.columns);
313
+ const s = new Set();
314
+ for (const id of meta.collapsibleGroupIds)
315
+ if (!meta.defaultOpen.get(id))
316
+ s.add(id);
317
+ return s;
318
+ })());
319
+ // Leaf ids hidden right now because their group is collapsed/expanded.
320
+ const hiddenByGroupCollapse = $derived(hiddenLeavesForCollapse(columnGroupMeta, collapsedColumnGroups));
321
+ function toggleColumnGroup(groupId) {
322
+ const next = new Set(collapsedColumnGroups);
323
+ if (next.has(groupId))
324
+ next.delete(groupId);
325
+ else
326
+ next.add(groupId);
327
+ collapsedColumnGroups = next;
328
+ }
329
+ function isColumnGroupCollapsed(groupId) {
330
+ return collapsedColumnGroups.has(groupId);
331
+ }
332
+ $effect(() => {
333
+ // When the consumer replaces `data` (e.g. a "Reset" button), drop any
334
+ // accumulated cell-edit overrides - otherwise `getCellDisplayValue`
335
+ // would keep returning the old edited values from `editedCellValues`
336
+ // even though the underlying data has been replaced.
337
+ internalData = props.data;
338
+ editedCellValues = {};
339
+ });
340
+ $effect(() => {
341
+ internalColumns = resolveCols(props.columns);
342
+ });
343
+ // Captured ONCE at mount: `externalSort` is a structural choice (tree vs
344
+ // flat data) so toggling it after mount is not supported. Reading it here
345
+ // - outside the getter below - guarantees the pass-through sort is wired
346
+ // in before `createSvGrid` first reads `_rowModels`.
347
+ // svelte-ignore state_referenced_locally
348
+ const externalSortEnabled = props.externalSort === true;
349
+ // Same one-shot capture for external filtering. Server-side mode means
350
+ // the wrapper records filter state but does not actually filter rows.
351
+ // svelte-ignore state_referenced_locally
352
+ const externalFilterEnabled = props.externalFilter === true;
353
+ const passthroughSortedRowModel = ({ rows }) => rows;
354
+ const grid = createSvGrid({
355
+ get _features() {
356
+ return resolveEffectiveFeatures();
357
+ },
358
+ get _rowModels() {
359
+ // Pagination is intentionally NOT in the grid's row-model pipeline.
360
+ // The wrapper applies its own filters (filterMenuValues, globalFilter,
361
+ // valueFilters) on top of `grid.getRowModel().rows`. If pagination
362
+ // ran first, those filters would only see the visible page. Instead
363
+ // the wrapper paginates last - see `allRows` below.
364
+ return {
365
+ coreRowModel: createCoreRowModel(),
366
+ filteredRowModel: createFilteredRowModel(),
367
+ // External-sort mode: pass the rows through untouched so the consumer
368
+ // controls ordering (e.g. tree data that must preserve hierarchy).
369
+ sortedRowModel: externalSortEnabled
370
+ ? passthroughSortedRowModel
371
+ : createSortedRowModel(sortFns),
372
+ groupedRowModel: createGroupedRowModel(),
373
+ expandedRowModel: createExpandedRowModel(),
374
+ };
375
+ },
376
+ get columns() {
377
+ return internalColumns;
378
+ },
379
+ get data() {
380
+ return internalData;
381
+ },
382
+ get getRowId() {
383
+ return props.getRowId;
384
+ },
385
+ state: {
386
+ columnFilters: [],
387
+ grouping: [],
388
+ sorting: [],
389
+ // svelte-ignore state_referenced_locally
390
+ pagination: { pageIndex: 0, pageSize: props.pageSize ?? 10 },
391
+ rowSelection: {},
392
+ expanded: {},
393
+ activeCell: { rowIndex: 0, colIndex: 0, cellId: null },
394
+ },
395
+ });
396
+ $effect(() => {
397
+ const unsubscribe = grid.store.subscribe(() => {
398
+ gridStateVersion += 1;
399
+ });
400
+ return unsubscribe;
401
+ });
402
+ /**
403
+ * The grid's columns reordered so left-pinned columns come first and
404
+ * right-pinned columns come last. All other code (rendering, keyboard nav,
405
+ * active cell) operates on this ordered view.
406
+ */
407
+ /**
408
+ * User-driven column order (drag-to-reorder OR `api.setColumnOrder`).
409
+ * Stored as a flat list of column ids. Empty = use the natural order
410
+ * from the columns prop. The pin grouping is applied on top of this.
411
+ */
412
+ let userColumnOrder = $state([...(props.columnOrder ?? [])]);
413
+ // Re-seed on prop change so consumers can drive order from outside.
414
+ let lastSeededOrder = "";
415
+ $effect(() => {
416
+ const incoming = props.columnOrder
417
+ ? [...props.columnOrder].join("|")
418
+ : "";
419
+ if (incoming === lastSeededOrder)
420
+ return;
421
+ lastSeededOrder = incoming;
422
+ userColumnOrder = props.columnOrder ? [...props.columnOrder] : [];
423
+ });
424
+ const allColumns = $derived.by(() => {
425
+ let raw = grid
426
+ .getAllColumns()
427
+ .filter((column) => !hiddenColumns[column.id] && !hiddenByGroupCollapse[column.id]);
428
+ // Apply user reorder (if any). Unknown ids in userColumnOrder are
429
+ // skipped; columns not in userColumnOrder keep their original
430
+ // relative order after the user-ordered ones.
431
+ if (userColumnOrder.length > 0) {
432
+ const byId = new Map(raw.map((c) => [c.id, c]));
433
+ const seen = new Set();
434
+ const ordered = [];
435
+ for (const id of userColumnOrder) {
436
+ const c = byId.get(id);
437
+ if (c && !seen.has(id)) {
438
+ ordered.push(c);
439
+ seen.add(id);
440
+ }
441
+ }
442
+ for (const c of raw) {
443
+ if (!seen.has(c.id))
444
+ ordered.push(c);
445
+ }
446
+ raw = ordered;
447
+ }
448
+ const leftIds = columnPinning.left;
449
+ const rightIds = columnPinning.right;
450
+ if (!leftIds.length && !rightIds.length)
451
+ return raw;
452
+ const pinned = new Set([...leftIds, ...rightIds]);
453
+ const findById = (id) => raw.find((column) => column.id === id);
454
+ const left = leftIds
455
+ .map(findById)
456
+ .filter((c) => Boolean(c));
457
+ const right = rightIds
458
+ .map(findById)
459
+ .filter((c) => Boolean(c));
460
+ const unpinned = raw.filter((column) => !pinned.has(column.id));
461
+ return [...left, ...unpinned, ...right];
462
+ });
463
+ /** Header groups reordered to match {@link allColumns}. */
464
+ const headerGroups = $derived.by(() => {
465
+ const base = grid.getHeaderGroups();
466
+ if (!base.length)
467
+ return base;
468
+ const byId = new Map(base[0].headers.map((header) => [header.column.id, header]));
469
+ const headers = [];
470
+ for (const column of allColumns) {
471
+ const header = byId.get(column.id);
472
+ if (header)
473
+ headers.push(header);
474
+ }
475
+ return [{ id: base[0].id, headers }];
476
+ });
477
+ const groupHeaderRows = $derived.by(() => {
478
+ const userCols = props.columns ?? [];
479
+ // 1. Find max depth in the user-provided column tree.
480
+ function maxDepth(defs) {
481
+ let m = 0;
482
+ for (const d of defs) {
483
+ if (d.columns?.length) {
484
+ m = Math.max(m, 1 + maxDepth(d.columns));
485
+ }
486
+ }
487
+ return m;
488
+ }
489
+ const depth = maxDepth(userCols);
490
+ if (depth === 0)
491
+ return [];
492
+ const leafEntries = [];
493
+ function buildId(def, parentId, fallbackIx) {
494
+ return def.id ?? def.field ?? `${parentId ?? 'col'}_d_${fallbackIx}`;
495
+ }
496
+ // Leaves hidden by a collapsed/expanded group are skipped everywhere here,
497
+ // so group colSpan + widthPx exclude them and stay aligned with the leaves
498
+ // the body actually renders.
499
+ const hiddenLeaf = hiddenByGroupCollapse;
500
+ function collectLeaves(defs, parentId, depthHere) {
501
+ defs.forEach((def, ix) => {
502
+ const id = buildId(def, parentId, ix);
503
+ if (def.columns?.length) {
504
+ collectLeaves(def.columns, id, depthHere + 1);
505
+ }
506
+ else if (!hiddenLeaf[id]) {
507
+ leafEntries.push({ id, widthPx: getColumnWidth(id) });
508
+ }
509
+ });
510
+ }
511
+ collectLeaves(userCols, undefined, 0);
512
+ function indexTree(defs, parentId, cursor) {
513
+ const nodes = [];
514
+ for (const def of defs) {
515
+ const id = buildId(def, parentId, nodes.length);
516
+ // Skip leaves the collapse state hides, so leaf indices/colSpans match
517
+ // `leafEntries` (and the body's rendered columns) exactly.
518
+ if (!def.columns?.length && hiddenLeaf[id])
519
+ continue;
520
+ const leafStart = cursor.leaf;
521
+ if (def.columns?.length) {
522
+ indexTree(def.columns, id, cursor);
523
+ }
524
+ else {
525
+ cursor.leaf += 1;
526
+ }
527
+ const leafEnd = cursor.leaf;
528
+ nodes.push({ def, id, leafStart, leafEnd });
529
+ }
530
+ return nodes;
531
+ }
532
+ const cursor = { leaf: 0 };
533
+ const topNodes = indexTree(userCols, undefined, cursor);
534
+ function nodesAtDepth(nodes, currentDepth, targetDepth) {
535
+ if (currentDepth === targetDepth)
536
+ return nodes;
537
+ const out = [];
538
+ for (const n of nodes) {
539
+ if (n.def.columns?.length) {
540
+ const childCursor = { leaf: n.leafStart };
541
+ const children = indexTree(n.def.columns, n.id, childCursor);
542
+ out.push(...nodesAtDepth(children, currentDepth + 1, targetDepth));
543
+ }
544
+ else {
545
+ // Leaf reached early - emit a placeholder at this row so the
546
+ // column above it stays empty (the leaf itself renders in the
547
+ // bottom leaf-header row, not here).
548
+ out.push(n);
549
+ }
550
+ }
551
+ return out;
552
+ }
553
+ function sumLeafWidths(from, to) {
554
+ let sum = 0;
555
+ for (let i = from; i < to; i += 1)
556
+ sum += leafEntries[i]?.widthPx ?? 0;
557
+ return sum;
558
+ }
559
+ const rows = [];
560
+ for (let d = 0; d < depth; d += 1) {
561
+ const at = nodesAtDepth(topNodes, 0, d);
562
+ const cells = at.map((n) => {
563
+ const isLeafEarly = !n.def.columns?.length;
564
+ const headerText = typeof n.def.header === 'string' ? n.def.header : '';
565
+ const collapsible = columnGroupMeta.collapsibleGroupIds.has(n.id);
566
+ return {
567
+ key: `${n.id}_d${d}`,
568
+ label: isLeafEarly ? '' : headerText,
569
+ colSpan: Math.max(1, n.leafEnd - n.leafStart),
570
+ widthPx: sumLeafWidths(n.leafStart, n.leafEnd),
571
+ firstLeafIndex: n.leafStart,
572
+ isPlaceholder: isLeafEarly,
573
+ groupId: collapsible ? n.id : undefined,
574
+ collapsible,
575
+ collapsed: collapsible && collapsedColumnGroups.has(n.id),
576
+ };
577
+ });
578
+ rows.push({ id: `gh_${d}`, cells });
579
+ }
580
+ return rows;
581
+ });
582
+ /** Cumulative pixel offsets for left- and right-pinned columns. */
583
+ const pinnedOffsets = $derived.by(() => {
584
+ const rowNumberWidth = showRowNumbersEffective ? rowNumberColumnWidth : 0;
585
+ const selectionWidth = showRowSelectionEffective ? selectionColumnWidth : 0;
586
+ const left = {};
587
+ let leftAcc = rowNumberWidth + selectionWidth;
588
+ for (const id of columnPinning.left) {
589
+ left[id] = leftAcc;
590
+ leftAcc += getColumnWidth(id);
591
+ }
592
+ const right = {};
593
+ let rightAcc = 0;
594
+ for (let i = columnPinning.right.length - 1; i >= 0; i -= 1) {
595
+ const id = columnPinning.right[i];
596
+ if (!id)
597
+ continue;
598
+ right[id] = rightAcc;
599
+ rightAcc += getColumnWidth(id);
600
+ }
601
+ return { left, right };
602
+ });
603
+ // ---- Column reorder (drag headers) ----------------------------------
604
+ // Live drag state for the built-in header drag-to-reorder. Only set
605
+ // when `props.enableColumnReorder` is true.
606
+ let colDragId = $state(null);
607
+ let colDropOnId = $state(null);
608
+ let colDropSide = $state(null);
609
+ // Live drag state for managed row dragging. Only meaningful while a row is
610
+ // being dragged (`props.rowDragManaged`). `rowDropIndex` is the visible row
611
+ // index currently hovered; `rowDropSide` says which edge the drop line paints.
612
+ let rowDragActive = $state(false);
613
+ let rowDropIndex = $state(null);
614
+ let rowDropSide = $state(null);
615
+ // ---- Conditional formatting --------------------------------------------
616
+ // True when the feature is in use; gates the per-cell positioning context
617
+ // (cells are otherwise non-relative for scroll performance).
618
+ const hasConditionalFormats = $derived((props.conditionalFormats?.length ?? 0) > 0);
619
+ // Per-column numeric min/max, needed only by colorScale / dataBar formats.
620
+ // Lazy: this derived never runs unless `conditionalFormats` is set.
621
+ const conditionalColumnStats = $derived.by(() => {
622
+ const map = new Map();
623
+ const formats = props.conditionalFormats;
624
+ if (!formats?.length || !formatsNeedingStats(formats))
625
+ return map;
626
+ for (const column of allColumns) {
627
+ const needs = formats.some((f) => (f.type === "colorScale" || f.type === "dataBar") &&
628
+ (!f.columns || f.columns.includes(column.id)));
629
+ if (!needs)
630
+ continue;
631
+ const def = column.columnDef;
632
+ const accessorFn = def.accessorFn;
633
+ const field = def.field;
634
+ const stat = computeColumnStat((function* () {
635
+ for (const row of allRows) {
636
+ yield accessorFn
637
+ ? accessorFn(row.original)
638
+ : field
639
+ ? row.original[field]
640
+ : row.getCellValueByColumnId(column.id);
641
+ }
642
+ })());
643
+ if (stat)
644
+ map.set(column.id, stat);
645
+ }
646
+ return map;
647
+ });
648
+ const sortDirectionByColumn = $derived.by(() => {
649
+ gridStateVersion;
650
+ const directions = {};
651
+ for (const column of allColumns)
652
+ directions[column.id] = column.getIsSorted();
653
+ return directions;
654
+ });
655
+ const groupingColumns = $derived.by(() => {
656
+ gridStateVersion;
657
+ return grid.getState().grouping ?? [];
658
+ });
659
+ const paginationState = $derived.by(() => {
660
+ gridStateVersion;
661
+ return grid.getState().pagination ?? { pageIndex: 0, pageSize: 10 };
662
+ });
663
+ /**
664
+ * Rows AFTER all filtering but BEFORE pagination. Used by the pager to
665
+ * compute the correct "X to Y of Z" range and total page count when
666
+ * filters reduce the dataset.
667
+ */
668
+ const allRowsBeforePagination = $derived.by(() => {
669
+ gridStateVersion;
670
+ // Touch internalData + internalColumns so the row model re-derives when
671
+ // the consumer replaces the data array (e.g. via a "Reset" button).
672
+ void internalData;
673
+ void internalColumns;
674
+ const rawRows = grid.getRowModel().rows;
675
+ // External-filter mode: the consumer fetched / pre-filtered the rows
676
+ // themselves (server-side data sources). Skip every local filter pass
677
+ // so the data isn't double-filtered against the visible page.
678
+ if (externalFilterEnabled)
679
+ return rawRows;
680
+ let rows = rawRows;
681
+ if (globalFilter.trim()) {
682
+ const needle = normalizeForFilter(globalFilter, props.filterLocale);
683
+ rows = rows.filter((row) => row
684
+ .getAllCells()
685
+ .some((cell) => normalizeForFilter(String(cell.getValue() ?? ""), props.filterLocale)
686
+ .includes(needle)));
687
+ }
688
+ // A single condition is "active" if it has the value(s) it needs.
689
+ const condActive = (op, value, valueTo) => {
690
+ if (op === "isBlank")
691
+ return true;
692
+ if (op === "between")
693
+ return value.trim().length > 0 && (valueTo ?? "").trim().length > 0;
694
+ return value.trim().length > 0;
695
+ };
696
+ const evalCond = (cellValue, columnId, op, value, valueTo) => applyExcelFilter(cellValue, { id: columnId, operator: op, value, valueTo: op === "between" ? valueTo : undefined }, { locale: props.filterLocale });
697
+ // A column filter is active if either of its (up to two) conditions is.
698
+ const menuFilters = Object.entries(filterMenuValues).filter(([_, f]) => {
699
+ const a = condActive(f.operator, f.value, f.valueTo);
700
+ const b = !!f.operator2 && condActive(f.operator2, f.value2 ?? "", f.valueTo2);
701
+ return a || b;
702
+ });
703
+ if (menuFilters.length) {
704
+ rows = rows.filter((row) => menuFilters.every(([columnId, f]) => {
705
+ const cellValue = getRowColumnValue(row, columnId);
706
+ const aActive = condActive(f.operator, f.value, f.valueTo);
707
+ const bActive = !!f.operator2 && condActive(f.operator2, f.value2 ?? "", f.valueTo2);
708
+ const ra = aActive ? evalCond(cellValue, columnId, f.operator, f.value, f.valueTo) : null;
709
+ const rb = bActive
710
+ ? evalCond(cellValue, columnId, f.operator2, f.value2 ?? "", f.valueTo2)
711
+ : null;
712
+ if (ra === null)
713
+ return rb ?? true;
714
+ if (rb === null)
715
+ return ra;
716
+ return f.join === "OR" ? ra || rb : ra && rb;
717
+ }));
718
+ }
719
+ const valueFilterEntries = Object.entries(valueFilters);
720
+ if (valueFilterEntries.length) {
721
+ // Resolve bucket defs up front so we don't re-hit the derived map
722
+ // for every row × column combination. Columns without bucketing
723
+ // map to `null` here and fall through to exact-value matching.
724
+ const bucketEntries = valueFilterEntries.map(([columnId, allowed]) => ({
725
+ columnId,
726
+ allowed,
727
+ buckets: facetBucketsByColumn.get(columnId) ?? null,
728
+ }));
729
+ rows = rows.filter((row) => bucketEntries.every(({ columnId, allowed, buckets }) => {
730
+ const raw = getRowColumnValue(row, columnId);
731
+ if (buckets) {
732
+ // Range-bucketed filter: find which bucket this row's value
733
+ // falls into and check whether that bucket's label is allowed.
734
+ const isDate = buckets[0].isDate;
735
+ const num = rawToNumber(raw, isDate);
736
+ if (!Number.isFinite(num))
737
+ return false;
738
+ for (const bucket of buckets) {
739
+ if (isInBucket(num, bucket))
740
+ return allowed.has(bucket.label);
741
+ }
742
+ return false;
743
+ }
744
+ return allowed.has(String(raw ?? ""));
745
+ }));
746
+ }
747
+ return rows;
748
+ });
749
+ /**
750
+ * Visible rows for the current page. Applied last so filters operate on
751
+ * the full dataset rather than the current page (see the comment above
752
+ * `_rowModels`).
753
+ */
754
+ const allRows = $derived.by(() => {
755
+ const rows = allRowsBeforePagination;
756
+ if (!paginationEnabled)
757
+ return rows;
758
+ const { pageIndex, pageSize } = paginationState;
759
+ const start = pageIndex * pageSize;
760
+ return rows.slice(start, start + pageSize);
761
+ });
762
+ const rowSelectionState = $derived.by(() => {
763
+ gridStateVersion;
764
+ return grid.getState().rowSelection ?? {};
765
+ });
766
+ // Forward selection changes to the consumer. Skips the very first invocation
767
+ // (the initial empty state) so consumers don't get a spurious callback on mount.
768
+ let lastSelectionSerialized = "";
769
+ $effect(() => {
770
+ const serialized = JSON.stringify(rowSelectionState);
771
+ if (serialized === lastSelectionSerialized)
772
+ return;
773
+ lastSelectionSerialized = serialized;
774
+ const callback = props.onRowSelectionChange;
775
+ if (!callback)
776
+ return;
777
+ const data = internalData;
778
+ const selectedRows = [];
779
+ for (let i = 0; i < data.length; i++) {
780
+ if (rowSelectionState[String(i)])
781
+ selectedRows.push(data[i]);
782
+ }
783
+ callback(rowSelectionState, selectedRows);
784
+ });
785
+ // Forward cell-selection rectangle changes to the consumer. Same
786
+ // dedupe pattern - fires only when the serialized rectangle changes
787
+ // so consumers don't see spurious callbacks during re-renders.
788
+ let lastCellRangeSerialized = "";
789
+ $effect(() => {
790
+ const a = selectionRange.anchor;
791
+ const f = selectionRange.focus;
792
+ const ranges = a && f
793
+ ? [[
794
+ Math.min(a.rowIndex, f.rowIndex),
795
+ Math.min(a.colIndex, f.colIndex),
796
+ Math.max(a.rowIndex, f.rowIndex),
797
+ Math.max(a.colIndex, f.colIndex),
798
+ ]]
799
+ : [];
800
+ const serialized = JSON.stringify(ranges);
801
+ if (serialized === lastCellRangeSerialized)
802
+ return;
803
+ lastCellRangeSerialized = serialized;
804
+ props.onCellSelectionChange?.(ranges);
805
+ });
806
+ // ---- Status bar: live aggregates of the selected cell range -----------
807
+ const statusBarEnabled = $derived(props.statusBar != null && props.statusBar !== false);
808
+ const statusBarAggregates = $derived(typeof props.statusBar === "object" && props.statusBar.aggregates
809
+ ? props.statusBar.aggregates
810
+ : ["count", "sum", "avg", "min", "max"]);
811
+ const statusBarStats = $derived.by(() => {
812
+ if (!statusBarEnabled)
813
+ return null;
814
+ const a = selectionRange.anchor;
815
+ const f = selectionRange.focus;
816
+ if (!a || !f)
817
+ return null;
818
+ const minR = Math.min(a.rowIndex, f.rowIndex);
819
+ const maxR = Math.max(a.rowIndex, f.rowIndex);
820
+ const minC = Math.min(a.colIndex, f.colIndex);
821
+ const maxC = Math.max(a.colIndex, f.colIndex);
822
+ let count = 0;
823
+ let numericCount = 0;
824
+ let sum = 0;
825
+ let min = Number.POSITIVE_INFINITY;
826
+ let max = Number.NEGATIVE_INFINITY;
827
+ for (let r = minR; r <= maxR; r += 1) {
828
+ const row = allRows[r];
829
+ if (!row || isGroupRow(row))
830
+ continue;
831
+ for (let c = minC; c <= maxC; c += 1) {
832
+ const col = allColumns[c];
833
+ if (!col)
834
+ continue;
835
+ count += 1;
836
+ const base = getColumnBaseValue(row, col);
837
+ const v = getCellDisplayValue(row.id, col.id, base);
838
+ if (v == null || v === "")
839
+ continue;
840
+ const n = Number(v);
841
+ if (!Number.isFinite(n))
842
+ continue;
843
+ numericCount += 1;
844
+ sum += n;
845
+ if (n < min)
846
+ min = n;
847
+ if (n > max)
848
+ max = n;
849
+ }
850
+ }
851
+ if (count <= 1)
852
+ return null;
853
+ return {
854
+ count,
855
+ numericCount,
856
+ sum,
857
+ avg: numericCount ? sum / numericCount : 0,
858
+ min: numericCount ? min : 0,
859
+ max: numericCount ? max : 0,
860
+ };
861
+ });
862
+ // ---- Tool panel (docked columns sidebar) -------------------------------
863
+ // svelte-ignore state_referenced_locally
864
+ let toolPanelOpen = $state(props.toolPanelDefaultOpen === true);
865
+ // svelte-ignore state_referenced_locally
866
+ let toolPanelTab = $state(props.toolPanelDefaultTab ?? "columns");
867
+ const toolPanelEnabled = $derived(props.toolPanel === true);
868
+ // Every column (including hidden ones) in the user's current order, so the
869
+ // panel can toggle/reorder anything. Group columns are flagged live.
870
+ const toolPanelColumns = $derived.by(() => {
871
+ gridStateVersion;
872
+ const all = grid.getAllColumns();
873
+ if (!userColumnOrder.length)
874
+ return all;
875
+ const byId = new Map(all.map((c) => [c.id, c]));
876
+ const ordered = [];
877
+ const seen = new Set();
878
+ for (const id of userColumnOrder) {
879
+ const c = byId.get(id);
880
+ if (c && !seen.has(id)) {
881
+ ordered.push(c);
882
+ seen.add(id);
883
+ }
884
+ }
885
+ for (const c of all)
886
+ if (!seen.has(c.id))
887
+ ordered.push(c);
888
+ return ordered;
889
+ });
890
+ // Forward sort-clause changes to the consumer. Same dedupe pattern as the
891
+ // selection callback above - fires only when the serialized clauses change.
892
+ let lastSortingSerialized = "";
893
+ $effect(() => {
894
+ gridStateVersion;
895
+ const sorting = (grid.getState().sorting ?? []);
896
+ const serialized = JSON.stringify(sorting);
897
+ if (serialized === lastSortingSerialized)
898
+ return;
899
+ lastSortingSerialized = serialized;
900
+ props.onSortingChange?.(sorting);
901
+ });
902
+ // Forward filter-state changes to the consumer. Consolidates the three
903
+ // wrapper-managed filter stores (global text, per-column operator filters,
904
+ // facet checklists) into one shape so server-side consumers can build a
905
+ // single query. Skipped entirely when no callback is registered to avoid
906
+ // serializing on every keystroke.
907
+ let lastFiltersSerialized = "";
908
+ $effect(() => {
909
+ if (!props.onFiltersChange)
910
+ return;
911
+ const menuEntries = Object.entries(filterMenuValues)
912
+ .filter(([, f]) => {
913
+ if (f.operator === "isBlank")
914
+ return true;
915
+ if (f.operator === "between") {
916
+ return f.value.trim().length > 0 && (f.valueTo ?? "").trim().length > 0;
917
+ }
918
+ return f.value.trim().length > 0;
919
+ })
920
+ .map(([id, f]) => ({
921
+ id,
922
+ operator: f.operator,
923
+ value: f.value,
924
+ ...(f.operator === "between" && f.valueTo
925
+ ? { valueTo: f.valueTo }
926
+ : {}),
927
+ }));
928
+ const valueEntries = Object.entries(valueFilters).map(([id, allowed]) => ({
929
+ id,
930
+ operator: "equals",
931
+ value: "",
932
+ selectedValues: Array.from(allowed).sort(),
933
+ }));
934
+ const merged = new Map();
935
+ for (const entry of menuEntries)
936
+ merged.set(entry.id, entry);
937
+ for (const entry of valueEntries) {
938
+ const existing = merged.get(entry.id);
939
+ merged.set(entry.id, existing
940
+ ? { ...existing, selectedValues: entry.selectedValues }
941
+ : entry);
942
+ }
943
+ const payload = {
944
+ global: globalFilter,
945
+ columns: Array.from(merged.values()),
946
+ };
947
+ const serialized = JSON.stringify(payload);
948
+ if (serialized === lastFiltersSerialized)
949
+ return;
950
+ lastFiltersSerialized = serialized;
951
+ props.onFiltersChange(payload);
952
+ });
953
+ const virtualizer = createSvelteVirtualizer({
954
+ count: 0,
955
+ estimateSize: 36,
956
+ overscan: 8,
957
+ viewportHeight: 520,
958
+ scrollOffset: 0,
959
+ });
960
+ const columnVirtualizer = createColumnVirtualizer({
961
+ count: 0,
962
+ viewportWidth: 0,
963
+ overscan: 3,
964
+ estimateSize: () => 140,
965
+ });
966
+ columnVirtualizer.subscribe(() => {
967
+ columnVirtualizerVersion += 1;
968
+ });
969
+ const rowVirtualizationEnabled = $derived((props.virtualization ?? true) && allRows.length > 0);
970
+ const columnVirtualizationEnabled = $derived((props.columnVirtualization ?? true) && allColumns.length > 0);
971
+ const virtualRows = $derived.by(() => {
972
+ virtualizer.version;
973
+ return virtualizer.getVirtualItems();
974
+ });
975
+ const virtualRowTotalSize = $derived.by(() => {
976
+ virtualizer.version;
977
+ return virtualizer.getTotalSize();
978
+ });
979
+ const virtualRowStart = $derived.by(() => virtualRows[0]?.start ?? 0);
980
+ const virtualRowEnd = $derived.by(() => virtualRows[virtualRows.length - 1]?.end ?? 0);
981
+ const virtualRowBottomSpacer = $derived.by(() => Math.max(virtualRowTotalSize - virtualRowEnd, 0));
982
+ // --- Huge-list scroll scaling -----------------------------------------
983
+ // Browsers cap how tall a single element may be, and mobile caps sit well
984
+ // below desktop. Past a few hundred thousand rows the true content height
985
+ // (count * rowHeight) exceeds that cap, the scroll container silently
986
+ // clamps its scrollHeight, and the last rows become unreachable - e.g. a
987
+ // 1,000,000-row grid that only scrolls to ~994,000 on a phone.
988
+ //
989
+ // When the true height exceeds the browser's max element height we cap the
990
+ // DOM scroll height and map between the limited DOM scroll range and the
991
+ // full logical range (the "scaling" technique from react-virtualized): the
992
+ // spacers are sized in the capped DOM space, while the virtualizer keeps
993
+ // working in true logical pixels. We detect the real per-browser cap at
994
+ // runtime (Chrome ~33.5M, Firefox ~17.9M, mobile lower) rather than guess a
995
+ // constant, so scaling activates only when genuinely needed and stays as
996
+ // fine-grained as the browser allows. For normal-sized grids scaling is
997
+ // inert and every value below reduces to the original behavior.
998
+ // Build the scaling mapping from the current true height + detected browser
999
+ // cap + viewport. The pure, unit-tested math lives in
1000
+ // ./virtualization/scroll-scaling; here we only feed it reactive inputs.
1001
+ // Inert (identity) for normal-sized grids.
1002
+ const rowScrollScaling = $derived(createRowScrollScaling(virtualRowTotalSize, getMaxDomScrollHeight(), viewportHeight));
1003
+ const rowDomTotalSize = $derived(rowScrollScaling.domTotal);
1004
+ const rowScrollScalingActive = $derived(rowScrollScaling.active);
1005
+ // Map a DOM scrollTop to the virtualizer's logical scroll offset, and back.
1006
+ function domToLogicalRowOffset(domTop) {
1007
+ return rowScrollScaling.domToLogical(domTop);
1008
+ }
1009
+ function logicalToDomRowOffset(logical) {
1010
+ return rowScrollScaling.logicalToDom(logical);
1011
+ }
1012
+ // px the logical row positions must shift to land inside the capped DOM
1013
+ // coordinate space (0 when not scaling). Derived from the virtualizer's
1014
+ // OWN committed scroll offset - not the live DOM scrollTop - so the spacer
1015
+ // shift and the rendered window are always computed from the same state and
1016
+ // can never skew by a frame (which would jitter at extreme scale).
1017
+ const rowOffsetAdjustment = $derived.by(() => {
1018
+ if (!rowScrollScalingActive)
1019
+ return 0;
1020
+ virtualizer.version;
1021
+ const logical = virtualizer.getState().scrollOffset;
1022
+ return logical - rowScrollScaling.logicalToDom(logical);
1023
+ });
1024
+ // Spacer heights in DOM space. With scaling inert these equal the original
1025
+ // virtualRowStart / virtualRowBottomSpacer.
1026
+ const rowTopSpacer = $derived(Math.max(virtualRowStart - rowOffsetAdjustment, 0));
1027
+ const rowBottomSpacer = $derived(Math.max(rowDomTotalSize - (virtualRowEnd - rowOffsetAdjustment), 0));
1028
+ const virtualColumns = $derived.by(() => {
1029
+ columnVirtualizerVersion;
1030
+ return columnVirtualizer.getVirtualItems();
1031
+ });
1032
+ const virtualColumnTotalSize = $derived.by(() => {
1033
+ columnVirtualizerVersion;
1034
+ return columnVirtualizer.getTotalSize();
1035
+ });
1036
+ const renderedColumnItems = $derived.by(() => {
1037
+ if (columnVirtualizationEnabled)
1038
+ return virtualColumns;
1039
+ let start = 0;
1040
+ return allColumns.map((column, index) => {
1041
+ const size = getColumnWidth(column.id);
1042
+ const item = { index, key: index, size, start, end: start + size };
1043
+ start += size;
1044
+ return item;
1045
+ });
1046
+ });
1047
+ const renderedColumns = $derived.by(() => renderedColumnItems
1048
+ .map((item) => ({ item, column: allColumns[item.index] }))
1049
+ .filter(hasRenderedColumn));
1050
+ const totalColumnWidth = $derived.by(() => {
1051
+ if (columnVirtualizationEnabled)
1052
+ return virtualColumnTotalSize;
1053
+ let total = 0;
1054
+ for (const column of allColumns)
1055
+ total += getColumnWidth(column.id);
1056
+ return total;
1057
+ });
1058
+ /** Horizontal overflow derived from the SOURCE OF TRUTH (column widths
1059
+ * + leading sticky columns) compared to the viewport. We can't use
1060
+ * `totalColumnWidth` here when column virtualization is on - that
1061
+ * returns the column virtualizer's cached total, which only updates
1062
+ * on `setOptions()` / scroll, NOT when `fittedColumnWidths` finishes
1063
+ * scaling on first measure. Reading `getColumnWidth(c.id)` for every
1064
+ * column instead is reactive to both `columnWidths` and
1065
+ * `fittedColumnWidths`, so the overflow decision settles in the same
1066
+ * render where fit-scaling lands - no race, no scrollbar flash. */
1067
+ const hasHorizontalOverflow = $derived.by(() => {
1068
+ const fixedCols = (showRowNumbersEffective ? rowNumberColumnWidth : 0) +
1069
+ (showRowSelectionEffective ? selectionColumnWidth : 0);
1070
+ let total = fixedCols;
1071
+ for (const column of allColumns)
1072
+ total += getColumnWidth(column.id);
1073
+ // +1 to tolerate sub-pixel rounding residue from `fitColumns`.
1074
+ return total > viewportWidth + 1;
1075
+ });
1076
+ const columnWindowStart = $derived.by(() => renderedColumnItems[0]?.start ?? 0);
1077
+ const columnWindowEnd = $derived.by(() => renderedColumnItems[renderedColumnItems.length - 1]?.end ?? 0);
1078
+ const columnWindowRightSpacer = $derived.by(() => Math.max(totalColumnWidth - columnWindowEnd, 0));
1079
+ const activeCell = $derived.by(() => {
1080
+ gridStateVersion;
1081
+ return (grid.getState().activeCell ?? { rowIndex: 0, colIndex: 0, cellId: null });
1082
+ });
1083
+ const activeDescendantId = $derived.by(() => {
1084
+ const active = activeCell;
1085
+ const inRows = active.rowIndex >= 0 && active.rowIndex < allRows.length;
1086
+ const inCols = active.colIndex >= 0 && active.colIndex < allColumns.length;
1087
+ if (!inRows || !inCols)
1088
+ return null;
1089
+ return getGridCellDomId("svgrid", active.rowIndex, active.colIndex);
1090
+ });
1091
+ // Above this many cells (rows x columns) the summary aggregation is
1092
+ // deferred one animation frame so it never blocks first paint - a
1093
+ // 100k x 50 grid would otherwise spend seconds summing reactive cells
1094
+ // before the grid ever appears. Smaller grids compute inline so the
1095
+ // footer is correct on the first frame (no flicker).
1096
+ const SUMMARY_DEFER_CELL_LIMIT = 50000;
1097
+ let summaryByColumn = $state({});
1098
+ $effect(() => {
1099
+ // Re-aggregate whenever the visible data, columns, edits, or any
1100
+ // state that reorders/filters rows changes.
1101
+ gridStateVersion;
1102
+ void editedCellValues;
1103
+ const rows = allRows;
1104
+ const columns = allColumns;
1105
+ if (!(props.enableRowSummaries ?? true)) {
1106
+ summaryByColumn = {};
1107
+ return;
1108
+ }
1109
+ if (rows.length * columns.length <= SUMMARY_DEFER_CELL_LIMIT ||
1110
+ typeof requestAnimationFrame === "undefined") {
1111
+ summaryByColumn = computeSummaries(rows, columns);
1112
+ return;
1113
+ }
1114
+ // Large grid: paint first, total a frame later.
1115
+ let cancelled = false;
1116
+ const handle = requestAnimationFrame(() => {
1117
+ if (!cancelled)
1118
+ summaryByColumn = computeSummaries(rows, columns);
1119
+ });
1120
+ return () => {
1121
+ cancelled = true;
1122
+ cancelAnimationFrame(handle);
1123
+ };
1124
+ });
1125
+ $effect(() => {
1126
+ if (!theadEl)
1127
+ return;
1128
+ headerHeight = theadEl.offsetHeight;
1129
+ const observer = new ResizeObserver(() => {
1130
+ headerHeight = theadEl?.offsetHeight ?? 0;
1131
+ });
1132
+ observer.observe(theadEl);
1133
+ return () => observer.disconnect();
1134
+ });
1135
+ // Bump scrollVersion when the table's layout size changes so scrollbar
1136
+ // visibility (and the thumb math that depends on scroll metrics) updates
1137
+ // after column resize / show-hide / add-remove.
1138
+ $effect(() => {
1139
+ if (!gridRootEl)
1140
+ return;
1141
+ const observer = new ResizeObserver(() => {
1142
+ scrollVersion += 1;
1143
+ });
1144
+ observer.observe(gridRootEl);
1145
+ return () => observer.disconnect();
1146
+ });
1147
+ $effect(() => {
1148
+ if (!allRows.length || !allColumns.length)
1149
+ return;
1150
+ const active = grid.getState().activeCell;
1151
+ if (active?.cellId)
1152
+ return;
1153
+ grid.setActiveCell({
1154
+ rowIndex: 0,
1155
+ colIndex: 0,
1156
+ cellId: getGridCellDomId("svgrid", 0, 0),
1157
+ });
1158
+ });
1159
+ $effect(() => {
1160
+ // Only reset scroll + selection + editing when the COLUMN SCHEMA
1161
+ // changes. Data length is too weak a signal:
1162
+ // - Streaming inserts grow the length and shouldn't move scroll.
1163
+ // - Filter / delete events shrink the length and shouldn't either
1164
+ // (the user's spot in the data is what they care about).
1165
+ // - Sort changes preserve length but mean "start from the top",
1166
+ // so callers who want that should drive it explicitly via
1167
+ // api.scrollToTop() (or the equivalent).
1168
+ // The columns ARE a schema change: existing scroll/selection
1169
+ // coordinates are no longer meaningful when the grid's column set
1170
+ // is replaced, so we still reset there.
1171
+ const colCount = props.columns.length;
1172
+ const nextSignature = `cols:${colCount}`;
1173
+ if (nextSignature === lastResetSignature)
1174
+ return;
1175
+ const isFirstRender = lastResetSignature === "";
1176
+ lastResetSignature = nextSignature;
1177
+ if (isFirstRender)
1178
+ return;
1179
+ selectionRange = { anchor: null, focus: null };
1180
+ selectionRanges = [];
1181
+ editingCell = null;
1182
+ if (scrollContainer) {
1183
+ scrollContainer.scrollTop = 0;
1184
+ scrollContainer.scrollLeft = 0;
1185
+ scrollVersion += 1;
1186
+ }
1187
+ virtualizer.setScrollOffset(0);
1188
+ columnVirtualizer.setHorizontalOffset(0);
1189
+ });
1190
+ // Wire scroll-change listeners SEPARATELY for each scrollbar - bundling
1191
+ // them in one effect with `if (!vertical || !horizontal) return` was
1192
+ // the bug behind "vertical scrollbar can't be dragged": with overflow
1193
+ // gating, demos without horizontal overflow never mount the horizontal
1194
+ // scrollbar, the combined guard tripped, and the vertical listener
1195
+ // never got attached either. Each scrollbar is now independent.
1196
+ $effect(() => {
1197
+ if (!scrollContainer || !verticalScrollbarEl)
1198
+ return;
1199
+ const el = verticalScrollbarEl;
1200
+ const onVertical = (event) => {
1201
+ const container = scrollContainer;
1202
+ if (!container)
1203
+ return;
1204
+ const customEvent = event;
1205
+ container.scrollTop = customEvent.detail.value;
1206
+ scheduleScrollSync(container.scrollTop, container.scrollLeft);
1207
+ };
1208
+ el.addEventListener("scroll-change", onVertical);
1209
+ return () => el.removeEventListener("scroll-change", onVertical);
1210
+ });
1211
+ $effect(() => {
1212
+ if (!scrollContainer || !horizontalScrollbarEl)
1213
+ return;
1214
+ const el = horizontalScrollbarEl;
1215
+ const onHorizontal = (event) => {
1216
+ const container = scrollContainer;
1217
+ if (!container)
1218
+ return;
1219
+ const customEvent = event;
1220
+ container.scrollLeft = customEvent.detail.value;
1221
+ scheduleScrollSync(container.scrollTop, container.scrollLeft);
1222
+ };
1223
+ el.addEventListener("scroll-change", onHorizontal);
1224
+ return () => el.removeEventListener("scroll-change", onHorizontal);
1225
+ });
1226
+ $effect(() => {
1227
+ // When containerHeight is a string (e.g. "100%") the actual pixel height
1228
+ // depends on the parent layout - read it from the live scroll container.
1229
+ // We track `viewportVersion` (only bumped by the ResizeObserver below)
1230
+ // instead of `scrollVersion` so this effect does NOT re-run on every
1231
+ // scroll event - which would otherwise re-call setOptions hundreds of
1232
+ // times during a drag.
1233
+ viewportVersion;
1234
+ const viewportHeight = typeof props.containerHeight === "string"
1235
+ ? (scrollContainer?.clientHeight ?? 520)
1236
+ : (props.containerHeight ?? 520);
1237
+ const rh = props.rowHeight;
1238
+ virtualizer.setOptions({
1239
+ count: allRows.length,
1240
+ estimateSize: typeof rh === "function" ? rh : (rh ?? 30),
1241
+ overscan: props.overscan ?? 8,
1242
+ viewportHeight,
1243
+ });
1244
+ });
1245
+ // Track size changes of the shell so the virtualizer's viewport, the
1246
+ // fit-columns scale, and anything else that depends on the container
1247
+ // width/height stays in sync. Always attached (window resize / parent
1248
+ // layout shift / sidebar collapse can change the size whether the
1249
+ // consumer passed a numeric or "100%" containerHeight).
1250
+ /** True after the first ResizeObserver tick - i.e. once the grid has
1251
+ * measured its real container size and `fitColumns` has had a chance
1252
+ * to scale the columns to that width. Used to gate the scrollbar
1253
+ * visibility: rendering it before this flips paints a horizontal
1254
+ * scrollbar for ONE frame (based on the base column widths summing
1255
+ * larger than the viewport), then immediately hides it once fit
1256
+ * scaling kicks in - visible as a "flashing horizontal scrollbar"
1257
+ * every time a demo first loads. */
1258
+ let hasMeasured = $state(false);
1259
+ $effect(() => {
1260
+ if (!scrollContainer)
1261
+ return;
1262
+ const observer = new ResizeObserver(() => {
1263
+ viewportVersion += 1;
1264
+ if (!hasMeasured)
1265
+ hasMeasured = true;
1266
+ });
1267
+ observer.observe(scrollContainer);
1268
+ return () => observer.disconnect();
1269
+ });
1270
+ $effect(() => {
1271
+ // Reading columnWidths here registers it as a reactive dependency so
1272
+ // the effect re-runs when the user resizes a column. We pass a fresh
1273
+ // closure each run; the virtualizer sees a new function reference and
1274
+ // re-derives its layout from the current per-column widths.
1275
+ columnWidths;
1276
+ columnVirtualizer.setOptions({
1277
+ count: allColumns.length,
1278
+ estimateSize: (index) => {
1279
+ const column = allColumns[index];
1280
+ return column ? getColumnWidth(column.id) : (props.columnWidth ?? 140);
1281
+ },
1282
+ overscan: props.columnOverscan ?? 3,
1283
+ viewportHeight: viewportWidth,
1284
+ });
1285
+ });
1286
+ $effect(() => {
1287
+ if (!scrollContainer)
1288
+ return;
1289
+ if (rowVirtualizationEnabled)
1290
+ virtualizer.setScrollOffset(domToLogicalRowOffset(scrollContainer.scrollTop));
1291
+ if (columnVirtualizationEnabled)
1292
+ columnVirtualizer.setHorizontalOffset(scrollContainer.scrollLeft);
1293
+ });
1294
+ // Re-arms once the user scrolls away from the bottom, so a long lazy-load
1295
+ // run only fires `onScrollBottomReached` once per arrival at the end.
1296
+ let scrollBottomArmed = true;
1297
+ /** Cached normalized options keyed by columnId - only used when the column
1298
+ * has a static (non-function) `editorOptions`. Dynamic (per-row) options
1299
+ * are resolved on every call because they can change as other cells in
1300
+ * the same row change (the whole point of cascading editors). */
1301
+ const editorOptionsCache = {};
1302
+ const headerSelectionState = $derived.by(() => {
1303
+ gridStateVersion;
1304
+ const selectable = allRows.filter((row) => !isGroupRow(row));
1305
+ if (!selectable.length)
1306
+ return "none";
1307
+ let selected = 0;
1308
+ for (const row of selectable)
1309
+ if (rowSelectionState[row.id])
1310
+ selected += 1;
1311
+ if (selected === 0)
1312
+ return "none";
1313
+ return selected === selectable.length ? "all" : "some";
1314
+ });
1315
+ /** True once a real interaction (click, keyboard nav, or a public-API
1316
+ * call) has activated a cell. Distinct from `activeCell.cellId`, which
1317
+ * the on-mount seed effect populates straight on the grid state without
1318
+ * going through `setActiveCell` - so it can't tell a seeded (0,0) apart
1319
+ * from a user-focused (0,0). The fill handle keys off this flag so it
1320
+ * stays hidden until the user actually selects something. */
1321
+ let userHasActivatedCell = $state(false);
1322
+ /**
1323
+ * Per-column fitted widths when `fitColumns` is on. Computed in one pass
1324
+ * so the LAST auto-sized column can absorb the rounding residue and make
1325
+ * the total match the target viewport width exactly. Without this the
1326
+ * per-column `Math.round` calls leave a 2-6 px residue and the user sees
1327
+ * a small horizontal scrollbar even though every column is "fitted".
1328
+ *
1329
+ * User-resized columns (entries in `columnWidths`) are taken at face
1330
+ * value and only the auto-sized columns share the scale + residue.
1331
+ *
1332
+ * Returns `null` when fit scaling is not in effect (off, no room, total
1333
+ * already >= target). Callers then fall back to the base width.
1334
+ */
1335
+ const fittedColumnWidths = $derived.by(() => {
1336
+ // Track viewport size (not scrollVersion) so we don't recompute on
1337
+ // every scroll - only when the container actually resizes.
1338
+ viewportVersion;
1339
+ if (!props.fitColumns)
1340
+ return null;
1341
+ const cols = grid.getAllColumns().filter((c) => !hiddenColumns[c.id]);
1342
+ if (!cols.length)
1343
+ return null;
1344
+ const rowNumberWidth = showRowNumbersEffective ? rowNumberColumnWidth : 0;
1345
+ const selectionWidth = showRowSelectionEffective ? selectionColumnWidth : 0;
1346
+ // Reserve the custom vertical scrollbar's width when it's visible. It
1347
+ // overlays the right 16px of the viewport (absolute, z-index 40) and
1348
+ // does NOT shrink clientWidth, so without this the last fitted column
1349
+ // slides under it and its right-aligned content (e.g. a number column)
1350
+ // is hidden behind the opaque scrollbar.
1351
+ const scrollbarWidth = hasVerticalOverflow ? 16 : 0;
1352
+ const target = (scrollContainer?.clientWidth ?? 0) -
1353
+ rowNumberWidth -
1354
+ selectionWidth -
1355
+ scrollbarWidth;
1356
+ if (target <= 0)
1357
+ return null;
1358
+ // Split base widths into pinned (user-resized) and scalable.
1359
+ let pinnedTotal = 0;
1360
+ let scalableBase = 0;
1361
+ const scalableIds = [];
1362
+ for (const c of cols) {
1363
+ const w = getColumnBaseWidth(c.id);
1364
+ if (columnWidths[c.id] !== undefined)
1365
+ pinnedTotal += w;
1366
+ else {
1367
+ scalableBase += w;
1368
+ scalableIds.push(c.id);
1369
+ }
1370
+ }
1371
+ const scalableTarget = target - pinnedTotal;
1372
+ if (scalableTarget <= 0 || scalableBase <= 0)
1373
+ return null;
1374
+ // Within 1px of target - no scaling needed.
1375
+ if (Math.abs(scalableBase - scalableTarget) <= 1)
1376
+ return null;
1377
+ // Shrink only by a modest amount (≥85% of natural). Beyond that, leave
1378
+ // natural widths and let the user scroll - squashing every column
1379
+ // tighter would hide content.
1380
+ const scale = scalableTarget / scalableBase;
1381
+ if (scale < 0.85)
1382
+ return null;
1383
+ const widths = {};
1384
+ let runningSum = 0;
1385
+ for (let i = 0; i < scalableIds.length - 1; i += 1) {
1386
+ const id = scalableIds[i];
1387
+ const w = Math.max(MIN_COLUMN_WIDTH, Math.round(getColumnBaseWidth(id) * scale));
1388
+ widths[id] = w;
1389
+ runningSum += w;
1390
+ }
1391
+ // The last scalable column absorbs whatever the previous rounding left
1392
+ // behind, so `sum(widths) === scalableTarget` exactly.
1393
+ const lastId = scalableIds[scalableIds.length - 1];
1394
+ widths[lastId] = Math.max(MIN_COLUMN_WIDTH, scalableTarget - runningSum);
1395
+ return widths;
1396
+ });
1397
+ let resizePendingWidth = 0;
1398
+ let resizeRaf = null;
1399
+ /** Where the fill handle should render: the bottom-right cell of the
1400
+ * selection range (or the active cell if there's no range). Returns
1401
+ * null when cell selection is off or there is no anchored selection. */
1402
+ const fillHandleCell = $derived.by(() => {
1403
+ if (!(props.enableCellSelection ?? false))
1404
+ return null;
1405
+ const anchor = selectionRange.anchor;
1406
+ const focus = selectionRange.focus;
1407
+ if (anchor && focus) {
1408
+ return {
1409
+ rowIndex: Math.max(anchor.rowIndex, focus.rowIndex),
1410
+ colIndex: Math.max(anchor.colIndex, focus.colIndex),
1411
+ };
1412
+ }
1413
+ const a = activeCell;
1414
+ // Only show the handle once the user (or the public API) has actually
1415
+ // activated a cell. The on-mount seed writes activeCell (0,0) directly
1416
+ // to the grid state, so `cellId` alone can't gate this - see
1417
+ // `userHasActivatedCell`.
1418
+ if (!userHasActivatedCell || !a)
1419
+ return null;
1420
+ return { rowIndex: a.rowIndex, colIndex: a.colIndex };
1421
+ });
1422
+ /**
1423
+ * Lazily-created canvas used to measure text width via the 2D context.
1424
+ * Canvas measurement bypasses the cell's `overflow: hidden; white-space:
1425
+ * nowrap` constraint, which makes the body's `scrollWidth` useless here.
1426
+ */
1427
+ let measureCanvas = null;
1428
+ /**
1429
+ * Range buckets for the value-facet list.
1430
+ *
1431
+ * Numeric and date columns with many distinct values would otherwise
1432
+ * paint thousands of single-value checkboxes in the filter menu -
1433
+ * unusable. When a column's `editorType` is `'number' | 'date' |
1434
+ * 'datetime'` AND it has more than BUCKET_THRESHOLD distinct values,
1435
+ * we collapse the facet list into BUCKET_COUNT equal-width ranges
1436
+ * (e.g. "1,000 - 1,500") and let the user check those.
1437
+ *
1438
+ * The bucket structure carries the numeric bounds so the row filter
1439
+ * can re-test each row's value against the selected ranges without
1440
+ * re-doing the bucket math.
1441
+ */
1442
+ /** Buckets for every column that should be bucketed, computed once and
1443
+ * reused by both the facet UI and the row filter. Computing them lazily
1444
+ * in a $derived means columns with no filter menu open and no active
1445
+ * filter never pay the iteration cost. */
1446
+ const facetBucketsByColumn = $derived.by(() => {
1447
+ const map = new Map();
1448
+ for (const column of allColumns) {
1449
+ const meta = isBucketableColumn(column);
1450
+ if (!meta)
1451
+ continue;
1452
+ const buckets = buildBuckets(column, meta.isDate, props.data, getColumnAccessorValue);
1453
+ if (buckets)
1454
+ map.set(column.id, buckets);
1455
+ }
1456
+ return map;
1457
+ });
1458
+ const columnMenuFacetValues = $derived.by(() => {
1459
+ // The funnel popover drives via `filterMenuFor`; the column menu's Filter
1460
+ // tab drives via `columnMenuFor`. Support whichever is open.
1461
+ const columnId = filterMenuFor ?? columnMenuFor;
1462
+ if (!columnId)
1463
+ return [];
1464
+ const column = allColumns.find((entry) => entry.id === columnId);
1465
+ if (!column)
1466
+ return [];
1467
+ // Range-bucketed facets for numeric / date columns with many values.
1468
+ const buckets = facetBucketsByColumn.get(columnId);
1469
+ if (buckets)
1470
+ return buckets.map((b) => b.label);
1471
+ // Default: distinct-value facets.
1472
+ const seen = new Set();
1473
+ for (const rowData of props.data) {
1474
+ seen.add(String(getColumnAccessorValue(rowData, column) ?? ""));
1475
+ }
1476
+ return Array.from(seen).sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
1477
+ });
1478
+ const columnMenuVisibleFacets = $derived.by(() => {
1479
+ const query = columnMenuSearch.trim().toLowerCase();
1480
+ if (!query)
1481
+ return columnMenuFacetValues;
1482
+ return columnMenuFacetValues.filter((value) => value.toLowerCase().includes(query));
1483
+ });
1484
+ // Fire onApiReady exactly once when the grid is first ready. Wrapping in
1485
+ // an effect that tracks `props.onApiReady` was racy - every parent render
1486
+ // creates a new inline arrow, the effect re-fired, and any synchronous
1487
+ // state mutation inside the callback (e.g. `api.setGroupBy(...)`) created
1488
+ // an infinite update loop. Now it's a true mount-once notification.
1489
+ let apiNotified = false;
1490
+ $effect(() => {
1491
+ if (apiNotified)
1492
+ return;
1493
+ const cb = props.onApiReady;
1494
+ if (!cb)
1495
+ return;
1496
+ apiNotified = true;
1497
+ cb(buildApi());
1498
+ });
1499
+ const ctx = {
1500
+ get props() { return props; },
1501
+ get editingEnabled() { return editingEnabled; },
1502
+ get paginationEnabled() { return paginationEnabled; },
1503
+ get groupingControlsEnabled() { return groupingControlsEnabled; },
1504
+ get globalFilter() { return globalFilter; },
1505
+ set globalFilter(v) { globalFilter = v; },
1506
+ get scrollContainer() { return scrollContainer; },
1507
+ set scrollContainer(v) { scrollContainer = v; },
1508
+ get gridRootEl() { return gridRootEl; },
1509
+ set gridRootEl(v) { gridRootEl = v; },
1510
+ get filterRowValues() { return filterRowValues; },
1511
+ set filterRowValues(v) { filterRowValues = v; },
1512
+ get filterMenuValues() { return filterMenuValues; },
1513
+ set filterMenuValues(v) { filterMenuValues = v; },
1514
+ get verticalScrollbarEl() { return verticalScrollbarEl; },
1515
+ set verticalScrollbarEl(v) { verticalScrollbarEl = v; },
1516
+ get horizontalScrollbarEl() { return horizontalScrollbarEl; },
1517
+ set horizontalScrollbarEl(v) { horizontalScrollbarEl = v; },
1518
+ get scrollVersion() { return scrollVersion; },
1519
+ set scrollVersion(v) { scrollVersion = v; },
1520
+ get viewportVersion() { return viewportVersion; },
1521
+ set viewportVersion(v) { viewportVersion = v; },
1522
+ get lastResetSignature() { return lastResetSignature; },
1523
+ set lastResetSignature(v) { lastResetSignature = v; },
1524
+ get pendingScrollTop() { return pendingScrollTop; },
1525
+ set pendingScrollTop(v) { pendingScrollTop = v; },
1526
+ get pendingScrollLeft() { return pendingScrollLeft; },
1527
+ set pendingScrollLeft(v) { pendingScrollLeft = v; },
1528
+ get scrollSyncRaf() { return scrollSyncRaf; },
1529
+ set scrollSyncRaf(v) { scrollSyncRaf = v; },
1530
+ get selectionRange() { return selectionRange; },
1531
+ set selectionRange(v) { selectionRange = v; },
1532
+ get selectionRanges() { return selectionRanges; },
1533
+ set selectionRanges(v) { selectionRanges = v; },
1534
+ get isDraggingSelection() { return isDraggingSelection; },
1535
+ set isDraggingSelection(v) { isDraggingSelection = v; },
1536
+ get fillDrag() { return fillDrag; },
1537
+ set fillDrag(v) { fillDrag = v; },
1538
+ get activeAtPointerDown() { return activeAtPointerDown; },
1539
+ set activeAtPointerDown(v) { activeAtPointerDown = v; },
1540
+ get editingCell() { return editingCell; },
1541
+ set editingCell(v) { editingCell = v; },
1542
+ get fullRowEdit() { return fullRowEdit; },
1543
+ set fullRowEdit(v) { fullRowEdit = v; },
1544
+ get editedCellValues() { return editedCellValues; },
1545
+ set editedCellValues(v) { editedCellValues = v; },
1546
+ get UNDO_LIMIT() { return UNDO_LIMIT; },
1547
+ get history() { return history; },
1548
+ set history(v) { history = v; },
1549
+ get historyPtr() { return historyPtr; },
1550
+ set historyPtr(v) { historyPtr = v; },
1551
+ get historyVersion() { return historyVersion; },
1552
+ set historyVersion(v) { historyVersion = v; },
1553
+ get tooltip() { return tooltip; },
1554
+ set tooltip(v) { tooltip = v; },
1555
+ get tooltipTimer() { return tooltipTimer; },
1556
+ set tooltipTimer(v) { tooltipTimer = v; },
1557
+ get showTooltipFor() { return showTooltipFor; },
1558
+ get hideTooltip() { return hideTooltip; },
1559
+ get findOpen() { return findOpen; },
1560
+ set findOpen(v) { findOpen = v; },
1561
+ get findQuery() { return findQuery; },
1562
+ set findQuery(v) { findQuery = v; },
1563
+ get findHitIndex() { return findHitIndex; },
1564
+ set findHitIndex(v) { findHitIndex = v; },
1565
+ get findHits() { return findHits; },
1566
+ get theadEl() { return theadEl; },
1567
+ set theadEl(v) { theadEl = v; },
1568
+ get headerHeight() { return headerHeight; },
1569
+ set headerHeight(v) { headerHeight = v; },
1570
+ get editorSelectAll() { return editorSelectAll; },
1571
+ set editorSelectAll(v) { editorSelectAll = v; },
1572
+ get columnWidths() { return columnWidths; },
1573
+ set columnWidths(v) { columnWidths = v; },
1574
+ get resizingColumnId() { return resizingColumnId; },
1575
+ set resizingColumnId(v) { resizingColumnId = v; },
1576
+ get resizeStartX() { return resizeStartX; },
1577
+ set resizeStartX(v) { resizeStartX = v; },
1578
+ get resizeStartWidth() { return resizeStartWidth; },
1579
+ set resizeStartWidth(v) { resizeStartWidth = v; },
1580
+ get MIN_COLUMN_WIDTH() { return MIN_COLUMN_WIDTH; },
1581
+ get columnPinning() { return columnPinning; },
1582
+ set columnPinning(v) { columnPinning = v; },
1583
+ get columnVirtualizerVersion() { return columnVirtualizerVersion; },
1584
+ set columnVirtualizerVersion(v) { columnVirtualizerVersion = v; },
1585
+ get gridStateVersion() { return gridStateVersion; },
1586
+ set gridStateVersion(v) { gridStateVersion = v; },
1587
+ get selectionColumnWidth() { return selectionColumnWidth; },
1588
+ get rowNumberColumnWidth() { return rowNumberColumnWidth; },
1589
+ get showRowNumbersEffective() { return showRowNumbersEffective; },
1590
+ get filterOperatorOptions() { return filterOperatorOptions; },
1591
+ get TEXT_OPERATORS() { return TEXT_OPERATORS; },
1592
+ get NUMBER_OPERATORS() { return NUMBER_OPERATORS; },
1593
+ get DATE_OPERATORS() { return DATE_OPERATORS; },
1594
+ get CHECKBOX_OPERATORS() { return CHECKBOX_OPERATORS; },
1595
+ get columnMenuFor() { return columnMenuFor; },
1596
+ get columnMenuTab() { return columnMenuTab; },
1597
+ set columnMenuTab(v) { columnMenuTab = v; },
1598
+ set columnMenuFor(v) { columnMenuFor = v; },
1599
+ get columnMenuPos() { return columnMenuPos; },
1600
+ set columnMenuPos(v) { columnMenuPos = v; },
1601
+ get columnMenuSearch() { return columnMenuSearch; },
1602
+ set columnMenuSearch(v) { columnMenuSearch = v; },
1603
+ get filterMenuFor() { return filterMenuFor; },
1604
+ set filterMenuFor(v) { filterMenuFor = v; },
1605
+ get filterMenuPos() { return filterMenuPos; },
1606
+ set filterMenuPos(v) { filterMenuPos = v; },
1607
+ get operatorMenuFor() { return operatorMenuFor; },
1608
+ set operatorMenuFor(v) { operatorMenuFor = v; },
1609
+ get operatorMenuPos() { return operatorMenuPos; },
1610
+ set operatorMenuPos(v) { operatorMenuPos = v; },
1611
+ get chooseColumnsPos() { return chooseColumnsPos; },
1612
+ set chooseColumnsPos(v) { chooseColumnsPos = v; },
1613
+ get contextMenuFor() { return contextMenuFor; },
1614
+ set contextMenuFor(v) { contextMenuFor = v; },
1615
+ get contextMenuPos() { return contextMenuPos; },
1616
+ set contextMenuPos(v) { contextMenuPos = v; },
1617
+ get noteOverrides() { return noteOverrides; },
1618
+ set noteOverrides(v) { noteOverrides = v; },
1619
+ get commentEditFor() { return commentEditFor; },
1620
+ set commentEditFor(v) { commentEditFor = v; },
1621
+ get commentDraft() { return commentDraft; },
1622
+ set commentDraft(v) { commentDraft = v; },
1623
+ get valueFilters() { return valueFilters; },
1624
+ set valueFilters(v) { valueFilters = v; },
1625
+ get viewportWidth() { return viewportWidth; },
1626
+ get viewportHeight() { return viewportHeight; },
1627
+ get scrollMetrics() { return scrollMetrics; },
1628
+ get hasVerticalOverflow() { return hasVerticalOverflow; },
1629
+ get showGlobalFilterEffective() { return showGlobalFilterEffective; },
1630
+ get showFilterRowEffective() { return showFilterRowEffective; },
1631
+ get showColumnFiltersEffective() { return showColumnFiltersEffective; },
1632
+ get showInlineColumnFilterEffective() { return showInlineColumnFilterEffective; },
1633
+ get showRowSelectionEffective() { return showRowSelectionEffective; },
1634
+ get enableCellSelectionEffective() { return enableCellSelectionEffective; },
1635
+ get flushScheduledScrollSync() { return flushScheduledScrollSync; },
1636
+ get scheduleScrollSync() { return scheduleScrollSync; },
1637
+ get internalData() { return internalData; },
1638
+ set internalData(v) { internalData = v; },
1639
+ get internalColumns() { return internalColumns; },
1640
+ set internalColumns(v) { internalColumns = v; },
1641
+ get hiddenColumns() { return hiddenColumns; },
1642
+ set hiddenColumns(v) { hiddenColumns = v; },
1643
+ get toggleColumnGroup() { return toggleColumnGroup; },
1644
+ get isColumnGroupCollapsed() { return isColumnGroupCollapsed; },
1645
+ get externalSortEnabled() { return externalSortEnabled; },
1646
+ get externalFilterEnabled() { return externalFilterEnabled; },
1647
+ get passthroughSortedRowModel() { return passthroughSortedRowModel; },
1648
+ get resolveEffectiveFeatures() { return resolveEffectiveFeatures; },
1649
+ get grid() { return grid; },
1650
+ get userColumnOrder() { return userColumnOrder; },
1651
+ set userColumnOrder(v) { userColumnOrder = v; },
1652
+ get lastSeededOrder() { return lastSeededOrder; },
1653
+ set lastSeededOrder(v) { lastSeededOrder = v; },
1654
+ get allColumns() { return allColumns; },
1655
+ get headerGroups() { return headerGroups; },
1656
+ get groupHeaderRows() { return groupHeaderRows; },
1657
+ get pinnedOffsets() { return pinnedOffsets; },
1658
+ get cellPinStyle() { return cellPinStyle; },
1659
+ get isColumnPinned() { return isColumnPinned; },
1660
+ get colDragId() { return colDragId; },
1661
+ set colDragId(v) { colDragId = v; },
1662
+ get colDropOnId() { return colDropOnId; },
1663
+ set colDropOnId(v) { colDropOnId = v; },
1664
+ get colDropSide() { return colDropSide; },
1665
+ set colDropSide(v) { colDropSide = v; },
1666
+ get rowDragActive() { return rowDragActive; },
1667
+ set rowDragActive(v) { rowDragActive = v; },
1668
+ get rowDropIndex() { return rowDropIndex; },
1669
+ set rowDropIndex(v) { rowDropIndex = v; },
1670
+ get rowDropSide() { return rowDropSide; },
1671
+ set rowDropSide(v) { rowDropSide = v; },
1672
+ get onRowDragStart() { return onRowDragStart; },
1673
+ get onRowDragOver() { return onRowDragOver; },
1674
+ get onRowDragLeave() { return onRowDragLeave; },
1675
+ get onRowDrop() { return onRowDrop; },
1676
+ get onRowsContainerDragOver() { return onRowsContainerDragOver; },
1677
+ get onRowsContainerDrop() { return onRowsContainerDrop; },
1678
+ get onRowDragEnd() { return onRowDragEnd; },
1679
+ get broadcastAlignedScroll() { return broadcastAlignedScroll; },
1680
+ get getCurrentColumnOrder() { return getCurrentColumnOrder; },
1681
+ get emitColumnOrder() { return emitColumnOrder; },
1682
+ get setColumnOrderInternal() { return setColumnOrderInternal; },
1683
+ get applyColumnDrop() { return applyColumnDrop; },
1684
+ get onColumnHeaderDragStart() { return onColumnHeaderDragStart; },
1685
+ get onColumnHeaderDragOver() { return onColumnHeaderDragOver; },
1686
+ get onColumnHeaderDragLeave() { return onColumnHeaderDragLeave; },
1687
+ get onColumnHeaderDrop() { return onColumnHeaderDrop; },
1688
+ get onColumnHeaderDragEnd() { return onColumnHeaderDragEnd; },
1689
+ get pinColumnLeft() { return pinColumnLeft; },
1690
+ get pinColumnRight() { return pinColumnRight; },
1691
+ get unpinColumn() { return unpinColumn; },
1692
+ get getColumnBaseValue() { return getColumnBaseValue; },
1693
+ get hasConditionalFormats() { return hasConditionalFormats; },
1694
+ get conditionalColumnStats() { return conditionalColumnStats; },
1695
+ get cellConditionalFormat() { return cellConditionalFormat; },
1696
+ get isGroupRow() { return isGroupRow; },
1697
+ get isCellEditable() { return isCellEditable; },
1698
+ get isCellEditableAt() { return isCellEditableAt; },
1699
+ get sortDirectionByColumn() { return sortDirectionByColumn; },
1700
+ get groupingColumns() { return groupingColumns; },
1701
+ get paginationState() { return paginationState; },
1702
+ get getRowColumnValue() { return getRowColumnValue; },
1703
+ get allRowsBeforePagination() { return allRowsBeforePagination; },
1704
+ get allRows() { return allRows; },
1705
+ get rowSelectionState() { return rowSelectionState; },
1706
+ get lastSelectionSerialized() { return lastSelectionSerialized; },
1707
+ set lastSelectionSerialized(v) { lastSelectionSerialized = v; },
1708
+ get lastCellRangeSerialized() { return lastCellRangeSerialized; },
1709
+ set lastCellRangeSerialized(v) { lastCellRangeSerialized = v; },
1710
+ get statusBarEnabled() { return statusBarEnabled; },
1711
+ get statusBarAggregates() { return statusBarAggregates; },
1712
+ get statusBarStats() { return statusBarStats; },
1713
+ get toolPanelOpen() { return toolPanelOpen; },
1714
+ set toolPanelOpen(v) { toolPanelOpen = v; },
1715
+ get toolPanelTab() { return toolPanelTab; },
1716
+ set toolPanelTab(v) { toolPanelTab = v; },
1717
+ get toolPanelEnabled() { return toolPanelEnabled; },
1718
+ get toolPanelColumns() { return toolPanelColumns; },
1719
+ get toolPanelHeaderLabel() { return toolPanelHeaderLabel; },
1720
+ get toggleColumnVisibleInPanel() { return toggleColumnVisibleInPanel; },
1721
+ get moveColumnInPanel() { return moveColumnInPanel; },
1722
+ get toggleGroupInPanel() { return toggleGroupInPanel; },
1723
+ get lastSortingSerialized() { return lastSortingSerialized; },
1724
+ set lastSortingSerialized(v) { lastSortingSerialized = v; },
1725
+ get lastFiltersSerialized() { return lastFiltersSerialized; },
1726
+ set lastFiltersSerialized(v) { lastFiltersSerialized = v; },
1727
+ get virtualizer() { return virtualizer; },
1728
+ get columnVirtualizer() { return columnVirtualizer; },
1729
+ get rowVirtualizationEnabled() { return rowVirtualizationEnabled; },
1730
+ get columnVirtualizationEnabled() { return columnVirtualizationEnabled; },
1731
+ get virtualRows() { return virtualRows; },
1732
+ get virtualRowTotalSize() { return virtualRowTotalSize; },
1733
+ get virtualRowStart() { return virtualRowStart; },
1734
+ get virtualRowEnd() { return virtualRowEnd; },
1735
+ get virtualRowBottomSpacer() { return virtualRowBottomSpacer; },
1736
+ get rowDomTotalSize() { return rowDomTotalSize; },
1737
+ get rowScrollScalingActive() { return rowScrollScalingActive; },
1738
+ get rowTopSpacer() { return rowTopSpacer; },
1739
+ get rowBottomSpacer() { return rowBottomSpacer; },
1740
+ get domToLogicalRowOffset() { return domToLogicalRowOffset; },
1741
+ get logicalToDomRowOffset() { return logicalToDomRowOffset; },
1742
+ get virtualColumns() { return virtualColumns; },
1743
+ get virtualColumnTotalSize() { return virtualColumnTotalSize; },
1744
+ get renderedColumnItems() { return renderedColumnItems; },
1745
+ get hasRenderedColumn() { return hasRenderedColumn; },
1746
+ get renderedColumns() { return renderedColumns; },
1747
+ get totalColumnWidth() { return totalColumnWidth; },
1748
+ get hasHorizontalOverflow() { return hasHorizontalOverflow; },
1749
+ get columnWindowStart() { return columnWindowStart; },
1750
+ get columnWindowEnd() { return columnWindowEnd; },
1751
+ get columnWindowRightSpacer() { return columnWindowRightSpacer; },
1752
+ get activeCell() { return activeCell; },
1753
+ get activeDescendantId() { return activeDescendantId; },
1754
+ get formatSummaryNumeric() { return formatSummaryNumeric; },
1755
+ get computeSummaries() { return computeSummaries; },
1756
+ get SUMMARY_DEFER_CELL_LIMIT() { return SUMMARY_DEFER_CELL_LIMIT; },
1757
+ get summaryByColumn() { return summaryByColumn; },
1758
+ set summaryByColumn(v) { summaryByColumn = v; },
1759
+ get hasMeasured() { return hasMeasured; },
1760
+ set hasMeasured(v) { hasMeasured = v; },
1761
+ get scrollBottomArmed() { return scrollBottomArmed; },
1762
+ set scrollBottomArmed(v) { scrollBottomArmed = v; },
1763
+ get onBodyScroll() { return onBodyScroll; },
1764
+ get computeRowClass() { return computeRowClass; },
1765
+ get computeCellClass() { return computeCellClass; },
1766
+ get computeCellTooltip() { return computeCellTooltip; },
1767
+ get computeCellNote() { return computeCellNote; },
1768
+ get getCellDisplayValue() { return getCellDisplayValue; },
1769
+ get getColumnAlign() { return getColumnAlign; },
1770
+ get editorOptionsCache() { return editorOptionsCache; },
1771
+ get getColumnEditorOptions() { return getColumnEditorOptions; },
1772
+ get formatListCellValue() { return formatListCellValue; },
1773
+ get formatCellValue() { return formatCellValue; },
1774
+ get getPinnedCellValue() { return getPinnedCellValue; },
1775
+ get formatPinnedValue() { return formatPinnedValue; },
1776
+ get computePinnedCellClass() { return computePinnedCellClass; },
1777
+ get isRowSelected() { return isRowSelected; },
1778
+ get toggleRowSelectionById() { return toggleRowSelectionById; },
1779
+ get headerSelectionState() { return headerSelectionState; },
1780
+ get toggleSelectAllRows() { return toggleSelectAllRows; },
1781
+ get userHasActivatedCell() { return userHasActivatedCell; },
1782
+ set userHasActivatedCell(v) { userHasActivatedCell = v; },
1783
+ get setActiveCell() { return setActiveCell; },
1784
+ get scrollActiveCellIntoView() { return scrollActiveCellIntoView; },
1785
+ get getColumnBaseWidth() { return getColumnBaseWidth; },
1786
+ get fittedColumnWidths() { return fittedColumnWidths; },
1787
+ get getColumnWidth() { return getColumnWidth; },
1788
+ get resizePendingWidth() { return resizePendingWidth; },
1789
+ set resizePendingWidth(v) { resizePendingWidth = v; },
1790
+ get resizeRaf() { return resizeRaf; },
1791
+ set resizeRaf(v) { resizeRaf = v; },
1792
+ get startColumnResize() { return startColumnResize; },
1793
+ get onColumnResizeMove() { return onColumnResizeMove; },
1794
+ get endColumnResize() { return endColumnResize; },
1795
+ get setSelection() { return setSelection; },
1796
+ get extendSelection() { return extendSelection; },
1797
+ get isCellInSelectedRange() { return isCellInSelectedRange; },
1798
+ get getCellRangeEdges() { return getCellRangeEdges; },
1799
+ get getSelectionRects() { return getSelectionRects; },
1800
+ get fillHandleCell() { return fillHandleCell; },
1801
+ get isInFillPreview() { return isInFillPreview; },
1802
+ get findColumnById() { return findColumnById; },
1803
+ get readCellRaw() { return readCellRaw; },
1804
+ get writeCellRaw() { return writeCellRaw; },
1805
+ get applyFillPattern() { return applyFillPattern; },
1806
+ get clearSelectedCellValues() { return clearSelectedCellValues; },
1807
+ get startFillDrag() { return startFillDrag; },
1808
+ get onFillPointerMove() { return onFillPointerMove; },
1809
+ get onFillPointerUp() { return onFillPointerUp; },
1810
+ get toggleBooleanCell() { return toggleBooleanCell; },
1811
+ get onCellPointerDown() { return onCellPointerDown; },
1812
+ get onCellPointerEnter() { return onCellPointerEnter; },
1813
+ get endDragSelection() { return endDragSelection; },
1814
+ get onWindowPointerMove() { return onWindowPointerMove; },
1815
+ get onCellClick() { return onCellClick; },
1816
+ get emitCellDoubleClick() { return emitCellDoubleClick; },
1817
+ get copySelectionToClipboard() { return copySelectionToClipboard; },
1818
+ get cutSelectionToClipboard() { return cutSelectionToClipboard; },
1819
+ get pasteFromClipboard() { return pasteFromClipboard; },
1820
+ get onGridPaste() { return onGridPaste; },
1821
+ get clearSelectedCells() { return clearSelectedCells; },
1822
+ get onCellDoubleClick() { return onCellDoubleClick; },
1823
+ get startEditingWithChar() { return startEditingWithChar; },
1824
+ get startEditing() { return startEditing; },
1825
+ get stopEditing() { return stopEditing; },
1826
+ get startFullRowEdit() { return startFullRowEdit; },
1827
+ get setFullRowDraft() { return setFullRowDraft; },
1828
+ get commitFullRowEdit() { return commitFullRowEdit; },
1829
+ get cancelFullRowEdit() { return cancelFullRowEdit; },
1830
+ get saveEditingCell() { return saveEditingCell; },
1831
+ get applyHistoryStep() { return applyHistoryStep; },
1832
+ get updateEditingCellValue() { return updateEditingCellValue; },
1833
+ get onEditorKeyDown() { return onEditorKeyDown; },
1834
+ get focusOnMount() { return focusOnMount; },
1835
+ get onHeaderSortClick() { return onHeaderSortClick; },
1836
+ get onGridKeyDown() { return onGridKeyDown; },
1837
+ get changePage() { return changePage; },
1838
+ get goToPage() { return goToPage; },
1839
+ get setPageSize() { return setPageSize; },
1840
+ get openContextMenu() { return openContextMenu; },
1841
+ get closeContextMenu() { return closeContextMenu; },
1842
+ get contextMenuItems() { return contextMenuItems; },
1843
+ get saveComment() { return saveComment; },
1844
+ get removeComment() { return removeComment; },
1845
+ get closeCommentEditor() { return closeCommentEditor; },
1846
+ get updateFilterRow() { return updateFilterRow; },
1847
+ get updateFilterOperator() { return updateFilterOperator; },
1848
+ get updateFilterMenuValue() { return updateFilterMenuValue; },
1849
+ get updateFilterMenuValueTo() { return updateFilterMenuValueTo; },
1850
+ get toggleCheckboxWithKeyboard() { return toggleCheckboxWithKeyboard; },
1851
+ get getColumnAccessorValue() { return getColumnAccessorValue; },
1852
+ get fallbackOperatorOption() { return fallbackOperatorOption; },
1853
+ get operatorOption() { return operatorOption; },
1854
+ get operatorsForColumn() { return operatorsForColumn; },
1855
+ get defaultOperatorFor() { return defaultOperatorFor; },
1856
+ get operatorLabelFor() { return operatorLabelFor; },
1857
+ get isColumnFiltered() { return isColumnFiltered; },
1858
+ get closeMenus() { return closeMenus; },
1859
+ get measureCanvas() { return measureCanvas; },
1860
+ set measureCanvas(v) { measureCanvas = v; },
1861
+ get measureText() { return measureText; },
1862
+ get autosizeColumn() { return autosizeColumn; },
1863
+ get autosizeAllColumns() { return autosizeAllColumns; },
1864
+ get resetColumns() { return resetColumns; },
1865
+ get openChooseColumns() { return openChooseColumns; },
1866
+ get openColumnMenu() { return openColumnMenu; },
1867
+ get openFilterMenu() { return openFilterMenu; },
1868
+ get openOperatorMenu() { return openOperatorMenu; },
1869
+ get sortColumnFromMenu() { return sortColumnFromMenu; },
1870
+ get clearColumnSort() { return clearColumnSort; },
1871
+ get groupByColumnFromMenu() { return groupByColumnFromMenu; },
1872
+ get clearGroupingFromMenu() { return clearGroupingFromMenu; },
1873
+ get isBucketableColumn() { return isBucketableColumn; },
1874
+ get buildBuckets() { return buildBuckets; },
1875
+ get isInBucket() { return isInBucket; },
1876
+ get facetBucketsByColumn() { return facetBucketsByColumn; },
1877
+ get columnMenuFacetValues() { return columnMenuFacetValues; },
1878
+ get columnMenuVisibleFacets() { return columnMenuVisibleFacets; },
1879
+ get isFacetChecked() { return isFacetChecked; },
1880
+ get toggleFacetValue() { return toggleFacetValue; },
1881
+ get isAllFacetsChecked() { return isAllFacetsChecked; },
1882
+ get toggleAllFacets() { return toggleAllFacets; },
1883
+ get clearColumnFilter() { return clearColumnFilter; },
1884
+ get onWindowKeydown() { return onWindowKeydown; },
1885
+ get columnDefMatchesId() { return columnDefMatchesId; },
1886
+ get buildApi() { return buildApi; },
1887
+ get apiNotified() { return apiNotified; },
1888
+ set apiNotified(v) { apiNotified = v; },
1889
+ };
1890
+ const { resolveEffectiveFeatures } = createFeatures(ctx);
1891
+ const { showTooltipFor, hideTooltip, flushScheduledScrollSync, scheduleScrollSync, onBodyScroll } = createScrollSync(ctx);
1892
+ const { onGridKeyDown, onWindowKeydown, onHeaderSortClick } = createKeyboard(ctx);
1893
+ const { computeSummaries, hasRenderedColumn } = createSummaries(ctx);
1894
+ const { updateFilterRow, updateFilterOperator, updateFilterMenuValue, updateFilterMenuValueTo, toggleCheckboxWithKeyboard, isColumnFiltered, closeMenus, openChooseColumns, openColumnMenu, openFilterMenu, openOperatorMenu, sortColumnFromMenu, clearColumnSort, groupByColumnFromMenu, clearGroupingFromMenu, isFacetChecked, toggleFacetValue, isAllFacetsChecked, toggleAllFacets, clearColumnFilter, changePage, goToPage, setPageSize, openContextMenu, closeContextMenu, contextMenuItems, saveComment, removeComment, closeCommentEditor } = createMenus(ctx);
1895
+ const { cellConditionalFormat, computeRowClass, computeCellClass, computeCellTooltip, computeCellNote, getColumnEditorOptions, formatListCellValue, formatCellValue, formatPinnedValue, computePinnedCellClass } = createCellRender(ctx);
1896
+ const { isCellEditable, isCellEditableAt, getRowColumnValue, getCellDisplayValue, startEditingWithChar, startEditing, stopEditing, startFullRowEdit, setFullRowDraft, commitFullRowEdit, cancelFullRowEdit, saveEditingCell, applyHistoryStep, updateEditingCellValue, onEditorKeyDown, focusOnMount, onCellDoubleClick, pasteFromClipboard, onGridPaste } = createEditing(ctx);
1897
+ const { isRowSelected, toggleRowSelectionById, toggleSelectAllRows, setActiveCell, scrollActiveCellIntoView, setSelection, extendSelection, isCellInSelectedRange, getCellRangeEdges, getSelectionRects, isInFillPreview, findColumnById, onCellPointerDown, onCellPointerEnter, endDragSelection, onWindowPointerMove, onCellClick, emitCellDoubleClick } = createSelection(ctx);
1898
+ const { cellPinStyle, isColumnPinned, getCurrentColumnOrder, emitColumnOrder, setColumnOrderInternal, applyColumnDrop, onColumnHeaderDragStart, onColumnHeaderDragOver, onColumnHeaderDragLeave, onColumnHeaderDrop, onColumnHeaderDragEnd, pinColumnLeft, pinColumnRight, unpinColumn, toggleColumnVisibleInPanel, moveColumnInPanel, toggleGroupInPanel, getColumnBaseWidth, getColumnWidth, startColumnResize, onColumnResizeMove, endColumnResize, measureText, autosizeColumn, autosizeAllColumns, resetColumns } = createColumns(ctx);
1899
+ const { onRowDragStart, onRowDragOver, onRowDragLeave, onRowDrop, onRowsContainerDragOver, onRowsContainerDrop, onRowDragEnd } = createRowDrag(ctx);
1900
+ const { register: registerAlignedGrid, broadcastScroll: broadcastAlignedScroll, broadcastWidths: broadcastAlignedWidths } = createAlignedGrids(ctx);
1901
+ const { buildApi } = createGridApi(ctx);
1902
+ const { readCellRaw, writeCellRaw, applyFillPattern, clearSelectedCellValues, startFillDrag, onFillPointerMove, onFillPointerUp, toggleBooleanCell, copySelectionToClipboard, clearSelectedCells, cutSelectionToClipboard } = createClipboard(ctx);
1903
+ // Aligned grids: register in the shared group on mount, and mirror column
1904
+ // resizes to peers whenever columnWidths changes. Horizontal-scroll mirroring
1905
+ // is driven from onBodyScroll (via ctx.broadcastAlignedScroll).
1906
+ $effect(() => {
1907
+ if (props.alignedGridGroup == null)
1908
+ return;
1909
+ return registerAlignedGrid();
1910
+ });
1911
+ $effect(() => {
1912
+ // Track columnWidths reactively, then broadcast to aligned peers.
1913
+ void columnWidths;
1914
+ broadcastAlignedWidths();
1915
+ });
1916
+ return ctx;
1917
+ }