@svgrid/grid 2.2.27 → 2.2.29

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 (248) hide show
  1. package/README.md +199 -199
  2. package/dist/FlexRender.svelte +96 -96
  3. package/dist/GridFooter.svelte +179 -179
  4. package/dist/GridMenus.svelte +782 -734
  5. package/dist/SvAutoComplete.svelte +165 -165
  6. package/dist/SvCalendar.svelte +503 -503
  7. package/dist/SvCarousel.svelte +141 -141
  8. package/dist/SvCheckBox.svelte +101 -101
  9. package/dist/SvColorInput.svelte +181 -181
  10. package/dist/SvComboBox.svelte +275 -275
  11. package/dist/SvContextMenu.svelte +116 -116
  12. package/dist/SvCountryInput.svelte +160 -160
  13. package/dist/SvDrawer.svelte +254 -250
  14. package/dist/SvDropDownList.svelte +374 -374
  15. package/dist/SvDurationInput.svelte +126 -126
  16. package/dist/SvField.svelte +293 -293
  17. package/dist/SvForm.svelte +437 -437
  18. package/dist/SvGrid.controller.svelte.d.ts +14 -1
  19. package/dist/SvGrid.controller.svelte.js +112 -28
  20. package/dist/SvGrid.css +2704 -2723
  21. package/dist/SvGrid.svelte +3361 -3333
  22. package/dist/SvGrid.types.d.ts +20 -5
  23. package/dist/SvGridChart.svelte +1724 -1724
  24. package/dist/SvGridChartPanel.svelte +485 -485
  25. package/dist/SvGridChartView.svelte +70 -70
  26. package/dist/SvGridDropdown.svelte +696 -696
  27. package/dist/SvGridSelect.svelte +259 -259
  28. package/dist/SvGroupCell.svelte +109 -109
  29. package/dist/SvListBox.svelte +326 -287
  30. package/dist/SvListBox.svelte.d.ts +10 -1
  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 +281 -281
  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 -131
  39. package/dist/SvPopover.svelte +197 -197
  40. package/dist/SvRadioGroup.svelte +107 -107
  41. package/dist/SvRowGroupPanel.svelte +170 -170
  42. package/dist/SvScrollArea.svelte +61 -61
  43. package/dist/SvSlider.svelte +200 -200
  44. package/dist/SvSwitchButton.svelte +107 -107
  45. package/dist/SvTagsInput.svelte +112 -112
  46. package/dist/SvTextInput.svelte +147 -147
  47. package/dist/SvTimePicker.svelte +245 -245
  48. package/dist/SvToaster.svelte +159 -159
  49. package/dist/SvToggleButton.svelte +85 -85
  50. package/dist/SvTooltip.svelte +161 -161
  51. package/dist/SvTour.svelte +204 -204
  52. package/dist/SvTree.svelte +437 -437
  53. package/dist/SvTreeSelect.svelte +233 -233
  54. package/dist/cdn/GridMenus-Da_p7SKS.js +486 -0
  55. package/dist/cdn/GridMenus-Ds3OpzZT.js +490 -0
  56. package/dist/cdn/{SvDateTimePicker-B1sDc9Pz.js → SvDateTimePicker-B8GopjhC.js} +2 -2
  57. package/dist/cdn/{SvDateTimePicker-Bh0FTs1E.js → SvDateTimePicker-DB0aIEk8.js} +2 -2
  58. package/dist/cdn/{SvGridChart-Bgk4hDs8.js → SvGridChart-BcLCYvw9.js} +1 -1
  59. package/dist/cdn/{SvGridChart-BKQsO5fZ.js → SvGridChart-BhnFdLd0.js} +1 -1
  60. package/dist/cdn/{SvGridChartPanel-DkCc2Z7b.js → SvGridChartPanel-Cmx9DHAS.js} +1 -1
  61. package/dist/cdn/{SvGridChartPanel-DSkHIQDd.js → SvGridChartPanel-DvjwxLvK.js} +1 -1
  62. package/dist/cdn/{SvGridChartView-BrbVaELm.js → SvGridChartView-B40DTJSX.js} +1 -1
  63. package/dist/cdn/{SvGridChartView-i9rWvSKg.js → SvGridChartView-PwqI4s02.js} +1 -1
  64. package/dist/cdn/{SvGridDropdown-D08sVmAy.js → SvGridDropdown-DjALc_4f.js} +1 -1
  65. package/dist/cdn/{SvGridDropdown-CGxxopQ4.js → SvGridDropdown-hpnHvOGt.js} +1 -1
  66. package/dist/cdn/{src-cgs1wcUS.js → src-BLJfdyL0.js} +4034 -3889
  67. package/dist/cdn/{src-Cw8d9U8j.js → src-DYDCiC0D.js} +7053 -6908
  68. package/dist/cdn/svgrid.js +9 -9
  69. package/dist/cdn/svgrid.svelte-external.js +9 -9
  70. package/dist/chart-export.js +8 -8
  71. package/dist/column-groups.js +8 -10
  72. package/dist/column-id.d.ts +9 -0
  73. package/dist/column-id.js +25 -0
  74. package/dist/core.js +2 -1
  75. package/dist/createListbox.svelte.d.ts +15 -2
  76. package/dist/createListbox.svelte.js +27 -6
  77. package/dist/editing.d.ts +1 -0
  78. package/dist/editing.js +45 -10
  79. package/dist/filtering/excel-filters.d.ts +30 -10
  80. package/dist/filtering/excel-filters.js +96 -15
  81. package/dist/index.d.ts +2 -2
  82. package/dist/index.js +2 -2
  83. package/dist/menus.d.ts +2 -0
  84. package/dist/menus.js +25 -0
  85. package/dist/row-resize.js +40 -0
  86. package/dist/selection.js +1 -1
  87. package/package.json +10 -10
  88. package/src/FlexRender.svelte +96 -96
  89. package/src/GridFooter.svelte +179 -179
  90. package/src/GridMenus.svelte +782 -734
  91. package/src/SvAutoComplete.svelte +165 -165
  92. package/src/SvCalendar.svelte +503 -503
  93. package/src/SvCalendar.test.ts +226 -226
  94. package/src/SvCarousel.svelte +141 -141
  95. package/src/SvCheckBox.svelte +101 -101
  96. package/src/SvColorInput.svelte +181 -181
  97. package/src/SvComboBox.svelte +275 -275
  98. package/src/SvContextMenu.svelte +116 -116
  99. package/src/SvCountryInput.svelte +160 -160
  100. package/src/SvDrawer.svelte +254 -250
  101. package/src/SvDrawer.test.ts +18 -1
  102. package/src/SvDropDownList.svelte +374 -374
  103. package/src/SvDurationInput.svelte +126 -126
  104. package/src/SvField.svelte +293 -293
  105. package/src/SvForm.svelte +437 -437
  106. package/src/SvForm.test.ts +411 -411
  107. package/src/SvGrid.controller.svelte.ts +3335 -3239
  108. package/src/SvGrid.css +2704 -2723
  109. package/src/SvGrid.svelte +3361 -3333
  110. package/src/SvGrid.types.ts +1628 -1613
  111. package/src/SvGridChart.svelte +1724 -1724
  112. package/src/SvGridChartPanel.svelte +485 -485
  113. package/src/SvGridChartView.svelte +70 -70
  114. package/src/SvGridDropdown.svelte +696 -696
  115. package/src/SvGridSelect.svelte +259 -259
  116. package/src/SvGroupCell.svelte +109 -109
  117. package/src/SvListBox.svelte +326 -287
  118. package/src/SvMaskedInput.svelte +122 -122
  119. package/src/SvMenu.svelte +124 -124
  120. package/src/SvMenu.test.ts +97 -97
  121. package/src/SvMenuList.svelte +146 -146
  122. package/src/SvMultiSelect.svelte +281 -281
  123. package/src/SvNavPane.test.ts +15 -4
  124. package/src/SvNumberInput.svelte +168 -168
  125. package/src/SvOtpInput.svelte +158 -158
  126. package/src/SvPasswordInput.svelte +151 -151
  127. package/src/SvPhoneInput.svelte +133 -131
  128. package/src/SvPopover.svelte +197 -197
  129. package/src/SvRadioGroup.svelte +107 -107
  130. package/src/SvRowGroupPanel.svelte +170 -170
  131. package/src/SvScrollArea.svelte +61 -61
  132. package/src/SvSlider.svelte +200 -200
  133. package/src/SvSwitchButton.svelte +107 -107
  134. package/src/SvTagsInput.svelte +112 -112
  135. package/src/SvTextInput.svelte +147 -147
  136. package/src/SvTimePicker.svelte +245 -245
  137. package/src/SvToaster.svelte +159 -159
  138. package/src/SvToaster.test.ts +95 -95
  139. package/src/SvToggleButton.svelte +85 -85
  140. package/src/SvTooltip.svelte +161 -161
  141. package/src/SvTour.svelte +204 -204
  142. package/src/SvTree.svelte +437 -437
  143. package/src/SvTreeSelect.svelte +233 -233
  144. package/src/a11y/dismissable.test.ts +119 -119
  145. package/src/a11y/dismissable.ts +114 -114
  146. package/src/a11y.contract.test.ts +49 -49
  147. package/src/a11y.test.ts +59 -59
  148. package/src/a11y.ts +61 -61
  149. package/src/ai.test.ts +502 -502
  150. package/src/ai.ts +1391 -1391
  151. package/src/build-api.coverage.test.ts +633 -633
  152. package/src/build-api.ts +895 -895
  153. package/src/builtin-editors.grid.test.ts +85 -85
  154. package/src/cell-formatting.ts +169 -169
  155. package/src/cell-render.ts +469 -469
  156. package/src/chart-export.ts +201 -201
  157. package/src/chart-view.svelte.ts +36 -36
  158. package/src/chart.ts +2296 -2296
  159. package/src/collaboration.test.ts +104 -104
  160. package/src/collaboration.ts +167 -167
  161. package/src/column-groups.test.ts +48 -0
  162. package/src/column-groups.ts +8 -10
  163. package/src/column-id.ts +30 -0
  164. package/src/core.performance.test.ts +30 -30
  165. package/src/core.ts +1112 -1111
  166. package/src/createAutocomplete.svelte.ts +132 -132
  167. package/src/createCombobox.svelte.ts +191 -191
  168. package/src/createCountryInput.svelte.ts +157 -157
  169. package/src/createDropdownList.svelte.ts +168 -168
  170. package/src/createForm.svelte.ts +386 -386
  171. package/src/createGrid.svelte.ts +42 -42
  172. package/src/createGrid.test.ts +10 -10
  173. package/src/createGridState.svelte.ts +17 -17
  174. package/src/createListbox.svelte.ts +39 -7
  175. package/src/createMenu.svelte.ts +225 -225
  176. package/src/createPopoverSelect.svelte.ts +213 -213
  177. package/src/createSlider.svelte.ts +191 -191
  178. package/src/createTooltip.svelte.ts +144 -144
  179. package/src/createTree.svelte.ts +319 -319
  180. package/src/editing.test.ts +949 -859
  181. package/src/editing.ts +709 -675
  182. package/src/editor-contract.ts +157 -157
  183. package/src/export-data-api.test.ts +126 -126
  184. package/src/export-format.test.ts +107 -107
  185. package/src/export-format.ts +598 -598
  186. package/src/filter-operators.ts +157 -157
  187. package/src/filtering/excel-filters.test.ts +44 -1
  188. package/src/filtering/excel-filters.ts +91 -14
  189. package/src/flex-render.ts +3 -3
  190. package/src/form-field.ts +127 -127
  191. package/src/index.ts +715 -713
  192. package/src/js-scroller.svelte.ts +173 -173
  193. package/src/keyboard.test.ts +59 -59
  194. package/src/keyboard.ts +97 -97
  195. package/src/list-nav.test.ts +49 -49
  196. package/src/list-nav.ts +29 -29
  197. package/src/list-option.test.ts +56 -56
  198. package/src/list-option.ts +172 -172
  199. package/src/menus.test.ts +736 -700
  200. package/src/menus.ts +679 -652
  201. package/src/merge-objects.ts +48 -48
  202. package/src/overlays.test.ts +90 -90
  203. package/src/render-component.ts +28 -28
  204. package/src/row-resize.test.ts +100 -0
  205. package/src/row-resize.ts +36 -0
  206. package/src/scheduler-model.test.ts +562 -562
  207. package/src/scheduler-model.ts +872 -872
  208. package/src/selection.test.ts +754 -754
  209. package/src/selection.ts +600 -600
  210. package/src/server-data-source.test.ts +289 -289
  211. package/src/server-data-source.ts +413 -413
  212. package/src/sparkline.test.ts +68 -68
  213. package/src/sparkline.ts +169 -169
  214. package/src/spreadsheet.test.ts +489 -489
  215. package/src/spreadsheet.ts +312 -312
  216. package/src/static-functions.ts +11 -11
  217. package/src/subscribe.ts +38 -38
  218. package/src/svgrid-wrapper.types.ts +524 -524
  219. package/src/svgrid.api-extensions.test.ts +8 -3
  220. package/src/svgrid.behavior.test.ts +706 -706
  221. package/src/svgrid.cell-dom-ids.test.ts +96 -0
  222. package/src/svgrid.charting.test.ts +534 -534
  223. package/src/svgrid.conditional-stat-scope.test.ts +111 -0
  224. package/src/svgrid.features.test.ts +157 -157
  225. package/src/svgrid.filter-menu-listbox.svelte.test.ts +308 -0
  226. package/src/svgrid.filter-menu-scroll.test.ts +3 -1
  227. package/src/svgrid.group-header-ids.test.ts +121 -0
  228. package/src/svgrid.new-features.wrapper.test.ts +251 -251
  229. package/src/svgrid.wrapper.test.ts +40 -40
  230. package/src/test-setup.ts +62 -62
  231. package/src/themes/index.ts +215 -215
  232. package/src/toast-store.svelte.ts +246 -246
  233. package/src/toast-store.test.ts +147 -147
  234. package/src/ui-buttons.test.ts +144 -144
  235. package/src/ui-inputs.test.ts +118 -118
  236. package/src/ui-range.test.ts +70 -70
  237. package/src/ui-selection.test.ts +155 -155
  238. package/src/ui-tier1.test.ts +142 -142
  239. package/src/virtual.test.ts +88 -88
  240. package/src/virtualization/column-virtualizer.test.ts +27 -27
  241. package/src/virtualization/column-virtualizer.ts +30 -30
  242. package/src/virtualization/svelte-virtualizer.svelte.ts +26 -26
  243. package/src/virtualization/types.ts +30 -30
  244. package/src/virtualization/virtualizer.test.ts +47 -47
  245. package/src/virtualization/virtualizer.ts +296 -296
  246. package/themes/ember.css +71 -71
  247. package/dist/cdn/GridMenus-BzxEYNtW.js +0 -421
  248. package/dist/cdn/GridMenus-Dr-nGEXn.js +0 -417
package/src/editing.ts CHANGED
@@ -1,675 +1,709 @@
1
- // editing handlers extracted from the controller. Imperative event handlers
2
- // reading/writing controller state via the `ctx` handle; the reactive core
3
- // ($state/$derived/$effect) stays in the controller.
4
- import {
5
- applyExcelFilter,
6
- normalizeForFilter,
7
- createColumnVirtualizer,
8
- createCoreRowModel,
9
- createExpandedRowModel,
10
- createFilteredRowModel,
11
- createGroupedRowModel,
12
- createPaginatedRowModel,
13
- createSvelteVirtualizer,
14
- createSortedRowModel,
15
- createSvGrid,
16
- filterFns,
17
- getGridCellA11yProps,
18
- getGridCellDomId,
19
- getGridHeaderA11yProps,
20
- getGridRootA11yProps,
21
- getGridRowA11yProps,
22
- parseEditorValue,
23
- normalizeEditorOptions,
24
- sortFns,
25
- tableFeatures,
26
- rowSortingFeature,
27
- columnFilteringFeature,
28
- columnGroupingFeature,
29
- type CellContext,
30
- type EditorContext,
31
- type CellEditorOption,
32
- type CellEditorType,
33
- type CellFormatter,
34
- type CellFormatConfig,
35
- type Column,
36
- type ColumnDef,
37
- type Row,
38
- type RowData,
39
- type SvGridApi,
40
- type TableFeatures,
41
- } from "./index";
42
- import "./sv-grid-scrollbar";
43
- import type { Snippet } from "svelte";
44
- import { getKeyboardIntent, getNextActiveCell } from "./keyboard";
45
- import {
46
- formatNumericWithConfig,
47
- getDateFormatter,
48
- resolveDatePattern,
49
- } from "./cell-formatting";
50
- import {
51
- RenderSnippetConfig,
52
- RenderComponentConfig,
53
- } from "./render-component";
54
- import { buildFillPattern } from "./fill-patterns";
55
- import { buildSparkline, toSparklineValues } from "./sparkline";
56
- import {
57
- resolveCellFormat,
58
- computeColumnStat,
59
- formatsNeedingStats,
60
- type ColumnStat,
61
- type ResolvedCellFormat,
62
- } from "./conditional-formatting";
63
- import SvGridDropdown from "./SvGridDropdown.svelte";
64
- import type {
65
- Props,
66
- SelectionPoint,
67
- SelectionRange,
68
- CellEditState,
69
- FilterOperator,
70
- FilterOption,
71
- MenuPosition,
72
- } from "./SvGrid.types";
73
- import {
74
- cfTextStyle,
75
- fmtStat,
76
- getCellKey,
77
- resolveClassList,
78
- toDateInputValue,
79
- toDateTimeLocalInputValue,
80
- getEditableInputValue,
81
- getEditorInputType,
82
- toValueArray,
83
- getOptionLabel,
84
- getOptionColor,
85
- colorfulChipStyle,
86
- getEditorClass,
87
- asDate,
88
- clampMenuX,
89
- cssEscape,
90
- rawToNumber,
91
- formatFacetNumber,
92
- formatFacetDate,
93
- } from "./SvGrid.helpers";
94
- import { createSelection } from "./selection";
95
- import { createColumns } from "./columns";
96
- import { createGridApi } from "./build-api";
97
- import { createClipboard } from "./clipboard";
98
- import {
99
- filterOperatorOptions,
100
- fallbackOperatorOption,
101
- TEXT_OPERATORS,
102
- NUMBER_OPERATORS,
103
- DATE_OPERATORS,
104
- CHECKBOX_OPERATORS,
105
- operatorOption,
106
- operatorsForColumn,
107
- defaultOperatorFor,
108
- operatorLabelFor,
109
- } from "./filter-operators";
110
- import {
111
- type FacetBucket,
112
- isBucketableColumn,
113
- buildBuckets,
114
- isInBucket,
115
- } from "./facet-buckets";
116
- import {
117
- getColumnBaseValue,
118
- isGroupRow,
119
- toolPanelHeaderLabel,
120
- formatSummaryNumeric,
121
- getColumnAlign,
122
- getPinnedCellValue,
123
- getColumnAccessorValue,
124
- columnDefMatchesId,
125
- } from "./cell-values";
126
-
127
- type HistoryStep = {
128
- rowId: string;
129
- columnId: string;
130
- field: string;
131
- before: unknown;
132
- after: unknown;
133
- };
134
-
135
- export function createEditing<
136
- TFeatures extends TableFeatures = TableFeatures,
137
- TData extends RowData = RowData,
138
- >(ctx: any) {
139
- /**
140
- * Resolve `columnDef.editable` for one row × column pair.
141
- *
142
- * - `undefined` / `true` → editable
143
- * - `false` → not editable (column-level lockdown, fastest path)
144
- * - function → call it with the cell's context and honour the
145
- * boolean it returns (cell-level lockdown - used for things like
146
- * "this field is owned by the server, this one isn't, by row")
147
- *
148
- * Called from every editing entry point: double-click, type-to-edit,
149
- * fill-handle drag, Delete-clear, clipboard paste. A central helper
150
- * keeps the cell-level callback signature consistent and saves a
151
- * lookup of CellContext at each site.
152
- */
153
- function isCellEditable(column: Column<TData>, row?: Row<TData>): boolean {
154
- const editable = column.columnDef.editable;
155
- if (editable === false) return false;
156
- if (typeof editable !== "function") return true;
157
- if (!row) return true;
158
- const cellCtx: CellContext<TData> = {
159
- cell: {
160
- id: `${row.id}_${column.id}`,
161
- row,
162
- column,
163
- getValue: () => getColumnBaseValue(row, column),
164
- getContext: () => cellCtx,
165
- },
166
- row,
167
- column,
168
- table: ctx.grid,
169
- getValue: () => getColumnBaseValue(row, column),
170
- };
171
- try {
172
- return editable(cellCtx) !== false;
173
- } catch {
174
- // A throwing predicate shouldn't crash the grid - log and treat
175
- // as not-editable so any error biases toward safety.
176
- return false;
177
- }
178
- }
179
-
180
- /** Variant that takes raw row + column indices for the rare callers
181
- * (fill-handle, paste, Delete) that already work in index-space. */
182
- function isCellEditableAt(rowIndex: number, colIndex: number): boolean {
183
- const row = ctx.allRows[rowIndex];
184
- const column = ctx.allColumns[colIndex];
185
- if (!column) return false;
186
- return isCellEditable(column, row);
187
- }
188
-
189
- function getRowColumnValue(row: Row<TData>, columnId: string) {
190
- const column = ctx.allColumns.find((entry: any) => entry.id === columnId);
191
- return column
192
- ? getColumnBaseValue(row, column)
193
- : row.getCellValueByColumnId(columnId);
194
- }
195
-
196
- function getCellDisplayValue(
197
- rowId: string,
198
- columnId: string,
199
- baseValue: unknown,
200
- ) {
201
- const key = getCellKey(rowId, columnId);
202
- return key in ctx.editedCellValues ? ctx.editedCellValues[key] : baseValue;
203
- }
204
-
205
- /** Start editing seeded with a typed character (Excel-style type-to-edit). */
206
- function startEditingWithChar(
207
- rowIndex: number,
208
- colIndex: number,
209
- char: string,
210
- ): boolean {
211
- if (!ctx.editingEnabled) return false;
212
- const row = ctx.allRows[rowIndex];
213
- const column = ctx.allColumns[colIndex];
214
- if (!row || !column || isGroupRow(row)) return false;
215
- if (!isCellEditable(column, row)) return false;
216
- const editorType = (column.columnDef.editorType ??
217
- "text") as CellEditorType;
218
- if (
219
- editorType === "checkbox" ||
220
- editorType === "date" ||
221
- editorType === "datetime" ||
222
- editorType === "list" ||
223
- editorType === "chips"
224
- ) {
225
- return false;
226
- }
227
- if (editorType === "number" && !/[0-9.+\-]/.test(char)) return false;
228
- ctx.editorSelectAll = false;
229
- ctx.editingCell = {
230
- rowId: row.id,
231
- columnId: column.id,
232
- editorType,
233
- value: char,
234
- };
235
- ctx.setActiveCell(rowIndex, colIndex);
236
- ctx.setSelection(rowIndex, colIndex);
237
- return true;
238
- }
239
-
240
- function saveEditingCell() {
241
- if (!ctx.editingCell) return;
242
- const row = ctx.allRows.find((entry: any) => entry.id === ctx.editingCell?.rowId);
243
- const column = ctx.allColumns.find(
244
- (entry: any) => entry.id === ctx.editingCell?.columnId,
245
- );
246
- const parsedValue = parseEditorValue(
247
- ctx.editingCell.editorType,
248
- ctx.editingCell.value,
249
- {
250
- multiple: column?.columnDef.editorMultiple === true,
251
- },
252
- );
253
- let oldValue: unknown = undefined;
254
- let finalValue: unknown = parsedValue;
255
- if (row?.original && column?.columnDef.field) {
256
- oldValue = (row.original as Record<string, unknown>)[
257
- column.columnDef.field
258
- ];
259
- // Per-column valueParser refines the type-coerced value before storing.
260
- const parser = (
261
- column.columnDef as { valueParser?: (p: unknown) => unknown }
262
- ).valueParser;
263
- if (parser) {
264
- finalValue = parser({
265
- newValue: parsedValue,
266
- oldValue,
267
- rawInput: ctx.editingCell.value,
268
- data: row.original,
269
- columnId: ctx.editingCell.columnId,
270
- });
271
- }
272
- (row.original as Record<string, unknown>)[column.columnDef.field] =
273
- finalValue;
274
- }
275
- const key = getCellKey(ctx.editingCell.rowId, ctx.editingCell.columnId);
276
- ctx.editedCellValues = {
277
- ...ctx.editedCellValues,
278
- [key]: finalValue,
279
- };
280
- ctx.grid.store.setState((prev: any) => ({ ...prev }));
281
- // Record into the history at the current pointer. Any forward
282
- // history (steps the user could have redone) is truncated - this
283
- // is the standard "edit invalidates redo" rule.
284
- if (oldValue !== finalValue && row?.original && column?.columnDef.field) {
285
- const step: HistoryStep = {
286
- rowId: ctx.editingCell.rowId,
287
- columnId: ctx.editingCell.columnId,
288
- field: column.columnDef.field as string,
289
- before: oldValue,
290
- after: finalValue,
291
- }
292
- const truncated = ctx.history.slice(0, ctx.historyPtr + 1)
293
- truncated.push(step)
294
- // Cap the buffer at UNDO_LIMIT; drop the OLDEST entries so the
295
- // pointer stays valid relative to the newest steps.
296
- if (truncated.length > ctx.UNDO_LIMIT) {
297
- const drop = truncated.length - ctx.UNDO_LIMIT
298
- ctx.history = truncated.slice(drop)
299
- ctx.historyPtr = ctx.history.length - 1
300
- } else {
301
- ctx.history = truncated
302
- ctx.historyPtr = ctx.history.length - 1
303
- }
304
- ctx.historyVersion += 1
305
- }
306
- // Notify the consumer AFTER the row has been updated so any callback-
307
- // driven recompute (cascade totals, server save, undo stack) sees the
308
- // post-write state. `rowIndex` matches the position in `props.data`.
309
- if (ctx.props.onCellValueChange && row?.original && column) {
310
- const rowIndex = ctx.internalData.indexOf(row.original as TData);
311
- ctx.props.onCellValueChange({
312
- rowIndex,
313
- columnId: column.id,
314
- oldValue,
315
- newValue: finalValue,
316
- row: row.original as TData,
317
- });
318
- }
319
- ctx.editingCell = null;
320
- }
321
-
322
- /** Apply an undo / redo step directly to the underlying row, bypassing
323
- * the editor pipeline so we don't accidentally re-push to the stack. */
324
- function applyHistoryStep(step: HistoryStep, direction: 'undo' | 'redo') {
325
- const row = ctx.allRows.find((r: any) => r.id === step.rowId)
326
- const col = ctx.allColumns.find((c: any) => c.id === step.columnId)
327
- if (!row?.original || !col) return
328
- const value = direction === 'undo' ? step.before : step.after
329
- ;(row.original as Record<string, unknown>)[step.field] = value
330
- const key = getCellKey(step.rowId, step.columnId)
331
- ctx.editedCellValues = { ...ctx.editedCellValues, [key]: value }
332
- ctx.grid.store.setState((prev: any) => ({ ...prev }))
333
- if (ctx.props.onCellValueChange) {
334
- const rowIndex = ctx.internalData.indexOf(row.original as TData)
335
- ctx.props.onCellValueChange({
336
- rowIndex,
337
- columnId: step.columnId,
338
- oldValue: direction === 'undo' ? step.after : step.before,
339
- newValue: value,
340
- row: row.original as TData,
341
- })
342
- }
343
- }
344
-
345
- function updateEditingCellValue(value: unknown) {
346
- ctx.editingCell = ctx.editingCell ? { ...ctx.editingCell, value } : ctx.editingCell;
347
- }
348
-
349
- function onEditorKeyDown(event: KeyboardEvent) {
350
- event.stopPropagation();
351
- if (event.key === "Enter") {
352
- event.preventDefault();
353
- saveEditingCell();
354
- ctx.gridRootEl?.focus({ preventScroll: true });
355
- } else if (event.key === "Escape") {
356
- event.preventDefault();
357
- ctx.editingCell = null;
358
- ctx.gridRootEl?.focus({ preventScroll: true });
359
- }
360
- }
361
-
362
- function focusOnMount(node: HTMLInputElement | HTMLTextAreaElement) {
363
- const selectAll = ctx.editorSelectAll;
364
- requestAnimationFrame(() => {
365
- node.focus({ preventScroll: true });
366
- try {
367
- if (selectAll) {
368
- node.select();
369
- } else {
370
- const end = node.value.length;
371
- node.setSelectionRange(end, end);
372
- }
373
- } catch {
374
- /* date/number inputs may not support text selection */
375
- }
376
- });
377
- }
378
-
379
- function onCellDoubleClick(rowIndex: number, colIndex: number) {
380
- if (!ctx.editingEnabled) return;
381
- const row = ctx.allRows[rowIndex];
382
- const column = ctx.allColumns[colIndex];
383
- if (!row || !column) return;
384
- if (isGroupRow(row)) return;
385
- // Full-row editing: put the whole row into edit instead of one cell.
386
- if (ctx.props.fullRowEditing) {
387
- if (ctx.fullRowEdit?.rowId === row.id) return;
388
- startFullRowEdit(rowIndex);
389
- return;
390
- }
391
- if (!isCellEditable(column, row)) return;
392
- if (ctx.editingCell?.rowId === row.id && ctx.editingCell?.columnId === column.id)
393
- return;
394
- const editorType = (column.columnDef.editorType ??
395
- "text") as CellEditorType;
396
- ctx.editorSelectAll = true;
397
- let initialValue = getCellDisplayValue(
398
- row.id,
399
- column.id,
400
- row.getCellValueByColumnId(column.id),
401
- );
402
- if (editorType === "list" || editorType === "chips") {
403
- if (column.columnDef.editorMultiple) {
404
- // Seed with an array so the editor can mutate slot-by-slot.
405
- initialValue = toValueArray(initialValue);
406
- } else if (Array.isArray(initialValue)) {
407
- initialValue = initialValue[0] ?? "";
408
- }
409
- }
410
- ctx.editingCell = {
411
- rowId: row.id,
412
- columnId: column.id,
413
- editorType,
414
- value: initialValue,
415
- };
416
- ctx.setActiveCell(rowIndex, colIndex);
417
- ctx.setSelection(rowIndex, colIndex);
418
- }
419
-
420
- async function pasteFromClipboard() {
421
- // Preferred path: the async Clipboard API. Requires a secure context
422
- // (HTTPS or localhost) AND read permission; it also works on Firefox,
423
- // where the native `paste` event does NOT fire on a non-editable element.
424
- // On plain HTTP (a XAMPP/Apache LAN host) `navigator.clipboard` is
425
- // undefined - there the Ctrl+V keydown handler skips preventDefault and
426
- // lets the browser deliver a native `paste` event to `onGridPaste`.
427
- if (!navigator.clipboard?.readText) return;
428
- let text: string;
429
- try {
430
- text = await navigator.clipboard.readText();
431
- } catch {
432
- return;
433
- }
434
- applyPastedText(text);
435
- }
436
-
437
- /**
438
- * Native `paste` ClipboardEvent fallback (insecure-context path). A real
439
- * Ctrl/Cmd+V on the focused grid root fires this with `clipboardData`
440
- * readable even over plain HTTP and with no permission prompt. Wired on the
441
- * grid root in SvGrid.svelte; the keydown handler lets the gesture through
442
- * (no preventDefault) whenever the async API is unavailable.
443
- */
444
- function onGridPaste(event: ClipboardEvent) {
445
- // A cell is being edited: the focused editor input handles its own paste
446
- // natively. Never hijack it for a range paste - doing so (on Firefox /
447
- // insecure contexts, where the async Clipboard API is unavailable) would
448
- // preventDefault the editor's paste and write to the data cell instead,
449
- // so the edit "wouldn't update".
450
- if (ctx.editingCell) return;
451
- // When the async API is available the keydown handler already pasted via
452
- // pasteFromClipboard(); ignore the (suppressed) native event so we don't
453
- // paste twice.
454
- if (typeof navigator.clipboard?.readText === "function") return;
455
- const text = event.clipboardData?.getData("text/plain") ?? "";
456
- if (!text) return;
457
- event.preventDefault();
458
- applyPastedText(text);
459
- }
460
-
461
- function applyPastedText(text: string) {
462
- const anchor = ctx.selectionRange.anchor ?? ctx.grid.getState().activeCell;
463
- if (!anchor) return;
464
- const focus = ctx.selectionRange.focus ?? anchor;
465
- const startRow = Math.min(anchor.rowIndex, focus.rowIndex);
466
- const startCol = Math.min(anchor.colIndex, focus.colIndex);
467
- const endRow = Math.max(anchor.rowIndex, focus.rowIndex);
468
- const endCol = Math.max(anchor.colIndex, focus.colIndex);
469
- const lines = text.replace(/\r\n/g, "\n").split("\n");
470
- if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
471
- if (!lines.length) return;
472
-
473
- // Excel/Sheets behaviour: when the clipboard holds a single cell and
474
- // the selection is a range, fill the entire range with that value.
475
- // For larger clipboards (multi-row/col TSV), paste at the top-left
476
- // corner and let the clipboard determine the span (the original
477
- // behaviour).
478
- const clipboardIsSingleCell =
479
- lines.length === 1 && (lines[0]?.split("\t").length ?? 0) === 1;
480
- const selectionIsRange = startRow !== endRow || startCol !== endCol;
481
- const fillRange = clipboardIsSingleCell && selectionIsRange;
482
-
483
- const rowSpan = fillRange ? endRow - startRow + 1 : lines.length;
484
- const colSpan = fillRange
485
- ? endCol - startCol + 1
486
- : Math.max(...lines.map((l) => l.split("\t").length));
487
-
488
- const next = ctx.internalData.slice() as Array<TData>;
489
- for (let i = 0; i < rowSpan; i += 1) {
490
- const targetRowIndex = startRow + i;
491
- const row = ctx.allRows[targetRowIndex];
492
- if (!row || isGroupRow(row)) continue;
493
- // Map the visible row back to its index in the data array via row.id (default = String(index)).
494
- const dataIndex = Number(row.id);
495
- if (
496
- !Number.isInteger(dataIndex) ||
497
- dataIndex < 0 ||
498
- dataIndex >= next.length
499
- )
500
- continue;
501
- const originalRow = next[dataIndex];
502
- if (!originalRow) continue;
503
- const sourceCells = fillRange
504
- ? null
505
- : lines[i]?.split("\t") ?? [];
506
- const updated: Record<string, unknown> = {
507
- ...(originalRow as Record<string, unknown>),
508
- };
509
- for (let j = 0; j < colSpan; j += 1) {
510
- const column = ctx.allColumns[startCol + j];
511
- if (!column?.columnDef.field) continue;
512
- if (!isCellEditableAt(targetRowIndex, startCol + j)) continue;
513
- const editorType = (column.columnDef.editorType ??
514
- "text") as CellEditorType;
515
- const raw = fillRange ? lines[0]! : sourceCells?.[j] ?? "";
516
- updated[column.columnDef.field] = parseEditorValue(editorType, raw);
517
- }
518
- next[dataIndex] = updated as TData;
519
- }
520
- ctx.internalData = next;
521
- ctx.grid.store.setState((prev: any) => ({ ...prev }));
522
- }
523
-
524
- /** Programmatically begin editing a cell (mirrors a double-click). */
525
- function startEditing(rowIndex: number, columnId: string): boolean {
526
- if (!ctx.editingEnabled) return false;
527
- const row = ctx.allRows[rowIndex];
528
- if (!row || isGroupRow(row)) return false;
529
- const colIndex = ctx.allColumns.findIndex((c: any) => c.id === columnId);
530
- if (colIndex < 0) return false;
531
- const column = ctx.allColumns[colIndex];
532
- if (!isCellEditable(column, row)) return false;
533
- if (
534
- ctx.editingCell?.rowId === row.id &&
535
- ctx.editingCell?.columnId === columnId
536
- )
537
- return true;
538
- onCellDoubleClick(rowIndex, colIndex);
539
- return (
540
- ctx.editingCell?.rowId === row.id &&
541
- ctx.editingCell?.columnId === columnId
542
- );
543
- }
544
-
545
- /** Commit (default) or cancel the active edit, if any. */
546
- function stopEditing(cancel = false): boolean {
547
- if (!ctx.editingCell) return false;
548
- if (cancel) {
549
- ctx.editingCell = null;
550
- } else {
551
- saveEditingCell();
552
- }
553
- return true;
554
- }
555
-
556
- // ---- Full-row editing -------------------------------------------------
557
- /** Put the whole row into edit mode, seeding a draft per editable column. */
558
- function startFullRowEdit(rowIndex: number): boolean {
559
- if (!ctx.editingEnabled || !ctx.props.fullRowEditing) return false;
560
- const row = ctx.allRows[rowIndex];
561
- if (!row || isGroupRow(row)) return false;
562
- if (ctx.fullRowEdit && ctx.fullRowEdit.rowId !== row.id) commitFullRowEdit();
563
- ctx.editingCell = null; // never both at once
564
- const draft: Record<string, unknown> = {};
565
- for (const column of ctx.allColumns) {
566
- if (!column.columnDef.field) continue;
567
- if (!isCellEditable(column, row)) continue;
568
- draft[column.id] = getCellDisplayValue(
569
- row.id,
570
- column.id,
571
- row.getCellValueByColumnId(column.id),
572
- );
573
- }
574
- ctx.fullRowEdit = { rowId: row.id, draft };
575
- ctx.setActiveCell(rowIndex, Math.max(0, ctx.allColumns.findIndex((c: any) => c.id in draft)));
576
- return true;
577
- }
578
-
579
- /** Stage one column's draft value during full-row editing. */
580
- function setFullRowDraft(columnId: string, value: unknown): void {
581
- const fr = ctx.fullRowEdit;
582
- if (!fr) return;
583
- ctx.fullRowEdit = { rowId: fr.rowId, draft: { ...fr.draft, [columnId]: value } };
584
- }
585
-
586
- /** Commit every drafted column of the full-row edit in one data update. */
587
- function commitFullRowEdit(): void {
588
- const fr = ctx.fullRowEdit;
589
- if (!fr) return;
590
- const row = ctx.allRows.find((r: any) => r.id === fr.rowId);
591
- if (!row?.original) {
592
- ctx.fullRowEdit = null;
593
- return;
594
- }
595
- const changed: Array<{ columnId: string; field: string; before: unknown; after: unknown }> = [];
596
- for (const column of ctx.allColumns) {
597
- if (!(column.id in fr.draft)) continue;
598
- const field = column.columnDef.field as string | undefined;
599
- if (!field) continue;
600
- const editorType = (column.columnDef.editorType ?? "text") as CellEditorType;
601
- const parsed = parseEditorValue(editorType, fr.draft[column.id], {
602
- multiple: column.columnDef.editorMultiple === true,
603
- });
604
- const oldValue = (row.original as Record<string, unknown>)[field];
605
- const parser = (column.columnDef as { valueParser?: (p: unknown) => unknown }).valueParser;
606
- const finalValue = parser
607
- ? parser({
608
- newValue: parsed,
609
- oldValue,
610
- rawInput: String(fr.draft[column.id] ?? ""),
611
- data: row.original,
612
- columnId: column.id,
613
- })
614
- : parsed;
615
- if (oldValue !== finalValue) {
616
- (row.original as Record<string, unknown>)[field] = finalValue;
617
- const key = getCellKey(fr.rowId, column.id);
618
- ctx.editedCellValues = { ...ctx.editedCellValues, [key]: finalValue };
619
- changed.push({ columnId: column.id, field, before: oldValue, after: finalValue });
620
- }
621
- }
622
- // Record the whole-row change as consecutive history steps.
623
- if (changed.length) {
624
- let hist = ctx.history.slice(0, ctx.historyPtr + 1);
625
- for (const c of changed) {
626
- hist.push({ rowId: fr.rowId, columnId: c.columnId, field: c.field, before: c.before, after: c.after });
627
- }
628
- if (hist.length > ctx.UNDO_LIMIT) hist = hist.slice(hist.length - ctx.UNDO_LIMIT);
629
- ctx.history = hist;
630
- ctx.historyPtr = ctx.history.length - 1;
631
- ctx.historyVersion += 1;
632
- }
633
- ctx.grid.store.setState((prev: any) => ({ ...prev }));
634
- if (ctx.props.onCellValueChange && changed.length) {
635
- const rowIndex = ctx.internalData.indexOf(row.original as TData);
636
- for (const c of changed) {
637
- ctx.props.onCellValueChange({
638
- rowIndex,
639
- columnId: c.columnId,
640
- oldValue: c.before,
641
- newValue: c.after,
642
- row: row.original as TData,
643
- });
644
- }
645
- }
646
- ctx.fullRowEdit = null;
647
- }
648
-
649
- /** Discard the full-row edit. */
650
- function cancelFullRowEdit(): void {
651
- ctx.fullRowEdit = null;
652
- }
653
-
654
- return {
655
- isCellEditable,
656
- isCellEditableAt,
657
- getRowColumnValue,
658
- getCellDisplayValue,
659
- startEditingWithChar,
660
- startEditing,
661
- stopEditing,
662
- startFullRowEdit,
663
- setFullRowDraft,
664
- commitFullRowEdit,
665
- cancelFullRowEdit,
666
- saveEditingCell,
667
- applyHistoryStep,
668
- updateEditingCellValue,
669
- onEditorKeyDown,
670
- focusOnMount,
671
- onCellDoubleClick,
672
- pasteFromClipboard,
673
- onGridPaste,
674
- };
675
- }
1
+ // editing handlers extracted from the controller. Imperative event handlers
2
+ // reading/writing controller state via the `ctx` handle; the reactive core
3
+ // ($state/$derived/$effect) stays in the controller.
4
+ import {
5
+ applyExcelFilter,
6
+ normalizeForFilter,
7
+ createColumnVirtualizer,
8
+ createCoreRowModel,
9
+ createExpandedRowModel,
10
+ createFilteredRowModel,
11
+ createGroupedRowModel,
12
+ createPaginatedRowModel,
13
+ createSvelteVirtualizer,
14
+ createSortedRowModel,
15
+ createSvGrid,
16
+ filterFns,
17
+ getGridCellA11yProps,
18
+ getGridCellDomId,
19
+ getGridHeaderA11yProps,
20
+ getGridRootA11yProps,
21
+ getGridRowA11yProps,
22
+ parseEditorValue,
23
+ normalizeEditorOptions,
24
+ sortFns,
25
+ tableFeatures,
26
+ rowSortingFeature,
27
+ columnFilteringFeature,
28
+ columnGroupingFeature,
29
+ type CellContext,
30
+ type EditorContext,
31
+ type CellEditorOption,
32
+ type CellEditorType,
33
+ type CellFormatter,
34
+ type CellFormatConfig,
35
+ type Column,
36
+ type ColumnDef,
37
+ type Row,
38
+ type RowData,
39
+ type SvGridApi,
40
+ type TableFeatures,
41
+ } from "./index";
42
+ import "./sv-grid-scrollbar";
43
+ import type { Snippet } from "svelte";
44
+ import { getKeyboardIntent, getNextActiveCell } from "./keyboard";
45
+ import {
46
+ formatNumericWithConfig,
47
+ getDateFormatter,
48
+ resolveDatePattern,
49
+ } from "./cell-formatting";
50
+ import {
51
+ RenderSnippetConfig,
52
+ RenderComponentConfig,
53
+ } from "./render-component";
54
+ import { buildFillPattern } from "./fill-patterns";
55
+ import { buildSparkline, toSparklineValues } from "./sparkline";
56
+ import {
57
+ resolveCellFormat,
58
+ computeColumnStat,
59
+ formatsNeedingStats,
60
+ type ColumnStat,
61
+ type ResolvedCellFormat,
62
+ } from "./conditional-formatting";
63
+ import SvGridDropdown from "./SvGridDropdown.svelte";
64
+ import type {
65
+ Props,
66
+ SelectionPoint,
67
+ SelectionRange,
68
+ CellEditState,
69
+ FilterOperator,
70
+ FilterOption,
71
+ MenuPosition,
72
+ } from "./SvGrid.types";
73
+ import {
74
+ cfTextStyle,
75
+ fmtStat,
76
+ getCellKey,
77
+ resolveClassList,
78
+ toDateInputValue,
79
+ toDateTimeLocalInputValue,
80
+ getEditableInputValue,
81
+ getEditorInputType,
82
+ toValueArray,
83
+ getOptionLabel,
84
+ getOptionColor,
85
+ colorfulChipStyle,
86
+ getEditorClass,
87
+ asDate,
88
+ clampMenuX,
89
+ cssEscape,
90
+ rawToNumber,
91
+ formatFacetNumber,
92
+ formatFacetDate,
93
+ } from "./SvGrid.helpers";
94
+ import { createSelection } from "./selection";
95
+ import { createColumns } from "./columns";
96
+ import { createGridApi } from "./build-api";
97
+ import { createClipboard } from "./clipboard";
98
+ import {
99
+ filterOperatorOptions,
100
+ fallbackOperatorOption,
101
+ TEXT_OPERATORS,
102
+ NUMBER_OPERATORS,
103
+ DATE_OPERATORS,
104
+ CHECKBOX_OPERATORS,
105
+ operatorOption,
106
+ operatorsForColumn,
107
+ defaultOperatorFor,
108
+ operatorLabelFor,
109
+ } from "./filter-operators";
110
+ import {
111
+ type FacetBucket,
112
+ isBucketableColumn,
113
+ buildBuckets,
114
+ isInBucket,
115
+ } from "./facet-buckets";
116
+ import {
117
+ getColumnBaseValue,
118
+ isGroupRow,
119
+ toolPanelHeaderLabel,
120
+ formatSummaryNumeric,
121
+ getColumnAlign,
122
+ getPinnedCellValue,
123
+ getColumnAccessorValue,
124
+ columnDefMatchesId,
125
+ } from "./cell-values";
126
+
127
+ type HistoryStep = {
128
+ rowId: string;
129
+ columnId: string;
130
+ field: string;
131
+ before: unknown;
132
+ after: unknown;
133
+ };
134
+
135
+ export function createEditing<
136
+ TFeatures extends TableFeatures = TableFeatures,
137
+ TData extends RowData = RowData,
138
+ >(ctx: any) {
139
+ /**
140
+ * Resolve `columnDef.editable` for one row × column pair.
141
+ *
142
+ * - `undefined` / `true` → editable
143
+ * - `false` → not editable (column-level lockdown, fastest path)
144
+ * - function → call it with the cell's context and honour the
145
+ * boolean it returns (cell-level lockdown - used for things like
146
+ * "this field is owned by the server, this one isn't, by row")
147
+ *
148
+ * Called from every editing entry point: double-click, type-to-edit,
149
+ * fill-handle drag, Delete-clear, clipboard paste. A central helper
150
+ * keeps the cell-level callback signature consistent and saves a
151
+ * lookup of CellContext at each site.
152
+ */
153
+ function isCellEditable(column: Column<TData>, row?: Row<TData>): boolean {
154
+ const editable = column.columnDef.editable;
155
+ if (editable === false) return false;
156
+ if (typeof editable !== "function") return true;
157
+ if (!row) return true;
158
+ const cellCtx: CellContext<TData> = {
159
+ cell: {
160
+ id: `${row.id}_${column.id}`,
161
+ row,
162
+ column,
163
+ getValue: () => getColumnBaseValue(row, column),
164
+ getContext: () => cellCtx,
165
+ },
166
+ row,
167
+ column,
168
+ table: ctx.grid,
169
+ getValue: () => getColumnBaseValue(row, column),
170
+ };
171
+ try {
172
+ return editable(cellCtx) !== false;
173
+ } catch {
174
+ // A throwing predicate shouldn't crash the grid - log and treat
175
+ // as not-editable so any error biases toward safety.
176
+ return false;
177
+ }
178
+ }
179
+
180
+ /** Variant that takes raw row + column indices for the rare callers
181
+ * (fill-handle, paste, Delete) that already work in index-space. */
182
+ function isCellEditableAt(rowIndex: number, colIndex: number): boolean {
183
+ const row = ctx.allRows[rowIndex];
184
+ const column = ctx.allColumns[colIndex];
185
+ if (!column) return false;
186
+ return isCellEditable(column, row);
187
+ }
188
+
189
+ function getRowColumnValue(row: Row<TData>, columnId: string) {
190
+ const column = ctx.allColumns.find((entry: any) => entry.id === columnId);
191
+ return column
192
+ ? getColumnBaseValue(row, column)
193
+ : row.getCellValueByColumnId(columnId);
194
+ }
195
+
196
+ function getCellDisplayValue(
197
+ rowId: string,
198
+ columnId: string,
199
+ baseValue: unknown,
200
+ ) {
201
+ const key = getCellKey(rowId, columnId);
202
+ return key in ctx.editedCellValues ? ctx.editedCellValues[key] : baseValue;
203
+ }
204
+
205
+ /** Start editing seeded with a typed character (Excel-style type-to-edit). */
206
+ function startEditingWithChar(
207
+ rowIndex: number,
208
+ colIndex: number,
209
+ char: string,
210
+ ): boolean {
211
+ if (!ctx.editingEnabled) return false;
212
+ const row = ctx.allRows[rowIndex];
213
+ const column = ctx.allColumns[colIndex];
214
+ if (!row || !column || isGroupRow(row)) return false;
215
+ if (!isCellEditable(column, row)) return false;
216
+ const editorType = (column.columnDef.editorType ??
217
+ "text") as CellEditorType;
218
+ if (
219
+ editorType === "checkbox" ||
220
+ editorType === "date" ||
221
+ editorType === "datetime" ||
222
+ editorType === "list" ||
223
+ editorType === "chips"
224
+ ) {
225
+ return false;
226
+ }
227
+ if (editorType === "number" && !/[0-9.+\-]/.test(char)) return false;
228
+ ctx.editorSelectAll = false;
229
+ ctx.editingCell = {
230
+ rowId: row.id,
231
+ columnId: column.id,
232
+ editorType,
233
+ value: char,
234
+ rowRef: row.original,
235
+ };
236
+ ctx.setActiveCell(rowIndex, colIndex);
237
+ ctx.setSelection(rowIndex, colIndex);
238
+ return true;
239
+ }
240
+
241
+ function saveEditingCell() {
242
+ if (!ctx.editingCell) return;
243
+ const editing = ctx.editingCell;
244
+ // Resolve the row this edit belongs to. `allRows` is only the current page,
245
+ // so fall back to the full filtered model, then to the data object captured
246
+ // when the edit started. Without that last hop an edit is silently dropped
247
+ // when a filter typed mid-edit hides the row from both models (#49).
248
+ const row =
249
+ ctx.allRows.find((entry: any) => entry.id === editing.rowId) ??
250
+ ctx.allRowsBeforePagination.find((entry: any) => entry.id === editing.rowId);
251
+ const rowData = (row?.original ?? editing.rowRef) as
252
+ | Record<string, unknown>
253
+ | undefined;
254
+ const column = ctx.allColumns.find(
255
+ (entry: any) => entry.id === ctx.editingCell?.columnId,
256
+ );
257
+ const parsedValue = parseEditorValue(
258
+ ctx.editingCell.editorType,
259
+ ctx.editingCell.value,
260
+ {
261
+ multiple: column?.columnDef.editorMultiple === true,
262
+ },
263
+ );
264
+ let oldValue: unknown = undefined;
265
+ let finalValue: unknown = parsedValue;
266
+ if (rowData && column?.columnDef.field) {
267
+ oldValue = rowData[column.columnDef.field];
268
+ // Per-column valueParser refines the type-coerced value before storing.
269
+ const parser = (
270
+ column.columnDef as { valueParser?: (p: unknown) => unknown }
271
+ ).valueParser;
272
+ if (parser) {
273
+ finalValue = parser({
274
+ newValue: parsedValue,
275
+ oldValue,
276
+ rawInput: ctx.editingCell.value,
277
+ data: rowData,
278
+ columnId: ctx.editingCell.columnId,
279
+ });
280
+ }
281
+ rowData[column.columnDef.field] = finalValue;
282
+ }
283
+ const key = getCellKey(ctx.editingCell.rowId, ctx.editingCell.columnId);
284
+ ctx.editedCellValues = {
285
+ ...ctx.editedCellValues,
286
+ [key]: finalValue,
287
+ };
288
+ ctx.grid.store.setState((prev: any) => ({ ...prev }));
289
+ // Record into the history at the current pointer. Any forward
290
+ // history (steps the user could have redone) is truncated - this
291
+ // is the standard "edit invalidates redo" rule.
292
+ if (oldValue !== finalValue && rowData && column?.columnDef.field) {
293
+ const step: HistoryStep = {
294
+ rowId: ctx.editingCell.rowId,
295
+ columnId: ctx.editingCell.columnId,
296
+ field: column.columnDef.field as string,
297
+ before: oldValue,
298
+ after: finalValue,
299
+ }
300
+ const truncated = ctx.history.slice(0, ctx.historyPtr + 1)
301
+ truncated.push(step)
302
+ // Cap the buffer at UNDO_LIMIT; drop the OLDEST entries so the
303
+ // pointer stays valid relative to the newest steps.
304
+ if (truncated.length > ctx.UNDO_LIMIT) {
305
+ const drop = truncated.length - ctx.UNDO_LIMIT
306
+ ctx.history = truncated.slice(drop)
307
+ ctx.historyPtr = ctx.history.length - 1
308
+ } else {
309
+ ctx.history = truncated
310
+ ctx.historyPtr = ctx.history.length - 1
311
+ }
312
+ ctx.historyVersion += 1
313
+ }
314
+ // Notify the consumer AFTER the row has been updated so any callback-
315
+ // driven recompute (cascade totals, server save, undo stack) sees the
316
+ // post-write state. `rowIndex` matches the position in `props.data`.
317
+ if (ctx.props.onCellValueChange && rowData && column) {
318
+ const rowIndex = ctx.internalData.indexOf(rowData as TData);
319
+ ctx.props.onCellValueChange({
320
+ rowIndex,
321
+ columnId: column.id,
322
+ oldValue,
323
+ newValue: finalValue,
324
+ row: rowData as TData,
325
+ });
326
+ }
327
+ ctx.editingCell = null;
328
+ }
329
+
330
+ /** Apply an undo / redo step directly to the underlying row, bypassing
331
+ * the editor pipeline so we don't accidentally re-push to the stack. */
332
+ function applyHistoryStep(step: HistoryStep, direction: 'undo' | 'redo') {
333
+ const row = ctx.allRows.find((r: any) => r.id === step.rowId)
334
+ const col = ctx.allColumns.find((c: any) => c.id === step.columnId)
335
+ if (!row?.original || !col) return
336
+ const value = direction === 'undo' ? step.before : step.after
337
+ ;(row.original as Record<string, unknown>)[step.field] = value
338
+ const key = getCellKey(step.rowId, step.columnId)
339
+ ctx.editedCellValues = { ...ctx.editedCellValues, [key]: value }
340
+ ctx.grid.store.setState((prev: any) => ({ ...prev }))
341
+ if (ctx.props.onCellValueChange) {
342
+ const rowIndex = ctx.internalData.indexOf(row.original as TData)
343
+ ctx.props.onCellValueChange({
344
+ rowIndex,
345
+ columnId: step.columnId,
346
+ oldValue: direction === 'undo' ? step.after : step.before,
347
+ newValue: value,
348
+ row: row.original as TData,
349
+ })
350
+ }
351
+ }
352
+
353
+ function updateEditingCellValue(value: unknown) {
354
+ ctx.editingCell = ctx.editingCell ? { ...ctx.editingCell, value } : ctx.editingCell;
355
+ }
356
+
357
+ /**
358
+ * Commit the open editor and move the active cell one column along, wrapping
359
+ * at row boundaries the way Excel does. Editors `stopPropagation()` every key
360
+ * so the grid's own Tab handler never sees this one - without the explicit
361
+ * move, Tab committed the edit and then let the browser walk focus out of the
362
+ * grid entirely (#48). Shared by every editor type, including the textarea.
363
+ */
364
+ function commitAndMoveByTab(shiftKey: boolean) {
365
+ const active = ctx.activeCell;
366
+ saveEditingCell();
367
+ ctx.gridRootEl?.focus({ preventScroll: true });
368
+ if (!active) return;
369
+ const next = getNextActiveCell(active, shiftKey ? "tabPrev" : "tabNext", {
370
+ maxRow: ctx.allRows.length - 1,
371
+ maxCol: ctx.allColumns.length - 1,
372
+ });
373
+ ctx.setActiveCell(next.rowIndex, next.colIndex);
374
+ ctx.setSelection(next.rowIndex, next.colIndex);
375
+ ctx.scrollActiveCellIntoView(next.rowIndex, next.colIndex);
376
+ }
377
+
378
+ function onEditorKeyDown(event: KeyboardEvent) {
379
+ event.stopPropagation();
380
+ if (event.key === "Enter") {
381
+ event.preventDefault();
382
+ saveEditingCell();
383
+ ctx.gridRootEl?.focus({ preventScroll: true });
384
+ } else if (event.key === "Tab") {
385
+ event.preventDefault();
386
+ commitAndMoveByTab(event.shiftKey);
387
+ } else if (event.key === "Escape") {
388
+ event.preventDefault();
389
+ ctx.editingCell = null;
390
+ ctx.gridRootEl?.focus({ preventScroll: true });
391
+ }
392
+ }
393
+
394
+ function focusOnMount(node: HTMLInputElement | HTMLTextAreaElement) {
395
+ const selectAll = ctx.editorSelectAll;
396
+ requestAnimationFrame(() => {
397
+ node.focus({ preventScroll: true });
398
+ try {
399
+ if (selectAll) {
400
+ node.select();
401
+ } else {
402
+ const end = node.value.length;
403
+ node.setSelectionRange(end, end);
404
+ }
405
+ } catch {
406
+ /* date/number inputs may not support text selection */
407
+ }
408
+ });
409
+ }
410
+
411
+ function onCellDoubleClick(rowIndex: number, colIndex: number) {
412
+ if (!ctx.editingEnabled) return;
413
+ const row = ctx.allRows[rowIndex];
414
+ const column = ctx.allColumns[colIndex];
415
+ if (!row || !column) return;
416
+ if (isGroupRow(row)) return;
417
+ // Full-row editing: put the whole row into edit instead of one cell.
418
+ if (ctx.props.fullRowEditing) {
419
+ if (ctx.fullRowEdit?.rowId === row.id) return;
420
+ startFullRowEdit(rowIndex);
421
+ return;
422
+ }
423
+ if (!isCellEditable(column, row)) return;
424
+ if (ctx.editingCell?.rowId === row.id && ctx.editingCell?.columnId === column.id)
425
+ return;
426
+ const editorType = (column.columnDef.editorType ??
427
+ "text") as CellEditorType;
428
+ ctx.editorSelectAll = true;
429
+ let initialValue = getCellDisplayValue(
430
+ row.id,
431
+ column.id,
432
+ row.getCellValueByColumnId(column.id),
433
+ );
434
+ if (editorType === "list" || editorType === "chips") {
435
+ if (column.columnDef.editorMultiple) {
436
+ // Seed with an array so the editor can mutate slot-by-slot.
437
+ initialValue = toValueArray(initialValue);
438
+ } else if (Array.isArray(initialValue)) {
439
+ initialValue = initialValue[0] ?? "";
440
+ }
441
+ }
442
+ ctx.editingCell = {
443
+ rowId: row.id,
444
+ columnId: column.id,
445
+ editorType,
446
+ value: initialValue,
447
+ rowRef: row.original,
448
+ };
449
+ ctx.setActiveCell(rowIndex, colIndex);
450
+ ctx.setSelection(rowIndex, colIndex);
451
+ }
452
+
453
+ async function pasteFromClipboard() {
454
+ // Preferred path: the async Clipboard API. Requires a secure context
455
+ // (HTTPS or localhost) AND read permission; it also works on Firefox,
456
+ // where the native `paste` event does NOT fire on a non-editable element.
457
+ // On plain HTTP (a XAMPP/Apache LAN host) `navigator.clipboard` is
458
+ // undefined - there the Ctrl+V keydown handler skips preventDefault and
459
+ // lets the browser deliver a native `paste` event to `onGridPaste`.
460
+ if (!navigator.clipboard?.readText) return;
461
+ let text: string;
462
+ try {
463
+ text = await navigator.clipboard.readText();
464
+ } catch {
465
+ return;
466
+ }
467
+ applyPastedText(text);
468
+ }
469
+
470
+ /**
471
+ * Native `paste` ClipboardEvent fallback (insecure-context path). A real
472
+ * Ctrl/Cmd+V on the focused grid root fires this with `clipboardData`
473
+ * readable even over plain HTTP and with no permission prompt. Wired on the
474
+ * grid root in SvGrid.svelte; the keydown handler lets the gesture through
475
+ * (no preventDefault) whenever the async API is unavailable.
476
+ */
477
+ function onGridPaste(event: ClipboardEvent) {
478
+ // A cell is being edited: the focused editor input handles its own paste
479
+ // natively. Never hijack it for a range paste - doing so (on Firefox /
480
+ // insecure contexts, where the async Clipboard API is unavailable) would
481
+ // preventDefault the editor's paste and write to the data cell instead,
482
+ // so the edit "wouldn't update".
483
+ if (ctx.editingCell) return;
484
+ // When the async API is available the keydown handler already pasted via
485
+ // pasteFromClipboard(); ignore the (suppressed) native event so we don't
486
+ // paste twice.
487
+ if (typeof navigator.clipboard?.readText === "function") return;
488
+ const text = event.clipboardData?.getData("text/plain") ?? "";
489
+ if (!text) return;
490
+ event.preventDefault();
491
+ applyPastedText(text);
492
+ }
493
+
494
+ function applyPastedText(text: string) {
495
+ const anchor = ctx.selectionRange.anchor ?? ctx.grid.getState().activeCell;
496
+ if (!anchor) return;
497
+ const focus = ctx.selectionRange.focus ?? anchor;
498
+ const startRow = Math.min(anchor.rowIndex, focus.rowIndex);
499
+ const startCol = Math.min(anchor.colIndex, focus.colIndex);
500
+ const endRow = Math.max(anchor.rowIndex, focus.rowIndex);
501
+ const endCol = Math.max(anchor.colIndex, focus.colIndex);
502
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
503
+ if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
504
+ if (!lines.length) return;
505
+
506
+ // Excel/Sheets behaviour: when the clipboard holds a single cell and
507
+ // the selection is a range, fill the entire range with that value.
508
+ // For larger clipboards (multi-row/col TSV), paste at the top-left
509
+ // corner and let the clipboard determine the span (the original
510
+ // behaviour).
511
+ const clipboardIsSingleCell =
512
+ lines.length === 1 && (lines[0]?.split("\t").length ?? 0) === 1;
513
+ const selectionIsRange = startRow !== endRow || startCol !== endCol;
514
+ const fillRange = clipboardIsSingleCell && selectionIsRange;
515
+
516
+ const rowSpan = fillRange ? endRow - startRow + 1 : lines.length;
517
+ const colSpan = fillRange
518
+ ? endCol - startCol + 1
519
+ : Math.max(...lines.map((l) => l.split("\t").length));
520
+
521
+ const next = ctx.internalData.slice() as Array<TData>;
522
+ for (let i = 0; i < rowSpan; i += 1) {
523
+ const targetRowIndex = startRow + i;
524
+ const row = ctx.allRows[targetRowIndex];
525
+ if (!row || isGroupRow(row)) continue;
526
+ // Map the visible row back to its index in the data array via row.id (default = String(index)).
527
+ const dataIndex = Number(row.id);
528
+ if (
529
+ !Number.isInteger(dataIndex) ||
530
+ dataIndex < 0 ||
531
+ dataIndex >= next.length
532
+ )
533
+ continue;
534
+ const originalRow = next[dataIndex];
535
+ if (!originalRow) continue;
536
+ const sourceCells = fillRange
537
+ ? null
538
+ : lines[i]?.split("\t") ?? [];
539
+ const updated: Record<string, unknown> = {
540
+ ...(originalRow as Record<string, unknown>),
541
+ };
542
+ for (let j = 0; j < colSpan; j += 1) {
543
+ const column = ctx.allColumns[startCol + j];
544
+ if (!column?.columnDef.field) continue;
545
+ if (!isCellEditableAt(targetRowIndex, startCol + j)) continue;
546
+ const editorType = (column.columnDef.editorType ??
547
+ "text") as CellEditorType;
548
+ const raw = fillRange ? lines[0]! : sourceCells?.[j] ?? "";
549
+ updated[column.columnDef.field] = parseEditorValue(editorType, raw);
550
+ }
551
+ next[dataIndex] = updated as TData;
552
+ }
553
+ ctx.internalData = next;
554
+ ctx.grid.store.setState((prev: any) => ({ ...prev }));
555
+ }
556
+
557
+ /** Programmatically begin editing a cell (mirrors a double-click). */
558
+ function startEditing(rowIndex: number, columnId: string): boolean {
559
+ if (!ctx.editingEnabled) return false;
560
+ const row = ctx.allRows[rowIndex];
561
+ if (!row || isGroupRow(row)) return false;
562
+ const colIndex = ctx.allColumns.findIndex((c: any) => c.id === columnId);
563
+ if (colIndex < 0) return false;
564
+ const column = ctx.allColumns[colIndex];
565
+ if (!isCellEditable(column, row)) return false;
566
+ if (
567
+ ctx.editingCell?.rowId === row.id &&
568
+ ctx.editingCell?.columnId === columnId
569
+ )
570
+ return true;
571
+ onCellDoubleClick(rowIndex, colIndex);
572
+ return (
573
+ ctx.editingCell?.rowId === row.id &&
574
+ ctx.editingCell?.columnId === columnId
575
+ );
576
+ }
577
+
578
+ /** Commit (default) or cancel the active edit, if any. */
579
+ function stopEditing(cancel = false): boolean {
580
+ if (!ctx.editingCell) return false;
581
+ if (cancel) {
582
+ ctx.editingCell = null;
583
+ } else {
584
+ saveEditingCell();
585
+ }
586
+ return true;
587
+ }
588
+
589
+ // ---- Full-row editing -------------------------------------------------
590
+ /** Put the whole row into edit mode, seeding a draft per editable column. */
591
+ function startFullRowEdit(rowIndex: number): boolean {
592
+ if (!ctx.editingEnabled || !ctx.props.fullRowEditing) return false;
593
+ const row = ctx.allRows[rowIndex];
594
+ if (!row || isGroupRow(row)) return false;
595
+ if (ctx.fullRowEdit && ctx.fullRowEdit.rowId !== row.id) commitFullRowEdit();
596
+ ctx.editingCell = null; // never both at once
597
+ const draft: Record<string, unknown> = {};
598
+ for (const column of ctx.allColumns) {
599
+ if (!column.columnDef.field) continue;
600
+ if (!isCellEditable(column, row)) continue;
601
+ draft[column.id] = getCellDisplayValue(
602
+ row.id,
603
+ column.id,
604
+ row.getCellValueByColumnId(column.id),
605
+ );
606
+ }
607
+ ctx.fullRowEdit = { rowId: row.id, draft };
608
+ ctx.setActiveCell(rowIndex, Math.max(0, ctx.allColumns.findIndex((c: any) => c.id in draft)));
609
+ return true;
610
+ }
611
+
612
+ /** Stage one column's draft value during full-row editing. */
613
+ function setFullRowDraft(columnId: string, value: unknown): void {
614
+ const fr = ctx.fullRowEdit;
615
+ if (!fr) return;
616
+ ctx.fullRowEdit = { rowId: fr.rowId, draft: { ...fr.draft, [columnId]: value } };
617
+ }
618
+
619
+ /** Commit every drafted column of the full-row edit in one data update. */
620
+ function commitFullRowEdit(): void {
621
+ const fr = ctx.fullRowEdit;
622
+ if (!fr) return;
623
+ const row = ctx.allRows.find((r: any) => r.id === fr.rowId);
624
+ if (!row?.original) {
625
+ ctx.fullRowEdit = null;
626
+ return;
627
+ }
628
+ const changed: Array<{ columnId: string; field: string; before: unknown; after: unknown }> = [];
629
+ for (const column of ctx.allColumns) {
630
+ if (!(column.id in fr.draft)) continue;
631
+ const field = column.columnDef.field as string | undefined;
632
+ if (!field) continue;
633
+ const editorType = (column.columnDef.editorType ?? "text") as CellEditorType;
634
+ const parsed = parseEditorValue(editorType, fr.draft[column.id], {
635
+ multiple: column.columnDef.editorMultiple === true,
636
+ });
637
+ const oldValue = (row.original as Record<string, unknown>)[field];
638
+ const parser = (column.columnDef as { valueParser?: (p: unknown) => unknown }).valueParser;
639
+ const finalValue = parser
640
+ ? parser({
641
+ newValue: parsed,
642
+ oldValue,
643
+ rawInput: String(fr.draft[column.id] ?? ""),
644
+ data: row.original,
645
+ columnId: column.id,
646
+ })
647
+ : parsed;
648
+ if (oldValue !== finalValue) {
649
+ (row.original as Record<string, unknown>)[field] = finalValue;
650
+ const key = getCellKey(fr.rowId, column.id);
651
+ ctx.editedCellValues = { ...ctx.editedCellValues, [key]: finalValue };
652
+ changed.push({ columnId: column.id, field, before: oldValue, after: finalValue });
653
+ }
654
+ }
655
+ // Record the whole-row change as consecutive history steps.
656
+ if (changed.length) {
657
+ let hist = ctx.history.slice(0, ctx.historyPtr + 1);
658
+ for (const c of changed) {
659
+ hist.push({ rowId: fr.rowId, columnId: c.columnId, field: c.field, before: c.before, after: c.after });
660
+ }
661
+ if (hist.length > ctx.UNDO_LIMIT) hist = hist.slice(hist.length - ctx.UNDO_LIMIT);
662
+ ctx.history = hist;
663
+ ctx.historyPtr = ctx.history.length - 1;
664
+ ctx.historyVersion += 1;
665
+ }
666
+ ctx.grid.store.setState((prev: any) => ({ ...prev }));
667
+ if (ctx.props.onCellValueChange && changed.length) {
668
+ const rowIndex = ctx.internalData.indexOf(row.original as TData);
669
+ for (const c of changed) {
670
+ ctx.props.onCellValueChange({
671
+ rowIndex,
672
+ columnId: c.columnId,
673
+ oldValue: c.before,
674
+ newValue: c.after,
675
+ row: row.original as TData,
676
+ });
677
+ }
678
+ }
679
+ ctx.fullRowEdit = null;
680
+ }
681
+
682
+ /** Discard the full-row edit. */
683
+ function cancelFullRowEdit(): void {
684
+ ctx.fullRowEdit = null;
685
+ }
686
+
687
+ return {
688
+ isCellEditable,
689
+ isCellEditableAt,
690
+ getRowColumnValue,
691
+ getCellDisplayValue,
692
+ startEditingWithChar,
693
+ startEditing,
694
+ stopEditing,
695
+ startFullRowEdit,
696
+ setFullRowDraft,
697
+ commitFullRowEdit,
698
+ cancelFullRowEdit,
699
+ saveEditingCell,
700
+ applyHistoryStep,
701
+ updateEditingCellValue,
702
+ onEditorKeyDown,
703
+ commitAndMoveByTab,
704
+ focusOnMount,
705
+ onCellDoubleClick,
706
+ pasteFromClipboard,
707
+ onGridPaste,
708
+ };
709
+ }