@svgrid/grid 2.2.27 → 2.2.28

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 (212) 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 +734 -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.css +2723 -2723
  19. package/dist/SvGrid.svelte +3333 -3333
  20. package/dist/SvGridChart.svelte +1724 -1724
  21. package/dist/SvGridChartPanel.svelte +485 -485
  22. package/dist/SvGridChartView.svelte +70 -70
  23. package/dist/SvGridDropdown.svelte +696 -696
  24. package/dist/SvGridSelect.svelte +259 -259
  25. package/dist/SvGroupCell.svelte +109 -109
  26. package/dist/SvListBox.svelte +287 -287
  27. package/dist/SvMaskedInput.svelte +122 -122
  28. package/dist/SvMenu.svelte +124 -124
  29. package/dist/SvMenuList.svelte +146 -146
  30. package/dist/SvMultiSelect.svelte +281 -281
  31. package/dist/SvNumberInput.svelte +168 -168
  32. package/dist/SvOtpInput.svelte +158 -158
  33. package/dist/SvPasswordInput.svelte +151 -151
  34. package/dist/SvPhoneInput.svelte +133 -131
  35. package/dist/SvPopover.svelte +197 -197
  36. package/dist/SvRadioGroup.svelte +107 -107
  37. package/dist/SvRowGroupPanel.svelte +170 -170
  38. package/dist/SvScrollArea.svelte +61 -61
  39. package/dist/SvSlider.svelte +200 -200
  40. package/dist/SvSwitchButton.svelte +107 -107
  41. package/dist/SvTagsInput.svelte +112 -112
  42. package/dist/SvTextInput.svelte +147 -147
  43. package/dist/SvTimePicker.svelte +245 -245
  44. package/dist/SvToaster.svelte +159 -159
  45. package/dist/SvToggleButton.svelte +85 -85
  46. package/dist/SvTooltip.svelte +161 -161
  47. package/dist/SvTour.svelte +204 -204
  48. package/dist/SvTree.svelte +437 -437
  49. package/dist/SvTreeSelect.svelte +233 -233
  50. package/dist/cdn/{GridMenus-BzxEYNtW.js → GridMenus-BbzEvTYO.js} +2 -2
  51. package/dist/cdn/{GridMenus-Dr-nGEXn.js → GridMenus-E220X2kM.js} +2 -2
  52. package/dist/cdn/{SvDateTimePicker-B1sDc9Pz.js → SvDateTimePicker-B8GopjhC.js} +2 -2
  53. package/dist/cdn/{SvDateTimePicker-Bh0FTs1E.js → SvDateTimePicker-DB0aIEk8.js} +2 -2
  54. package/dist/cdn/{SvGridChart-Bgk4hDs8.js → SvGridChart-BcLCYvw9.js} +1 -1
  55. package/dist/cdn/{SvGridChart-BKQsO5fZ.js → SvGridChart-BhnFdLd0.js} +1 -1
  56. package/dist/cdn/{SvGridChartPanel-DkCc2Z7b.js → SvGridChartPanel-Cmx9DHAS.js} +1 -1
  57. package/dist/cdn/{SvGridChartPanel-DSkHIQDd.js → SvGridChartPanel-DvjwxLvK.js} +1 -1
  58. package/dist/cdn/{SvGridChartView-BrbVaELm.js → SvGridChartView-B40DTJSX.js} +1 -1
  59. package/dist/cdn/{SvGridChartView-i9rWvSKg.js → SvGridChartView-PwqI4s02.js} +1 -1
  60. package/dist/cdn/{SvGridDropdown-D08sVmAy.js → SvGridDropdown-DjALc_4f.js} +1 -1
  61. package/dist/cdn/{SvGridDropdown-CGxxopQ4.js → SvGridDropdown-hpnHvOGt.js} +1 -1
  62. package/dist/cdn/{src-cgs1wcUS.js → src-BxNEslEo.js} +25 -25
  63. package/dist/cdn/{src-Cw8d9U8j.js → src-C4yKQZ5t.js} +26 -26
  64. package/dist/cdn/svgrid.js +5 -5
  65. package/dist/cdn/svgrid.svelte-external.js +5 -5
  66. package/dist/chart-export.js +8 -8
  67. package/package.json +10 -10
  68. package/src/FlexRender.svelte +96 -96
  69. package/src/GridFooter.svelte +179 -179
  70. package/src/GridMenus.svelte +734 -734
  71. package/src/SvAutoComplete.svelte +165 -165
  72. package/src/SvCalendar.svelte +503 -503
  73. package/src/SvCalendar.test.ts +226 -226
  74. package/src/SvCarousel.svelte +141 -141
  75. package/src/SvCheckBox.svelte +101 -101
  76. package/src/SvColorInput.svelte +181 -181
  77. package/src/SvComboBox.svelte +275 -275
  78. package/src/SvContextMenu.svelte +116 -116
  79. package/src/SvCountryInput.svelte +160 -160
  80. package/src/SvDrawer.svelte +254 -250
  81. package/src/SvDrawer.test.ts +18 -1
  82. package/src/SvDropDownList.svelte +374 -374
  83. package/src/SvDurationInput.svelte +126 -126
  84. package/src/SvField.svelte +293 -293
  85. package/src/SvForm.svelte +437 -437
  86. package/src/SvForm.test.ts +411 -411
  87. package/src/SvGrid.controller.svelte.ts +3239 -3239
  88. package/src/SvGrid.css +2723 -2723
  89. package/src/SvGrid.svelte +3333 -3333
  90. package/src/SvGrid.types.ts +1613 -1613
  91. package/src/SvGridChart.svelte +1724 -1724
  92. package/src/SvGridChartPanel.svelte +485 -485
  93. package/src/SvGridChartView.svelte +70 -70
  94. package/src/SvGridDropdown.svelte +696 -696
  95. package/src/SvGridSelect.svelte +259 -259
  96. package/src/SvGroupCell.svelte +109 -109
  97. package/src/SvListBox.svelte +287 -287
  98. package/src/SvMaskedInput.svelte +122 -122
  99. package/src/SvMenu.svelte +124 -124
  100. package/src/SvMenu.test.ts +97 -97
  101. package/src/SvMenuList.svelte +146 -146
  102. package/src/SvMultiSelect.svelte +281 -281
  103. package/src/SvNavPane.test.ts +15 -4
  104. package/src/SvNumberInput.svelte +168 -168
  105. package/src/SvOtpInput.svelte +158 -158
  106. package/src/SvPasswordInput.svelte +151 -151
  107. package/src/SvPhoneInput.svelte +133 -131
  108. package/src/SvPopover.svelte +197 -197
  109. package/src/SvRadioGroup.svelte +107 -107
  110. package/src/SvRowGroupPanel.svelte +170 -170
  111. package/src/SvScrollArea.svelte +61 -61
  112. package/src/SvSlider.svelte +200 -200
  113. package/src/SvSwitchButton.svelte +107 -107
  114. package/src/SvTagsInput.svelte +112 -112
  115. package/src/SvTextInput.svelte +147 -147
  116. package/src/SvTimePicker.svelte +245 -245
  117. package/src/SvToaster.svelte +159 -159
  118. package/src/SvToaster.test.ts +95 -95
  119. package/src/SvToggleButton.svelte +85 -85
  120. package/src/SvTooltip.svelte +161 -161
  121. package/src/SvTour.svelte +204 -204
  122. package/src/SvTree.svelte +437 -437
  123. package/src/SvTreeSelect.svelte +233 -233
  124. package/src/a11y/dismissable.test.ts +119 -119
  125. package/src/a11y/dismissable.ts +114 -114
  126. package/src/a11y.contract.test.ts +49 -49
  127. package/src/a11y.test.ts +59 -59
  128. package/src/a11y.ts +61 -61
  129. package/src/ai.test.ts +502 -502
  130. package/src/ai.ts +1391 -1391
  131. package/src/build-api.coverage.test.ts +633 -633
  132. package/src/build-api.ts +895 -895
  133. package/src/builtin-editors.grid.test.ts +85 -85
  134. package/src/cell-formatting.ts +169 -169
  135. package/src/cell-render.ts +469 -469
  136. package/src/chart-export.ts +201 -201
  137. package/src/chart-view.svelte.ts +36 -36
  138. package/src/chart.ts +2296 -2296
  139. package/src/collaboration.test.ts +104 -104
  140. package/src/collaboration.ts +167 -167
  141. package/src/core.performance.test.ts +30 -30
  142. package/src/core.ts +1111 -1111
  143. package/src/createAutocomplete.svelte.ts +132 -132
  144. package/src/createCombobox.svelte.ts +191 -191
  145. package/src/createCountryInput.svelte.ts +157 -157
  146. package/src/createDropdownList.svelte.ts +168 -168
  147. package/src/createForm.svelte.ts +386 -386
  148. package/src/createGrid.svelte.ts +42 -42
  149. package/src/createGrid.test.ts +10 -10
  150. package/src/createGridState.svelte.ts +17 -17
  151. package/src/createMenu.svelte.ts +225 -225
  152. package/src/createPopoverSelect.svelte.ts +213 -213
  153. package/src/createSlider.svelte.ts +191 -191
  154. package/src/createTooltip.svelte.ts +144 -144
  155. package/src/createTree.svelte.ts +319 -319
  156. package/src/editing.test.ts +859 -859
  157. package/src/editing.ts +675 -675
  158. package/src/editor-contract.ts +157 -157
  159. package/src/export-data-api.test.ts +126 -126
  160. package/src/export-format.test.ts +107 -107
  161. package/src/export-format.ts +598 -598
  162. package/src/filter-operators.ts +157 -157
  163. package/src/flex-render.ts +3 -3
  164. package/src/form-field.ts +127 -127
  165. package/src/index.ts +713 -713
  166. package/src/js-scroller.svelte.ts +173 -173
  167. package/src/keyboard.test.ts +59 -59
  168. package/src/keyboard.ts +97 -97
  169. package/src/list-nav.test.ts +49 -49
  170. package/src/list-nav.ts +29 -29
  171. package/src/list-option.test.ts +56 -56
  172. package/src/list-option.ts +172 -172
  173. package/src/menus.test.ts +700 -700
  174. package/src/menus.ts +652 -652
  175. package/src/merge-objects.ts +48 -48
  176. package/src/overlays.test.ts +90 -90
  177. package/src/render-component.ts +28 -28
  178. package/src/scheduler-model.test.ts +562 -562
  179. package/src/scheduler-model.ts +872 -872
  180. package/src/selection.test.ts +754 -754
  181. package/src/selection.ts +600 -600
  182. package/src/server-data-source.test.ts +289 -289
  183. package/src/server-data-source.ts +413 -413
  184. package/src/sparkline.test.ts +68 -68
  185. package/src/sparkline.ts +169 -169
  186. package/src/spreadsheet.test.ts +489 -489
  187. package/src/spreadsheet.ts +312 -312
  188. package/src/static-functions.ts +11 -11
  189. package/src/subscribe.ts +38 -38
  190. package/src/svgrid-wrapper.types.ts +524 -524
  191. package/src/svgrid.behavior.test.ts +706 -706
  192. package/src/svgrid.charting.test.ts +534 -534
  193. package/src/svgrid.features.test.ts +157 -157
  194. package/src/svgrid.new-features.wrapper.test.ts +251 -251
  195. package/src/svgrid.wrapper.test.ts +40 -40
  196. package/src/test-setup.ts +62 -62
  197. package/src/themes/index.ts +215 -215
  198. package/src/toast-store.svelte.ts +246 -246
  199. package/src/toast-store.test.ts +147 -147
  200. package/src/ui-buttons.test.ts +144 -144
  201. package/src/ui-inputs.test.ts +118 -118
  202. package/src/ui-range.test.ts +70 -70
  203. package/src/ui-selection.test.ts +155 -155
  204. package/src/ui-tier1.test.ts +142 -142
  205. package/src/virtual.test.ts +88 -88
  206. package/src/virtualization/column-virtualizer.test.ts +27 -27
  207. package/src/virtualization/column-virtualizer.ts +30 -30
  208. package/src/virtualization/svelte-virtualizer.svelte.ts +26 -26
  209. package/src/virtualization/types.ts +30 -30
  210. package/src/virtualization/virtualizer.test.ts +47 -47
  211. package/src/virtualization/virtualizer.ts +296 -296
  212. package/themes/ember.css +71 -71
package/src/editing.ts CHANGED
@@ -1,675 +1,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
- };
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
+ };
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
+ }