@svgrid/grid 2.6.17 → 2.6.18

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 (253) hide show
  1. package/CHANGELOG.md +346 -346
  2. package/README.md +199 -199
  3. package/dist/FlexRender.svelte +96 -96
  4. package/dist/GridFooter.svelte +181 -181
  5. package/dist/GridMenus.svelte +705 -705
  6. package/dist/SvAutoComplete.svelte +165 -165
  7. package/dist/SvAvatar.svelte +75 -75
  8. package/dist/SvCalendar.svelte +503 -503
  9. package/dist/SvCarousel.svelte +141 -141
  10. package/dist/SvCheckBox.svelte +102 -102
  11. package/dist/SvCircularProgress.svelte +109 -109
  12. package/dist/SvColorInput.svelte +181 -181
  13. package/dist/SvComboBox.svelte +275 -275
  14. package/dist/SvContextMenu.svelte +116 -116
  15. package/dist/SvCountryInput.svelte +163 -163
  16. package/dist/SvDrawer.svelte +254 -254
  17. package/dist/SvDropDownList.svelte +374 -374
  18. package/dist/SvDurationInput.svelte +126 -126
  19. package/dist/SvField.svelte +293 -293
  20. package/dist/SvForm.svelte +437 -437
  21. package/dist/SvGrid.css +2896 -2896
  22. package/dist/SvGrid.svelte +2956 -2956
  23. package/dist/SvGridCellEditor.svelte +662 -662
  24. package/dist/SvGridChart.svelte +1716 -1716
  25. package/dist/SvGridChartPanel.svelte +485 -485
  26. package/dist/SvGridChartView.svelte +70 -70
  27. package/dist/SvGridDropdown.svelte +728 -728
  28. package/dist/SvGridSelect.svelte +266 -266
  29. package/dist/SvGroupCell.svelte +116 -116
  30. package/dist/SvListBox.svelte +326 -326
  31. package/dist/SvMaskedInput.svelte +122 -122
  32. package/dist/SvMenu.svelte +124 -124
  33. package/dist/SvMenuList.svelte +146 -146
  34. package/dist/SvMultiSelect.svelte +289 -289
  35. package/dist/SvNumberInput.svelte +168 -168
  36. package/dist/SvOtpInput.svelte +158 -158
  37. package/dist/SvPasswordInput.svelte +151 -151
  38. package/dist/SvPhoneInput.svelte +133 -133
  39. package/dist/SvPopover.svelte +197 -197
  40. package/dist/SvProgress.svelte +116 -116
  41. package/dist/SvRadioGroup.svelte +107 -107
  42. package/dist/SvRating.svelte +112 -112
  43. package/dist/SvResult.svelte +73 -73
  44. package/dist/SvRichText.svelte +211 -211
  45. package/dist/SvRowGroupPanel.svelte +170 -170
  46. package/dist/SvScrollArea.svelte +61 -61
  47. package/dist/SvSlider.svelte +203 -203
  48. package/dist/SvSwitchButton.svelte +108 -108
  49. package/dist/SvTagsInput.svelte +115 -115
  50. package/dist/SvTextInput.svelte +147 -147
  51. package/dist/SvTimePicker.svelte +245 -245
  52. package/dist/SvToaster.svelte +159 -159
  53. package/dist/SvToggleButton.svelte +85 -85
  54. package/dist/SvTooltip.svelte +161 -161
  55. package/dist/SvTour.svelte +208 -208
  56. package/dist/SvTree.svelte +444 -444
  57. package/dist/SvTreeSelect.svelte +235 -235
  58. package/dist/cdn/{GridMenus-3kKYmYOE.js → GridMenus-B0F9iBrG.js} +2 -2
  59. package/dist/cdn/{GridMenus-BcDiwQ9U.js → GridMenus-IHK_l7m6.js} +2 -2
  60. package/dist/cdn/{SvDateTimePicker-DSUhIta8.js → SvDateTimePicker-CHnUkWcH.js} +2 -2
  61. package/dist/cdn/{SvDateTimePicker-h9kPyszT.js → SvDateTimePicker-CRQH_U7E.js} +2 -2
  62. package/dist/cdn/{SvGridCellEditor-DkyQO6FV.js → SvGridCellEditor-BGUCzuPB.js} +1 -1
  63. package/dist/cdn/{SvGridCellEditor-JpJSRhDx.js → SvGridCellEditor-G8IMWIws.js} +1 -1
  64. package/dist/cdn/{SvGridChart-CwhFz7GV.js → SvGridChart-BEJmNNx9.js} +1 -1
  65. package/dist/cdn/{SvGridChart-Bs2GIR2Q.js → SvGridChart-BwVos976.js} +1 -1
  66. package/dist/cdn/{SvGridChartPanel-1WXuStzM.js → SvGridChartPanel-BOknOkrP.js} +1 -1
  67. package/dist/cdn/{SvGridChartPanel-e5_nqNP9.js → SvGridChartPanel-D2PjII4O.js} +1 -1
  68. package/dist/cdn/{SvGridChartView-SmPW10dI.js → SvGridChartView-00LPUHL1.js} +1 -1
  69. package/dist/cdn/{SvGridChartView-eSPuJE6g.js → SvGridChartView-BhUEJ5ki.js} +1 -1
  70. package/dist/cdn/{SvGridDropdown-B1ZcLpgs.js → SvGridDropdown-D0VdjeR8.js} +1 -1
  71. package/dist/cdn/{SvGridDropdown-CtdbHcIS.js → SvGridDropdown-D13MtJ2j.js} +1 -1
  72. package/dist/cdn/{src-DMZZVVFd.js → src-B1TdiyS8.js} +26 -26
  73. package/dist/cdn/{src-D79V6bCA.js → src-Cd0tearp.js} +27 -27
  74. package/dist/cdn/svgrid.js +5 -5
  75. package/dist/cdn/svgrid.svelte-external.js +5 -5
  76. package/dist/chart-export.js +8 -8
  77. package/package.json +11 -11
  78. package/src/FlexRender.svelte +96 -96
  79. package/src/GridFooter.svelte +181 -181
  80. package/src/GridMenus.svelte +705 -705
  81. package/src/SvAutoComplete.svelte +165 -165
  82. package/src/SvAvatar.svelte +75 -75
  83. package/src/SvCalendar.svelte +503 -503
  84. package/src/SvCalendar.test.ts +226 -226
  85. package/src/SvCarousel.svelte +141 -141
  86. package/src/SvCheckBox.svelte +102 -102
  87. package/src/SvCircularProgress.svelte +109 -109
  88. package/src/SvColorInput.svelte +181 -181
  89. package/src/SvComboBox.svelte +275 -275
  90. package/src/SvContextMenu.svelte +116 -116
  91. package/src/SvCountryInput.svelte +163 -163
  92. package/src/SvDrawer.svelte +254 -254
  93. package/src/SvDropDownList.svelte +374 -374
  94. package/src/SvDurationInput.svelte +126 -126
  95. package/src/SvField.svelte +293 -293
  96. package/src/SvForm.svelte +437 -437
  97. package/src/SvForm.test.ts +411 -411
  98. package/src/SvGrid.controller.svelte.ts +3974 -3974
  99. package/src/SvGrid.css +2896 -2896
  100. package/src/SvGrid.svelte +2956 -2956
  101. package/src/SvGrid.types.ts +1790 -1790
  102. package/src/SvGridCellEditor.svelte +662 -662
  103. package/src/SvGridChart.svelte +1716 -1716
  104. package/src/SvGridChartPanel.svelte +485 -485
  105. package/src/SvGridChartView.svelte +70 -70
  106. package/src/SvGridDropdown.svelte +728 -728
  107. package/src/SvGridSelect.svelte +266 -266
  108. package/src/SvGroupCell.svelte +116 -116
  109. package/src/SvListBox.svelte +326 -326
  110. package/src/SvMaskedInput.svelte +122 -122
  111. package/src/SvMenu.svelte +124 -124
  112. package/src/SvMenu.test.ts +97 -97
  113. package/src/SvMenuList.svelte +146 -146
  114. package/src/SvMultiSelect.svelte +289 -289
  115. package/src/SvNumberInput.svelte +168 -168
  116. package/src/SvOtpInput.svelte +158 -158
  117. package/src/SvPasswordInput.svelte +151 -151
  118. package/src/SvPhoneInput.svelte +133 -133
  119. package/src/SvPopover.svelte +197 -197
  120. package/src/SvProgress.svelte +116 -116
  121. package/src/SvRadioGroup.svelte +107 -107
  122. package/src/SvRating.svelte +112 -112
  123. package/src/SvResult.svelte +73 -73
  124. package/src/SvRichText.svelte +211 -211
  125. package/src/SvRowGroupPanel.svelte +170 -170
  126. package/src/SvScrollArea.svelte +61 -61
  127. package/src/SvSlider.svelte +203 -203
  128. package/src/SvSwitchButton.svelte +108 -108
  129. package/src/SvTagsInput.svelte +115 -115
  130. package/src/SvTextInput.svelte +147 -147
  131. package/src/SvTimePicker.svelte +245 -245
  132. package/src/SvToaster.svelte +159 -159
  133. package/src/SvToaster.test.ts +95 -95
  134. package/src/SvToggleButton.svelte +85 -85
  135. package/src/SvTooltip.svelte +161 -161
  136. package/src/SvTour.svelte +208 -208
  137. package/src/SvTree.svelte +444 -444
  138. package/src/SvTreeSelect.svelte +235 -235
  139. package/src/a11y/dismissable.test.ts +119 -119
  140. package/src/a11y/dismissable.ts +114 -114
  141. package/src/a11y.contract.test.ts +49 -49
  142. package/src/a11y.test.ts +59 -59
  143. package/src/a11y.ts +61 -61
  144. package/src/ai.test.ts +502 -502
  145. package/src/ai.ts +1391 -1391
  146. package/src/build-api.coverage.test.ts +633 -633
  147. package/src/build-api.ts +846 -846
  148. package/src/builtin-editors.grid.test.ts +83 -83
  149. package/src/cell-formatting.ts +169 -169
  150. package/src/cell-render.test.ts +513 -513
  151. package/src/cell-render.ts +496 -496
  152. package/src/cell-values.ts +118 -118
  153. package/src/chart-export.ts +201 -201
  154. package/src/chart-view.svelte.ts +36 -36
  155. package/src/chart.ts +2295 -2295
  156. package/src/collaboration.test.ts +104 -104
  157. package/src/collaboration.ts +167 -167
  158. package/src/core.performance.test.ts +30 -30
  159. package/src/core.ts +1261 -1261
  160. package/src/createAutocomplete.svelte.ts +132 -132
  161. package/src/createCombobox.svelte.ts +191 -191
  162. package/src/createCountryInput.svelte.ts +157 -157
  163. package/src/createDropdownList.svelte.ts +168 -168
  164. package/src/createForm.svelte.ts +386 -386
  165. package/src/createGrid.svelte.ts +42 -42
  166. package/src/createGrid.test.ts +10 -10
  167. package/src/createGridState.svelte.ts +17 -17
  168. package/src/createListbox.svelte.ts +250 -250
  169. package/src/createMenu.svelte.ts +224 -224
  170. package/src/createPopoverSelect.svelte.ts +213 -213
  171. package/src/createSlider.svelte.ts +191 -191
  172. package/src/createTooltip.svelte.ts +144 -144
  173. package/src/createTree.svelte.ts +319 -319
  174. package/src/editing.test.ts +949 -949
  175. package/src/editing.ts +606 -606
  176. package/src/editor-contract.ts +170 -170
  177. package/src/editor-registry.grid.test.ts +144 -144
  178. package/src/editor-registry.ts +122 -122
  179. package/src/export-data-api.test.ts +126 -126
  180. package/src/export-format.test.ts +107 -107
  181. package/src/export-format.ts +601 -601
  182. package/src/filter-operators.ts +160 -160
  183. package/src/flex-render.ts +3 -3
  184. package/src/form-field.ts +127 -127
  185. package/src/group-display.test.ts +167 -167
  186. package/src/group-display.ts +200 -200
  187. package/src/headless.ts +87 -87
  188. package/src/index.ts +754 -754
  189. package/src/js-scroller.svelte.ts +173 -173
  190. package/src/keyboard-handlers.ts +270 -270
  191. package/src/keyboard.test.ts +59 -59
  192. package/src/keyboard.ts +97 -97
  193. package/src/list-nav.test.ts +49 -49
  194. package/src/list-nav.ts +29 -29
  195. package/src/list-option.test.ts +56 -56
  196. package/src/list-option.ts +172 -172
  197. package/src/menus.ts +567 -567
  198. package/src/merge-objects.ts +48 -48
  199. package/src/overlays.test.ts +90 -90
  200. package/src/render-component.ts +28 -28
  201. package/src/row-drag-touch.ts +211 -211
  202. package/src/row-drag.test.ts +353 -353
  203. package/src/row-drag.ts +415 -415
  204. package/src/row-resize.ts +210 -210
  205. package/src/scheduler-model.test.ts +562 -562
  206. package/src/scheduler-model.ts +872 -872
  207. package/src/selection.test.ts +754 -754
  208. package/src/selection.ts +491 -491
  209. package/src/server-data-source.test.ts +383 -383
  210. package/src/server-data-source.ts +469 -469
  211. package/src/sparkline.test.ts +68 -68
  212. package/src/sparkline.ts +169 -169
  213. package/src/spreadsheet.test.ts +488 -488
  214. package/src/spreadsheet.ts +312 -312
  215. package/src/static-functions.ts +11 -11
  216. package/src/subscribe.ts +38 -38
  217. package/src/svgrid-wrapper.types.ts +558 -558
  218. package/src/svgrid.async-editor-options.test.ts +273 -273
  219. package/src/svgrid.auto-row-height.test.ts +204 -204
  220. package/src/svgrid.behavior.test.ts +910 -910
  221. package/src/svgrid.charting.test.ts +534 -534
  222. package/src/svgrid.comments-autocomplete.test.ts +127 -127
  223. package/src/svgrid.context-menu.test.ts +147 -147
  224. package/src/svgrid.features.test.ts +157 -157
  225. package/src/svgrid.filter-depth.test.ts +163 -163
  226. package/src/svgrid.filter-menu-listbox.svelte.test.ts +331 -331
  227. package/src/svgrid.filter-menu-scroll.test.ts +112 -112
  228. package/src/svgrid.grand-total.test.ts +188 -188
  229. package/src/svgrid.group-display-mode.test.ts +171 -171
  230. package/src/svgrid.group-footers.test.ts +121 -121
  231. package/src/svgrid.group-pagination.test.ts +153 -153
  232. package/src/svgrid.new-features.wrapper.test.ts +251 -251
  233. package/src/svgrid.tree-data.test.ts +186 -186
  234. package/src/svgrid.wrapper.test.ts +63 -63
  235. package/src/svgriddropdown.async-panel.svelte.test.ts +195 -195
  236. package/src/test-setup.ts +62 -62
  237. package/src/themes/index.ts +288 -288
  238. package/src/toast-store.svelte.ts +246 -246
  239. package/src/toast-store.test.ts +147 -147
  240. package/src/tree-row-model.test.ts +168 -168
  241. package/src/ui-buttons.test.ts +144 -144
  242. package/src/ui-inputs.test.ts +118 -118
  243. package/src/ui-localization.test.ts +113 -113
  244. package/src/ui-range.test.ts +70 -70
  245. package/src/ui-selection.test.ts +155 -155
  246. package/src/ui-tier1.test.ts +142 -142
  247. package/src/virtual.test.ts +88 -88
  248. package/src/virtualization/column-virtualizer.test.ts +27 -27
  249. package/src/virtualization/column-virtualizer.ts +30 -30
  250. package/src/virtualization/svelte-virtualizer.svelte.ts +26 -26
  251. package/src/virtualization/types.ts +30 -30
  252. package/src/virtualization/virtualizer.test.ts +47 -47
  253. package/src/virtualization/virtualizer.ts +322 -322
package/src/menus.ts CHANGED
@@ -1,567 +1,567 @@
1
- // menus handlers extracted from the controller. Imperative event handlers
2
- // reading/writing controller state via the `ctx` handle; the reactive core
3
- // ($state/$derived/$effect) stays in the controller.
4
- import {
5
- type RowData,
6
- type TableFeatures,
7
- } from "./index";
8
- import "./sv-grid-scrollbar";
9
- import { untrack } from "svelte";
10
- import type {
11
- FilterOperator,
12
- } from "./SvGrid.types";
13
- import {
14
- clampMenuX,
15
- cssEscape,
16
- } from "./SvGrid.helpers";
17
- import { splitInTokens, joinInTokens } from "./filtering/excel-filters";
18
-
19
- export function createMenus<
20
- TFeatures extends TableFeatures = TableFeatures,
21
- TData extends RowData = RowData,
22
- >(ctx: any) {
23
- function updateFilterRow(columnId: string, value: string) {
24
- ctx.filterRowValues = { ...ctx.filterRowValues, [columnId]: value };
25
- const current = ctx.filterMenuValues[columnId] ?? {
26
- operator: "contains" as const,
27
- value: "",
28
- };
29
- ctx.filterMenuValues = {
30
- ...ctx.filterMenuValues,
31
- [columnId]: { ...current, value },
32
- };
33
- }
34
-
35
- function updateFilterOperator(columnId: string, operator: FilterOperator) {
36
- const current = ctx.filterMenuValues[columnId] ?? {
37
- operator: "contains" as const,
38
- value: "",
39
- };
40
- ctx.filterMenuValues = {
41
- ...ctx.filterMenuValues,
42
- [columnId]: { ...current, operator },
43
- };
44
- }
45
-
46
- function updateFilterMenuValue(columnId: string, value: string) {
47
- const current = ctx.filterMenuValues[columnId] ?? {
48
- operator: "contains" as const,
49
- value: "",
50
- };
51
- ctx.filterMenuValues = {
52
- ...ctx.filterMenuValues,
53
- [columnId]: { ...current, value },
54
- };
55
- ctx.filterRowValues = { ...ctx.filterRowValues, [columnId]: value };
56
- }
57
-
58
- /** Upper-bound input for the `between` operator. Only relevant when
59
- * the column's current operator is `between`; harmless to call
60
- * otherwise. */
61
- function updateFilterMenuValueTo(columnId: string, valueTo: string) {
62
- const current = ctx.filterMenuValues[columnId] ?? {
63
- operator: "between" as const,
64
- value: "",
65
- };
66
- ctx.filterMenuValues = {
67
- ...ctx.filterMenuValues,
68
- [columnId]: { ...current, valueTo },
69
- };
70
- }
71
-
72
- /** Current `in` / `notIn` token list for a column (from the filter-row value). */
73
- function filterTokens(columnId: string): string[] {
74
- return splitInTokens(ctx.filterRowValues[columnId] ?? "");
75
- }
76
-
77
- /** Add a value to a column's `in` / `notIn` list (no-op if already present). */
78
- function addFilterToken(columnId: string, token: string) {
79
- const t = token.trim();
80
- if (!t) return;
81
- const tokens = filterTokens(columnId);
82
- if (!tokens.includes(t)) tokens.push(t);
83
- updateFilterRow(columnId, joinInTokens(tokens));
84
- }
85
-
86
- /** Remove a value from a column's `in` / `notIn` list. */
87
- function removeFilterToken(columnId: string, token: string) {
88
- updateFilterRow(
89
- columnId,
90
- joinInTokens(filterTokens(columnId).filter((t) => t !== token)),
91
- );
92
- }
93
-
94
- /** Toggle a value in a column's `in` / `notIn` list (checklist behaviour). */
95
- function toggleFilterToken(columnId: string, token: string) {
96
- if (filterTokens(columnId).includes(token)) removeFilterToken(columnId, token);
97
- else addFilterToken(columnId, token);
98
- }
99
-
100
- /**
101
- * Replace a column's `in` / `notIn` list wholesale. The suggestions dropdown
102
- * hands back the full token set after a click, which keeps tokens the user
103
- * typed by hand (or that the search box is currently hiding) intact.
104
- */
105
- function setFilterTokens(columnId: string, tokens: Iterable<string>) {
106
- const list = [...tokens].map((t) => t.trim()).filter(Boolean);
107
- updateFilterRow(columnId, joinInTokens(list));
108
- }
109
-
110
- function toggleCheckboxWithKeyboard(
111
- event: KeyboardEvent,
112
- toggle: () => void,
113
- ) {
114
- if (event.key !== "Enter" && event.key !== " ") return;
115
- event.preventDefault();
116
- toggle();
117
- }
118
-
119
- function isColumnFiltered(columnId: string) {
120
- if (ctx.valueFilters[columnId]) return true;
121
- const menuFilter = ctx.filterMenuValues[columnId];
122
- return Boolean(
123
- menuFilter &&
124
- (menuFilter.operator === "isBlank" ||
125
- menuFilter.operator === "isNotBlank" ||
126
- menuFilter.value.trim()),
127
- );
128
- }
129
-
130
- function closeMenus() {
131
- ctx.columnMenuFor = null;
132
- ctx.filterMenuFor = null;
133
- ctx.operatorMenuFor = null;
134
- ctx.inSuggestFor = null;
135
- ctx.chooseColumnsPos = null;
136
- }
137
-
138
- /** Open the `in` / `notIn` value-suggestions dropdown under a chip input. */
139
- function openInSuggest(anchor: HTMLElement, columnId: string) {
140
- const rect = anchor.getBoundingClientRect();
141
- ctx.inSuggestPos = { x: clampMenuX(rect.left, 220), y: rect.bottom + 4 };
142
- ctx.inSuggestQuery = "";
143
- ctx.inSuggestFor = columnId;
144
- }
145
-
146
- function closeInSuggest() {
147
- ctx.inSuggestFor = null;
148
- ctx.inSuggestQuery = "";
149
- }
150
-
151
- function openChooseColumns(event: MouseEvent) {
152
- event.stopPropagation();
153
- // Submenu behavior: keep the parent operations menu open and float the
154
- // Choose Columns panel out to the right of it (AG-Grid style). Falls
155
- // back to below the item if the popover would clip the viewport.
156
- const trigger = event.currentTarget as HTMLElement;
157
- const menuEl = trigger.closest(".sv-grid-menu") as HTMLElement | null;
158
- const anchor = (menuEl ?? trigger).getBoundingClientRect();
159
- const panelWidth = 240;
160
- const wantRight = anchor.right + 4;
161
- const x =
162
- wantRight + panelWidth + 8 > window.innerWidth
163
- ? clampMenuX(anchor.left - panelWidth - 4, panelWidth)
164
- : clampMenuX(wantRight, panelWidth);
165
- ctx.chooseColumnsPos = { x, y: anchor.top };
166
- }
167
-
168
- function openColumnMenu(event: MouseEvent, columnId: string) {
169
- event.stopPropagation();
170
- const wasOpen = ctx.columnMenuFor === columnId;
171
- closeMenus();
172
- if (wasOpen) return;
173
- const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
174
- ctx.columnMenuPos = {
175
- x: clampMenuX(rect.right - 240, 240),
176
- y: rect.bottom + 4,
177
- };
178
- ctx.columnMenuTab = "general";
179
- ctx.columnMenuFor = columnId;
180
- }
181
-
182
- function openFilterMenu(event: MouseEvent, columnId: string) {
183
- event.stopPropagation();
184
- const wasOpen = ctx.filterMenuFor === columnId;
185
- closeMenus();
186
- if (wasOpen) return;
187
-
188
- // If the consumer is running in row-mode (or any mode where the
189
- // funnel popover wouldn't render), redirect the click to the
190
- // inline filter input for this column. Without this the funnel
191
- // would be a dead button - it visibly clicks but nothing happens
192
- // because the menu is gated behind `showColumnFiltersEffective`.
193
- if (!ctx.showColumnFiltersEffective && ctx.showFilterRowEffective) {
194
- // Find the row-mode filter input and focus it. The input is
195
- // tagged with `data-svgrid-filter-col` so we can target by id
196
- // without depending on column position.
197
- const input = (ctx.scrollContainer as HTMLElement | null)?.querySelector<HTMLInputElement>(
198
- `[data-svgrid-filter-col="${cssEscape(columnId)}"]`,
199
- );
200
- if (input) {
201
- input.focus();
202
- input.select();
203
- // Brief pulse so the user sees where focus landed.
204
- input.classList.add("sv-grid-filter-value-pulse");
205
- setTimeout(() => input.classList.remove("sv-grid-filter-value-pulse"), 700);
206
- }
207
- return;
208
- }
209
-
210
- const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
211
- ctx.filterMenuPos = {
212
- x: clampMenuX(rect.right - 260, 260),
213
- y: rect.bottom + 4,
214
- };
215
- ctx.columnMenuSearch = "";
216
- ctx.filterMenuFor = columnId;
217
- }
218
-
219
- function openOperatorMenu(event: MouseEvent, columnId: string) {
220
- event.stopPropagation();
221
- const wasOpen = ctx.operatorMenuFor === columnId;
222
- closeMenus();
223
- if (wasOpen) return;
224
- const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
225
- ctx.operatorMenuPos = { x: clampMenuX(rect.left, 184), y: rect.bottom + 4 };
226
- ctx.operatorMenuFor = columnId;
227
- }
228
-
229
- function sortColumnFromMenu(columnId: string, desc: boolean) {
230
- ctx.grid.store.setState((prev: any) => ({
231
- ...prev,
232
- sorting: [{ id: columnId, desc }],
233
- }));
234
- closeMenus();
235
- }
236
-
237
- function clearColumnSort(columnId: string) {
238
- ctx.grid.store.setState((prev: any) => ({
239
- ...prev,
240
- sorting: (prev.sorting ?? []).filter(
241
- (entry: { id: string }) => entry.id !== columnId,
242
- ),
243
- }));
244
- closeMenus();
245
- }
246
-
247
- function groupByColumnFromMenu(columnId: string) {
248
- const current = ctx.grid.getState().grouping ?? [];
249
- if (current.includes(columnId)) {
250
- closeMenus();
251
- return;
252
- }
253
- ctx.grid.setGrouping([...current, columnId]);
254
- closeMenus();
255
- }
256
-
257
- function clearGroupingFromMenu(columnId: string) {
258
- const current = ctx.grid.getState().grouping ?? [];
259
- ctx.grid.setGrouping(current.filter((id: string) => id !== columnId));
260
- closeMenus();
261
- }
262
-
263
- function isFacetChecked(columnId: string, value: string) {
264
- const selected = ctx.valueFilters[columnId];
265
- return selected ? selected.has(value) : true;
266
- }
267
-
268
- function toggleFacetValue(columnId: string, value: string) {
269
- const allValues = ctx.columnMenuFacetValues;
270
- const next = new Set(ctx.valueFilters[columnId] ?? allValues);
271
- if (next.has(value)) next.delete(value);
272
- else next.add(value);
273
- if (next.size === allValues.length) {
274
- const copy = { ...ctx.valueFilters };
275
- delete copy[columnId];
276
- ctx.valueFilters = copy;
277
- } else {
278
- ctx.valueFilters = { ...ctx.valueFilters, [columnId]: next };
279
- }
280
- }
281
-
282
- /**
283
- * Replace a column's checked-facet set. "Everything checked" is stored as an
284
- * ABSENT entry (so an unfiltered high-cardinality column never holds a set of
285
- * every value), which is why the full-size case deletes instead of writing.
286
- */
287
- function setFacetSelection(columnId: string, next: ReadonlySet<string>) {
288
- if (next.size >= ctx.columnMenuFacetValues.length) {
289
- const copy = { ...ctx.valueFilters };
290
- delete copy[columnId];
291
- ctx.valueFilters = copy;
292
- return;
293
- }
294
- ctx.valueFilters = { ...ctx.valueFilters, [columnId]: new Set(next) };
295
- }
296
-
297
- function isAllFacetsChecked(columnId: string) {
298
- const selected = ctx.valueFilters[columnId];
299
- return !selected || selected.size >= ctx.columnMenuFacetValues.length;
300
- }
301
-
302
- function toggleAllFacets(columnId: string) {
303
- if (isAllFacetsChecked(columnId)) {
304
- ctx.valueFilters = { ...ctx.valueFilters, [columnId]: new Set<string>() };
305
- } else {
306
- const copy = { ...ctx.valueFilters };
307
- delete copy[columnId];
308
- ctx.valueFilters = copy;
309
- }
310
- }
311
-
312
- function clearColumnFilter(columnId: string) {
313
- // `untrack`: read-modify-write on the filter maps. Keeps the method safe to
314
- // call from a consumer's reactive `$effect` (e.g. via `api.clearFilter`)
315
- // without capturing these reads as a dependency and looping. See
316
- // `build-api`'s `setFilter` for the full rationale.
317
- untrack(() => {
318
- if (ctx.valueFilters[columnId]) {
319
- const next = { ...ctx.valueFilters };
320
- delete next[columnId];
321
- ctx.valueFilters = next;
322
- }
323
- if (ctx.filterMenuValues[columnId]) {
324
- const next = { ...ctx.filterMenuValues };
325
- delete next[columnId];
326
- ctx.filterMenuValues = next;
327
- }
328
- if (ctx.filterRowValues[columnId]) {
329
- const next = { ...ctx.filterRowValues };
330
- delete next[columnId];
331
- ctx.filterRowValues = next;
332
- }
333
- });
334
- }
335
-
336
- // External pagination is controlled: emit the requested page/size and let
337
- // the consumer fetch + update props. Never mutate local pagination state.
338
- function emitExternalPagination(pageIndex: number, pageSize: number): boolean {
339
- if (ctx.props.externalPagination !== true) return false;
340
- ctx.props.onPaginationChange?.({ pageIndex: Math.max(0, pageIndex), pageSize });
341
- ctx.scrollContainer?.scrollTo?.({ top: 0 });
342
- return true;
343
- }
344
-
345
- function changePage(delta: number) {
346
- if (
347
- emitExternalPagination(
348
- (ctx.props.pageIndex ?? 0) + delta,
349
- ctx.props.pageSize ?? 10,
350
- )
351
- )
352
- return;
353
- ctx.grid.setPagination((prev: any) => ({
354
- ...prev,
355
- pageIndex: Math.max((prev?.pageIndex ?? 0) + delta, 0),
356
- }));
357
- ctx.scrollContainer?.scrollTo?.({ top: 0 });
358
- }
359
-
360
- function goToPage(pageIndex: number) {
361
- if (emitExternalPagination(pageIndex, ctx.props.pageSize ?? 10)) return;
362
- ctx.grid.setPagination((prev: any) => ({
363
- ...prev,
364
- pageIndex: Math.max(0, pageIndex),
365
- }));
366
- ctx.scrollContainer?.scrollTo?.({ top: 0 });
367
- }
368
-
369
- function setPageSize(pageSize: number) {
370
- // External mode: changing page size resets to the first page.
371
- if (emitExternalPagination(0, pageSize)) return;
372
- ctx.grid.setPagination((prev: any) => {
373
- const oldSize = prev?.pageSize ?? 10;
374
- const oldIndex = prev?.pageIndex ?? 0;
375
- // Keep the first visible row in view when the page size changes.
376
- const firstVisibleRow = oldIndex * oldSize;
377
- return {
378
- ...prev,
379
- pageSize,
380
- pageIndex: Math.max(0, Math.floor(firstVisibleRow / pageSize)),
381
- };
382
- });
383
- }
384
-
385
- // ---- Right-click context menu --------------------------------------
386
- type CtxTarget = { rowIndex: number; colIndex: number; columnId: string; rowId: string; row: TData | null };
387
- type ResolvedItem = { key: string; label: string; separator?: boolean; disabled?: boolean; run?: () => void };
388
-
389
- function insertRowAt(t: CtxTarget, offset: number) {
390
- const data = ctx.internalData.slice() as TData[];
391
- const idx = t.row ? data.indexOf(t.row) : -1;
392
- const at = idx < 0 ? data.length : idx + offset;
393
- data.splice(at, 0, {} as TData);
394
- ctx.internalData = data;
395
- }
396
- function removeRowAt(t: CtxTarget) {
397
- if (!t.row) return;
398
- ctx.internalData = (ctx.internalData as TData[]).filter((r) => r !== t.row);
399
- }
400
- function removeColAt(t: CtxTarget) {
401
- ctx.internalColumns = ctx.internalColumns.filter(
402
- (d: any) => (d.id ?? d.field) !== t.columnId,
403
- );
404
- }
405
-
406
- // Built-in items, keyed. `run` reads the live target passed at click time.
407
- // `msg` names the GridMessages key so the label localizes (falls back to the
408
- // English `label` when no `localeText` is set).
409
- const builtins: Record<string, { label: string; msg?: string; run: (t: CtxTarget) => void }> = {
410
- copy: { label: "Copy", msg: "menuCopy", run: () => ctx.copySelectionToClipboard() },
411
- cut: { label: "Cut", msg: "menuCut", run: () => ctx.cutSelectionToClipboard() },
412
- paste: { label: "Paste", msg: "menuPaste", run: () => void ctx.pasteFromClipboard() },
413
- clear: { label: "Clear", msg: "menuClear", run: () => ctx.clearSelectedCells() },
414
- row_above: { label: "Insert row above", msg: "menuInsertRowAbove", run: (t) => insertRowAt(t, 0) },
415
- row_below: { label: "Insert row below", msg: "menuInsertRowBelow", run: (t) => insertRowAt(t, 1) },
416
- remove_row: { label: "Remove row", msg: "menuRemoveRow", run: removeRowAt },
417
- remove_col: { label: "Remove column", msg: "menuRemoveColumn", run: removeColAt },
418
- comment: { label: "Edit comment", msg: "menuEditComment", run: (t) => openCommentEditor(t) },
419
- // Charting: open the chart panel scoped to the current cell selection. Gated
420
- // on `chartingEnabled` in the resolver below.
421
- chart: { label: "Chart selected range", msg: "chartRange", run: () => { ctx.chartPanelOpen = true; } },
422
- };
423
- const DEFAULT_ITEMS = [
424
- "copy", "cut", "paste", "clear", "separator",
425
- "row_above", "row_below", "remove_row", "separator", "remove_col",
426
- ];
427
-
428
- function openContextMenu(
429
- event: MouseEvent,
430
- rowIndex: number,
431
- colIndex: number,
432
- columnId: string,
433
- ) {
434
- if (!ctx.props.contextMenu) return;
435
- event.preventDefault();
436
- closeMenus();
437
- ctx.contextMenuFor = null;
438
- const rowModel = ctx.allRows[rowIndex];
439
- const row = rowModel?.original ?? null;
440
- const rowId = rowModel?.id ?? String(rowIndex);
441
- // Reserve ~280px for the menu body. If the click is in the bottom third,
442
- // flip the menu above the cursor so it stays fully in the viewport.
443
- const menuHeight = 280;
444
- const y = event.clientY + menuHeight > window.innerHeight
445
- ? Math.max(8, event.clientY - menuHeight)
446
- : event.clientY;
447
- ctx.contextMenuPos = {
448
- x: clampMenuX(event.clientX, 220),
449
- y,
450
- };
451
- ctx.contextMenuFor = { rowIndex, colIndex, columnId, rowId, row };
452
- }
453
-
454
- function closeContextMenu() {
455
- ctx.contextMenuFor = null;
456
- }
457
-
458
- // ---- Editable comments ---------------------------------------------
459
- function openCommentEditor(t: CtxTarget) {
460
- const cur =
461
- ctx.noteOverrides?.[t.rowId]?.[t.columnId] ??
462
- ctx.props.notes?.[t.rowId]?.[t.columnId] ??
463
- "";
464
- ctx.commentDraft = cur;
465
- ctx.commentEditFor = { rowId: t.rowId, columnId: t.columnId, x: ctx.contextMenuPos.x, y: ctx.contextMenuPos.y };
466
- ctx.contextMenuFor = null;
467
- }
468
- function writeNote(rowId: string, columnId: string, note: string) {
469
- const next = { ...ctx.noteOverrides };
470
- next[rowId] = { ...(next[rowId] ?? {}), [columnId]: note };
471
- ctx.noteOverrides = next;
472
- ctx.props.onNoteChange?.({ rowId, columnId, note });
473
- }
474
- function saveComment() {
475
- const e = ctx.commentEditFor;
476
- if (!e) return;
477
- writeNote(e.rowId, e.columnId, ctx.commentDraft);
478
- ctx.commentEditFor = null;
479
- }
480
- function removeComment() {
481
- const e = ctx.commentEditFor;
482
- if (!e) return;
483
- writeNote(e.rowId, e.columnId, "");
484
- ctx.commentEditFor = null;
485
- }
486
- function closeCommentEditor() {
487
- ctx.commentEditFor = null;
488
- }
489
-
490
- /** Resolve the configured items against the current target for rendering. */
491
- function contextMenuItems(): ResolvedItem[] {
492
- const target = ctx.contextMenuFor as CtxTarget | null;
493
- if (!target) return [];
494
- const cfg = ctx.props.contextMenu;
495
- const messages = ctx.messages;
496
- const entries: any[] = Array.isArray(cfg)
497
- ? cfg
498
- : [
499
- ...DEFAULT_ITEMS,
500
- ...(ctx.chartingEnabled ? ["separator", "chart"] : []),
501
- ...(ctx.props.editableComments ? ["separator", "comment"] : []),
502
- ];
503
- const out: ResolvedItem[] = [];
504
- for (const entry of entries) {
505
- if (entry === "separator") { out.push({ key: "sep" + out.length, label: "", separator: true }); continue; }
506
- if (typeof entry === "string") {
507
- // The chart item only makes sense when charting is enabled.
508
- if (entry === "chart" && !ctx.chartingEnabled) continue;
509
- const b = builtins[entry];
510
- if (!b) continue;
511
- const label = (b.msg && messages?.[b.msg]) || b.label;
512
- out.push({ key: entry, label, run: () => b.run(target) });
513
- continue;
514
- }
515
- if (entry.hidden?.(target)) continue;
516
- out.push({
517
- key: entry.key,
518
- label: entry.label,
519
- disabled: entry.disabled?.(target) ?? false,
520
- run: () => entry.action(target),
521
- });
522
- }
523
- // Drop leading/trailing/double separators.
524
- return out.filter((it, i, a) =>
525
- !it.separator || (i > 0 && i < a.length - 1 && !a[i - 1]?.separator),
526
- );
527
- }
528
-
529
- return {
530
- updateFilterRow,
531
- updateFilterOperator,
532
- updateFilterMenuValue,
533
- updateFilterMenuValueTo,
534
- addFilterToken,
535
- removeFilterToken,
536
- toggleFilterToken,
537
- toggleCheckboxWithKeyboard,
538
- isColumnFiltered,
539
- closeMenus,
540
- openInSuggest,
541
- closeInSuggest,
542
- openChooseColumns,
543
- openColumnMenu,
544
- openFilterMenu,
545
- openOperatorMenu,
546
- sortColumnFromMenu,
547
- clearColumnSort,
548
- groupByColumnFromMenu,
549
- clearGroupingFromMenu,
550
- isFacetChecked,
551
- toggleFacetValue,
552
- setFacetSelection,
553
- setFilterTokens,
554
- isAllFacetsChecked,
555
- toggleAllFacets,
556
- clearColumnFilter,
557
- changePage,
558
- goToPage,
559
- setPageSize,
560
- openContextMenu,
561
- closeContextMenu,
562
- contextMenuItems,
563
- saveComment,
564
- removeComment,
565
- closeCommentEditor,
566
- };
567
- }
1
+ // menus handlers extracted from the controller. Imperative event handlers
2
+ // reading/writing controller state via the `ctx` handle; the reactive core
3
+ // ($state/$derived/$effect) stays in the controller.
4
+ import {
5
+ type RowData,
6
+ type TableFeatures,
7
+ } from "./index";
8
+ import "./sv-grid-scrollbar";
9
+ import { untrack } from "svelte";
10
+ import type {
11
+ FilterOperator,
12
+ } from "./SvGrid.types";
13
+ import {
14
+ clampMenuX,
15
+ cssEscape,
16
+ } from "./SvGrid.helpers";
17
+ import { splitInTokens, joinInTokens } from "./filtering/excel-filters";
18
+
19
+ export function createMenus<
20
+ TFeatures extends TableFeatures = TableFeatures,
21
+ TData extends RowData = RowData,
22
+ >(ctx: any) {
23
+ function updateFilterRow(columnId: string, value: string) {
24
+ ctx.filterRowValues = { ...ctx.filterRowValues, [columnId]: value };
25
+ const current = ctx.filterMenuValues[columnId] ?? {
26
+ operator: "contains" as const,
27
+ value: "",
28
+ };
29
+ ctx.filterMenuValues = {
30
+ ...ctx.filterMenuValues,
31
+ [columnId]: { ...current, value },
32
+ };
33
+ }
34
+
35
+ function updateFilterOperator(columnId: string, operator: FilterOperator) {
36
+ const current = ctx.filterMenuValues[columnId] ?? {
37
+ operator: "contains" as const,
38
+ value: "",
39
+ };
40
+ ctx.filterMenuValues = {
41
+ ...ctx.filterMenuValues,
42
+ [columnId]: { ...current, operator },
43
+ };
44
+ }
45
+
46
+ function updateFilterMenuValue(columnId: string, value: string) {
47
+ const current = ctx.filterMenuValues[columnId] ?? {
48
+ operator: "contains" as const,
49
+ value: "",
50
+ };
51
+ ctx.filterMenuValues = {
52
+ ...ctx.filterMenuValues,
53
+ [columnId]: { ...current, value },
54
+ };
55
+ ctx.filterRowValues = { ...ctx.filterRowValues, [columnId]: value };
56
+ }
57
+
58
+ /** Upper-bound input for the `between` operator. Only relevant when
59
+ * the column's current operator is `between`; harmless to call
60
+ * otherwise. */
61
+ function updateFilterMenuValueTo(columnId: string, valueTo: string) {
62
+ const current = ctx.filterMenuValues[columnId] ?? {
63
+ operator: "between" as const,
64
+ value: "",
65
+ };
66
+ ctx.filterMenuValues = {
67
+ ...ctx.filterMenuValues,
68
+ [columnId]: { ...current, valueTo },
69
+ };
70
+ }
71
+
72
+ /** Current `in` / `notIn` token list for a column (from the filter-row value). */
73
+ function filterTokens(columnId: string): string[] {
74
+ return splitInTokens(ctx.filterRowValues[columnId] ?? "");
75
+ }
76
+
77
+ /** Add a value to a column's `in` / `notIn` list (no-op if already present). */
78
+ function addFilterToken(columnId: string, token: string) {
79
+ const t = token.trim();
80
+ if (!t) return;
81
+ const tokens = filterTokens(columnId);
82
+ if (!tokens.includes(t)) tokens.push(t);
83
+ updateFilterRow(columnId, joinInTokens(tokens));
84
+ }
85
+
86
+ /** Remove a value from a column's `in` / `notIn` list. */
87
+ function removeFilterToken(columnId: string, token: string) {
88
+ updateFilterRow(
89
+ columnId,
90
+ joinInTokens(filterTokens(columnId).filter((t) => t !== token)),
91
+ );
92
+ }
93
+
94
+ /** Toggle a value in a column's `in` / `notIn` list (checklist behaviour). */
95
+ function toggleFilterToken(columnId: string, token: string) {
96
+ if (filterTokens(columnId).includes(token)) removeFilterToken(columnId, token);
97
+ else addFilterToken(columnId, token);
98
+ }
99
+
100
+ /**
101
+ * Replace a column's `in` / `notIn` list wholesale. The suggestions dropdown
102
+ * hands back the full token set after a click, which keeps tokens the user
103
+ * typed by hand (or that the search box is currently hiding) intact.
104
+ */
105
+ function setFilterTokens(columnId: string, tokens: Iterable<string>) {
106
+ const list = [...tokens].map((t) => t.trim()).filter(Boolean);
107
+ updateFilterRow(columnId, joinInTokens(list));
108
+ }
109
+
110
+ function toggleCheckboxWithKeyboard(
111
+ event: KeyboardEvent,
112
+ toggle: () => void,
113
+ ) {
114
+ if (event.key !== "Enter" && event.key !== " ") return;
115
+ event.preventDefault();
116
+ toggle();
117
+ }
118
+
119
+ function isColumnFiltered(columnId: string) {
120
+ if (ctx.valueFilters[columnId]) return true;
121
+ const menuFilter = ctx.filterMenuValues[columnId];
122
+ return Boolean(
123
+ menuFilter &&
124
+ (menuFilter.operator === "isBlank" ||
125
+ menuFilter.operator === "isNotBlank" ||
126
+ menuFilter.value.trim()),
127
+ );
128
+ }
129
+
130
+ function closeMenus() {
131
+ ctx.columnMenuFor = null;
132
+ ctx.filterMenuFor = null;
133
+ ctx.operatorMenuFor = null;
134
+ ctx.inSuggestFor = null;
135
+ ctx.chooseColumnsPos = null;
136
+ }
137
+
138
+ /** Open the `in` / `notIn` value-suggestions dropdown under a chip input. */
139
+ function openInSuggest(anchor: HTMLElement, columnId: string) {
140
+ const rect = anchor.getBoundingClientRect();
141
+ ctx.inSuggestPos = { x: clampMenuX(rect.left, 220), y: rect.bottom + 4 };
142
+ ctx.inSuggestQuery = "";
143
+ ctx.inSuggestFor = columnId;
144
+ }
145
+
146
+ function closeInSuggest() {
147
+ ctx.inSuggestFor = null;
148
+ ctx.inSuggestQuery = "";
149
+ }
150
+
151
+ function openChooseColumns(event: MouseEvent) {
152
+ event.stopPropagation();
153
+ // Submenu behavior: keep the parent operations menu open and float the
154
+ // Choose Columns panel out to the right of it (AG-Grid style). Falls
155
+ // back to below the item if the popover would clip the viewport.
156
+ const trigger = event.currentTarget as HTMLElement;
157
+ const menuEl = trigger.closest(".sv-grid-menu") as HTMLElement | null;
158
+ const anchor = (menuEl ?? trigger).getBoundingClientRect();
159
+ const panelWidth = 240;
160
+ const wantRight = anchor.right + 4;
161
+ const x =
162
+ wantRight + panelWidth + 8 > window.innerWidth
163
+ ? clampMenuX(anchor.left - panelWidth - 4, panelWidth)
164
+ : clampMenuX(wantRight, panelWidth);
165
+ ctx.chooseColumnsPos = { x, y: anchor.top };
166
+ }
167
+
168
+ function openColumnMenu(event: MouseEvent, columnId: string) {
169
+ event.stopPropagation();
170
+ const wasOpen = ctx.columnMenuFor === columnId;
171
+ closeMenus();
172
+ if (wasOpen) return;
173
+ const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
174
+ ctx.columnMenuPos = {
175
+ x: clampMenuX(rect.right - 240, 240),
176
+ y: rect.bottom + 4,
177
+ };
178
+ ctx.columnMenuTab = "general";
179
+ ctx.columnMenuFor = columnId;
180
+ }
181
+
182
+ function openFilterMenu(event: MouseEvent, columnId: string) {
183
+ event.stopPropagation();
184
+ const wasOpen = ctx.filterMenuFor === columnId;
185
+ closeMenus();
186
+ if (wasOpen) return;
187
+
188
+ // If the consumer is running in row-mode (or any mode where the
189
+ // funnel popover wouldn't render), redirect the click to the
190
+ // inline filter input for this column. Without this the funnel
191
+ // would be a dead button - it visibly clicks but nothing happens
192
+ // because the menu is gated behind `showColumnFiltersEffective`.
193
+ if (!ctx.showColumnFiltersEffective && ctx.showFilterRowEffective) {
194
+ // Find the row-mode filter input and focus it. The input is
195
+ // tagged with `data-svgrid-filter-col` so we can target by id
196
+ // without depending on column position.
197
+ const input = (ctx.scrollContainer as HTMLElement | null)?.querySelector<HTMLInputElement>(
198
+ `[data-svgrid-filter-col="${cssEscape(columnId)}"]`,
199
+ );
200
+ if (input) {
201
+ input.focus();
202
+ input.select();
203
+ // Brief pulse so the user sees where focus landed.
204
+ input.classList.add("sv-grid-filter-value-pulse");
205
+ setTimeout(() => input.classList.remove("sv-grid-filter-value-pulse"), 700);
206
+ }
207
+ return;
208
+ }
209
+
210
+ const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
211
+ ctx.filterMenuPos = {
212
+ x: clampMenuX(rect.right - 260, 260),
213
+ y: rect.bottom + 4,
214
+ };
215
+ ctx.columnMenuSearch = "";
216
+ ctx.filterMenuFor = columnId;
217
+ }
218
+
219
+ function openOperatorMenu(event: MouseEvent, columnId: string) {
220
+ event.stopPropagation();
221
+ const wasOpen = ctx.operatorMenuFor === columnId;
222
+ closeMenus();
223
+ if (wasOpen) return;
224
+ const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
225
+ ctx.operatorMenuPos = { x: clampMenuX(rect.left, 184), y: rect.bottom + 4 };
226
+ ctx.operatorMenuFor = columnId;
227
+ }
228
+
229
+ function sortColumnFromMenu(columnId: string, desc: boolean) {
230
+ ctx.grid.store.setState((prev: any) => ({
231
+ ...prev,
232
+ sorting: [{ id: columnId, desc }],
233
+ }));
234
+ closeMenus();
235
+ }
236
+
237
+ function clearColumnSort(columnId: string) {
238
+ ctx.grid.store.setState((prev: any) => ({
239
+ ...prev,
240
+ sorting: (prev.sorting ?? []).filter(
241
+ (entry: { id: string }) => entry.id !== columnId,
242
+ ),
243
+ }));
244
+ closeMenus();
245
+ }
246
+
247
+ function groupByColumnFromMenu(columnId: string) {
248
+ const current = ctx.grid.getState().grouping ?? [];
249
+ if (current.includes(columnId)) {
250
+ closeMenus();
251
+ return;
252
+ }
253
+ ctx.grid.setGrouping([...current, columnId]);
254
+ closeMenus();
255
+ }
256
+
257
+ function clearGroupingFromMenu(columnId: string) {
258
+ const current = ctx.grid.getState().grouping ?? [];
259
+ ctx.grid.setGrouping(current.filter((id: string) => id !== columnId));
260
+ closeMenus();
261
+ }
262
+
263
+ function isFacetChecked(columnId: string, value: string) {
264
+ const selected = ctx.valueFilters[columnId];
265
+ return selected ? selected.has(value) : true;
266
+ }
267
+
268
+ function toggleFacetValue(columnId: string, value: string) {
269
+ const allValues = ctx.columnMenuFacetValues;
270
+ const next = new Set(ctx.valueFilters[columnId] ?? allValues);
271
+ if (next.has(value)) next.delete(value);
272
+ else next.add(value);
273
+ if (next.size === allValues.length) {
274
+ const copy = { ...ctx.valueFilters };
275
+ delete copy[columnId];
276
+ ctx.valueFilters = copy;
277
+ } else {
278
+ ctx.valueFilters = { ...ctx.valueFilters, [columnId]: next };
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Replace a column's checked-facet set. "Everything checked" is stored as an
284
+ * ABSENT entry (so an unfiltered high-cardinality column never holds a set of
285
+ * every value), which is why the full-size case deletes instead of writing.
286
+ */
287
+ function setFacetSelection(columnId: string, next: ReadonlySet<string>) {
288
+ if (next.size >= ctx.columnMenuFacetValues.length) {
289
+ const copy = { ...ctx.valueFilters };
290
+ delete copy[columnId];
291
+ ctx.valueFilters = copy;
292
+ return;
293
+ }
294
+ ctx.valueFilters = { ...ctx.valueFilters, [columnId]: new Set(next) };
295
+ }
296
+
297
+ function isAllFacetsChecked(columnId: string) {
298
+ const selected = ctx.valueFilters[columnId];
299
+ return !selected || selected.size >= ctx.columnMenuFacetValues.length;
300
+ }
301
+
302
+ function toggleAllFacets(columnId: string) {
303
+ if (isAllFacetsChecked(columnId)) {
304
+ ctx.valueFilters = { ...ctx.valueFilters, [columnId]: new Set<string>() };
305
+ } else {
306
+ const copy = { ...ctx.valueFilters };
307
+ delete copy[columnId];
308
+ ctx.valueFilters = copy;
309
+ }
310
+ }
311
+
312
+ function clearColumnFilter(columnId: string) {
313
+ // `untrack`: read-modify-write on the filter maps. Keeps the method safe to
314
+ // call from a consumer's reactive `$effect` (e.g. via `api.clearFilter`)
315
+ // without capturing these reads as a dependency and looping. See
316
+ // `build-api`'s `setFilter` for the full rationale.
317
+ untrack(() => {
318
+ if (ctx.valueFilters[columnId]) {
319
+ const next = { ...ctx.valueFilters };
320
+ delete next[columnId];
321
+ ctx.valueFilters = next;
322
+ }
323
+ if (ctx.filterMenuValues[columnId]) {
324
+ const next = { ...ctx.filterMenuValues };
325
+ delete next[columnId];
326
+ ctx.filterMenuValues = next;
327
+ }
328
+ if (ctx.filterRowValues[columnId]) {
329
+ const next = { ...ctx.filterRowValues };
330
+ delete next[columnId];
331
+ ctx.filterRowValues = next;
332
+ }
333
+ });
334
+ }
335
+
336
+ // External pagination is controlled: emit the requested page/size and let
337
+ // the consumer fetch + update props. Never mutate local pagination state.
338
+ function emitExternalPagination(pageIndex: number, pageSize: number): boolean {
339
+ if (ctx.props.externalPagination !== true) return false;
340
+ ctx.props.onPaginationChange?.({ pageIndex: Math.max(0, pageIndex), pageSize });
341
+ ctx.scrollContainer?.scrollTo?.({ top: 0 });
342
+ return true;
343
+ }
344
+
345
+ function changePage(delta: number) {
346
+ if (
347
+ emitExternalPagination(
348
+ (ctx.props.pageIndex ?? 0) + delta,
349
+ ctx.props.pageSize ?? 10,
350
+ )
351
+ )
352
+ return;
353
+ ctx.grid.setPagination((prev: any) => ({
354
+ ...prev,
355
+ pageIndex: Math.max((prev?.pageIndex ?? 0) + delta, 0),
356
+ }));
357
+ ctx.scrollContainer?.scrollTo?.({ top: 0 });
358
+ }
359
+
360
+ function goToPage(pageIndex: number) {
361
+ if (emitExternalPagination(pageIndex, ctx.props.pageSize ?? 10)) return;
362
+ ctx.grid.setPagination((prev: any) => ({
363
+ ...prev,
364
+ pageIndex: Math.max(0, pageIndex),
365
+ }));
366
+ ctx.scrollContainer?.scrollTo?.({ top: 0 });
367
+ }
368
+
369
+ function setPageSize(pageSize: number) {
370
+ // External mode: changing page size resets to the first page.
371
+ if (emitExternalPagination(0, pageSize)) return;
372
+ ctx.grid.setPagination((prev: any) => {
373
+ const oldSize = prev?.pageSize ?? 10;
374
+ const oldIndex = prev?.pageIndex ?? 0;
375
+ // Keep the first visible row in view when the page size changes.
376
+ const firstVisibleRow = oldIndex * oldSize;
377
+ return {
378
+ ...prev,
379
+ pageSize,
380
+ pageIndex: Math.max(0, Math.floor(firstVisibleRow / pageSize)),
381
+ };
382
+ });
383
+ }
384
+
385
+ // ---- Right-click context menu --------------------------------------
386
+ type CtxTarget = { rowIndex: number; colIndex: number; columnId: string; rowId: string; row: TData | null };
387
+ type ResolvedItem = { key: string; label: string; separator?: boolean; disabled?: boolean; run?: () => void };
388
+
389
+ function insertRowAt(t: CtxTarget, offset: number) {
390
+ const data = ctx.internalData.slice() as TData[];
391
+ const idx = t.row ? data.indexOf(t.row) : -1;
392
+ const at = idx < 0 ? data.length : idx + offset;
393
+ data.splice(at, 0, {} as TData);
394
+ ctx.internalData = data;
395
+ }
396
+ function removeRowAt(t: CtxTarget) {
397
+ if (!t.row) return;
398
+ ctx.internalData = (ctx.internalData as TData[]).filter((r) => r !== t.row);
399
+ }
400
+ function removeColAt(t: CtxTarget) {
401
+ ctx.internalColumns = ctx.internalColumns.filter(
402
+ (d: any) => (d.id ?? d.field) !== t.columnId,
403
+ );
404
+ }
405
+
406
+ // Built-in items, keyed. `run` reads the live target passed at click time.
407
+ // `msg` names the GridMessages key so the label localizes (falls back to the
408
+ // English `label` when no `localeText` is set).
409
+ const builtins: Record<string, { label: string; msg?: string; run: (t: CtxTarget) => void }> = {
410
+ copy: { label: "Copy", msg: "menuCopy", run: () => ctx.copySelectionToClipboard() },
411
+ cut: { label: "Cut", msg: "menuCut", run: () => ctx.cutSelectionToClipboard() },
412
+ paste: { label: "Paste", msg: "menuPaste", run: () => void ctx.pasteFromClipboard() },
413
+ clear: { label: "Clear", msg: "menuClear", run: () => ctx.clearSelectedCells() },
414
+ row_above: { label: "Insert row above", msg: "menuInsertRowAbove", run: (t) => insertRowAt(t, 0) },
415
+ row_below: { label: "Insert row below", msg: "menuInsertRowBelow", run: (t) => insertRowAt(t, 1) },
416
+ remove_row: { label: "Remove row", msg: "menuRemoveRow", run: removeRowAt },
417
+ remove_col: { label: "Remove column", msg: "menuRemoveColumn", run: removeColAt },
418
+ comment: { label: "Edit comment", msg: "menuEditComment", run: (t) => openCommentEditor(t) },
419
+ // Charting: open the chart panel scoped to the current cell selection. Gated
420
+ // on `chartingEnabled` in the resolver below.
421
+ chart: { label: "Chart selected range", msg: "chartRange", run: () => { ctx.chartPanelOpen = true; } },
422
+ };
423
+ const DEFAULT_ITEMS = [
424
+ "copy", "cut", "paste", "clear", "separator",
425
+ "row_above", "row_below", "remove_row", "separator", "remove_col",
426
+ ];
427
+
428
+ function openContextMenu(
429
+ event: MouseEvent,
430
+ rowIndex: number,
431
+ colIndex: number,
432
+ columnId: string,
433
+ ) {
434
+ if (!ctx.props.contextMenu) return;
435
+ event.preventDefault();
436
+ closeMenus();
437
+ ctx.contextMenuFor = null;
438
+ const rowModel = ctx.allRows[rowIndex];
439
+ const row = rowModel?.original ?? null;
440
+ const rowId = rowModel?.id ?? String(rowIndex);
441
+ // Reserve ~280px for the menu body. If the click is in the bottom third,
442
+ // flip the menu above the cursor so it stays fully in the viewport.
443
+ const menuHeight = 280;
444
+ const y = event.clientY + menuHeight > window.innerHeight
445
+ ? Math.max(8, event.clientY - menuHeight)
446
+ : event.clientY;
447
+ ctx.contextMenuPos = {
448
+ x: clampMenuX(event.clientX, 220),
449
+ y,
450
+ };
451
+ ctx.contextMenuFor = { rowIndex, colIndex, columnId, rowId, row };
452
+ }
453
+
454
+ function closeContextMenu() {
455
+ ctx.contextMenuFor = null;
456
+ }
457
+
458
+ // ---- Editable comments ---------------------------------------------
459
+ function openCommentEditor(t: CtxTarget) {
460
+ const cur =
461
+ ctx.noteOverrides?.[t.rowId]?.[t.columnId] ??
462
+ ctx.props.notes?.[t.rowId]?.[t.columnId] ??
463
+ "";
464
+ ctx.commentDraft = cur;
465
+ ctx.commentEditFor = { rowId: t.rowId, columnId: t.columnId, x: ctx.contextMenuPos.x, y: ctx.contextMenuPos.y };
466
+ ctx.contextMenuFor = null;
467
+ }
468
+ function writeNote(rowId: string, columnId: string, note: string) {
469
+ const next = { ...ctx.noteOverrides };
470
+ next[rowId] = { ...(next[rowId] ?? {}), [columnId]: note };
471
+ ctx.noteOverrides = next;
472
+ ctx.props.onNoteChange?.({ rowId, columnId, note });
473
+ }
474
+ function saveComment() {
475
+ const e = ctx.commentEditFor;
476
+ if (!e) return;
477
+ writeNote(e.rowId, e.columnId, ctx.commentDraft);
478
+ ctx.commentEditFor = null;
479
+ }
480
+ function removeComment() {
481
+ const e = ctx.commentEditFor;
482
+ if (!e) return;
483
+ writeNote(e.rowId, e.columnId, "");
484
+ ctx.commentEditFor = null;
485
+ }
486
+ function closeCommentEditor() {
487
+ ctx.commentEditFor = null;
488
+ }
489
+
490
+ /** Resolve the configured items against the current target for rendering. */
491
+ function contextMenuItems(): ResolvedItem[] {
492
+ const target = ctx.contextMenuFor as CtxTarget | null;
493
+ if (!target) return [];
494
+ const cfg = ctx.props.contextMenu;
495
+ const messages = ctx.messages;
496
+ const entries: any[] = Array.isArray(cfg)
497
+ ? cfg
498
+ : [
499
+ ...DEFAULT_ITEMS,
500
+ ...(ctx.chartingEnabled ? ["separator", "chart"] : []),
501
+ ...(ctx.props.editableComments ? ["separator", "comment"] : []),
502
+ ];
503
+ const out: ResolvedItem[] = [];
504
+ for (const entry of entries) {
505
+ if (entry === "separator") { out.push({ key: "sep" + out.length, label: "", separator: true }); continue; }
506
+ if (typeof entry === "string") {
507
+ // The chart item only makes sense when charting is enabled.
508
+ if (entry === "chart" && !ctx.chartingEnabled) continue;
509
+ const b = builtins[entry];
510
+ if (!b) continue;
511
+ const label = (b.msg && messages?.[b.msg]) || b.label;
512
+ out.push({ key: entry, label, run: () => b.run(target) });
513
+ continue;
514
+ }
515
+ if (entry.hidden?.(target)) continue;
516
+ out.push({
517
+ key: entry.key,
518
+ label: entry.label,
519
+ disabled: entry.disabled?.(target) ?? false,
520
+ run: () => entry.action(target),
521
+ });
522
+ }
523
+ // Drop leading/trailing/double separators.
524
+ return out.filter((it, i, a) =>
525
+ !it.separator || (i > 0 && i < a.length - 1 && !a[i - 1]?.separator),
526
+ );
527
+ }
528
+
529
+ return {
530
+ updateFilterRow,
531
+ updateFilterOperator,
532
+ updateFilterMenuValue,
533
+ updateFilterMenuValueTo,
534
+ addFilterToken,
535
+ removeFilterToken,
536
+ toggleFilterToken,
537
+ toggleCheckboxWithKeyboard,
538
+ isColumnFiltered,
539
+ closeMenus,
540
+ openInSuggest,
541
+ closeInSuggest,
542
+ openChooseColumns,
543
+ openColumnMenu,
544
+ openFilterMenu,
545
+ openOperatorMenu,
546
+ sortColumnFromMenu,
547
+ clearColumnSort,
548
+ groupByColumnFromMenu,
549
+ clearGroupingFromMenu,
550
+ isFacetChecked,
551
+ toggleFacetValue,
552
+ setFacetSelection,
553
+ setFilterTokens,
554
+ isAllFacetsChecked,
555
+ toggleAllFacets,
556
+ clearColumnFilter,
557
+ changePage,
558
+ goToPage,
559
+ setPageSize,
560
+ openContextMenu,
561
+ closeContextMenu,
562
+ contextMenuItems,
563
+ saveComment,
564
+ removeComment,
565
+ closeCommentEditor,
566
+ };
567
+ }