@svgrid/grid 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/GridMenus.svelte +205 -127
  2. package/dist/SvGrid.controller.svelte.d.ts +44 -1
  3. package/dist/SvGrid.controller.svelte.js +223 -38
  4. package/dist/SvGrid.css +2012 -1709
  5. package/dist/SvGrid.helpers.test.d.ts +1 -0
  6. package/dist/SvGrid.helpers.test.js +298 -0
  7. package/dist/SvGrid.svelte +2346 -2043
  8. package/dist/SvGrid.types.d.ts +91 -4
  9. package/dist/aligned-grids.d.ts +6 -0
  10. package/dist/aligned-grids.js +84 -0
  11. package/dist/aligned-grids.test.d.ts +1 -0
  12. package/dist/aligned-grids.test.js +75 -0
  13. package/dist/build-api.coverage.test.d.ts +20 -0
  14. package/dist/build-api.coverage.test.js +505 -0
  15. package/dist/build-api.js +59 -29
  16. package/dist/cell-render.test.d.ts +1 -0
  17. package/dist/cell-render.test.js +338 -0
  18. package/dist/chart-export.test.d.ts +1 -0
  19. package/dist/chart-export.test.js +302 -0
  20. package/dist/chart.coverage.test.d.ts +1 -0
  21. package/dist/chart.coverage.test.js +748 -0
  22. package/dist/clipboard.js +88 -24
  23. package/dist/clipboard.test.d.ts +1 -0
  24. package/dist/clipboard.test.js +700 -0
  25. package/dist/collaboration.coverage.test.d.ts +1 -0
  26. package/dist/collaboration.coverage.test.js +200 -0
  27. package/dist/column-groups.d.ts +19 -0
  28. package/dist/column-groups.js +62 -0
  29. package/dist/column-groups.test.d.ts +1 -0
  30. package/dist/column-groups.test.js +56 -0
  31. package/dist/column-types.d.ts +10 -0
  32. package/dist/column-types.js +63 -0
  33. package/dist/column-types.test.d.ts +1 -0
  34. package/dist/column-types.test.js +62 -0
  35. package/dist/columns.test.d.ts +1 -0
  36. package/dist/columns.test.js +625 -0
  37. package/dist/core.d.ts +85 -0
  38. package/dist/editing.d.ts +7 -0
  39. package/dist/editing.js +191 -5
  40. package/dist/editing.test.d.ts +1 -0
  41. package/dist/editing.test.js +732 -0
  42. package/dist/editors/cell-editors.coverage.test.d.ts +1 -0
  43. package/dist/editors/cell-editors.coverage.test.js +139 -0
  44. package/dist/facet-buckets.test.d.ts +1 -0
  45. package/dist/facet-buckets.test.js +296 -0
  46. package/dist/filter-operators.test.d.ts +1 -0
  47. package/dist/filter-operators.test.js +135 -0
  48. package/dist/hyperformula-adapter.test.d.ts +1 -0
  49. package/dist/hyperformula-adapter.test.js +205 -0
  50. package/dist/index.d.ts +5 -2
  51. package/dist/index.js +4 -1
  52. package/dist/keyboard-handlers.coverage.test.d.ts +1 -0
  53. package/dist/keyboard-handlers.coverage.test.js +495 -0
  54. package/dist/keyboard-handlers.js +7 -2
  55. package/dist/menus.js +1 -0
  56. package/dist/menus.test.d.ts +1 -0
  57. package/dist/menus.test.js +560 -0
  58. package/dist/named-views.coverage.test.d.ts +1 -0
  59. package/dist/named-views.coverage.test.js +180 -0
  60. package/dist/row-drag.d.ts +49 -0
  61. package/dist/row-drag.js +221 -0
  62. package/dist/row-drag.test.d.ts +1 -0
  63. package/dist/row-drag.test.js +142 -0
  64. package/dist/row-resize.test.d.ts +1 -0
  65. package/dist/row-resize.test.js +329 -0
  66. package/dist/scroll-sync.js +3 -0
  67. package/dist/scroll-sync.test.d.ts +1 -0
  68. package/dist/scroll-sync.test.js +290 -0
  69. package/dist/selection.d.ts +7 -1
  70. package/dist/selection.js +76 -36
  71. package/dist/selection.multi-range.test.d.ts +1 -0
  72. package/dist/selection.multi-range.test.js +55 -0
  73. package/dist/selection.test.d.ts +1 -0
  74. package/dist/selection.test.js +647 -0
  75. package/dist/server-data-source.coverage.test.d.ts +1 -0
  76. package/dist/server-data-source.coverage.test.js +154 -0
  77. package/dist/spreadsheet.d.ts +30 -0
  78. package/dist/spreadsheet.js +48 -0
  79. package/dist/spreadsheet.test.d.ts +1 -0
  80. package/dist/spreadsheet.test.js +446 -0
  81. package/dist/sv-grid-scrollbar.js +13 -1
  82. package/dist/svgrid-wrapper.types.d.ts +19 -0
  83. package/dist/svgrid.behavior.test.js +20 -0
  84. package/dist/svgrid.interaction.test.js +31 -0
  85. package/dist/svgrid.new-features.wrapper.test.js +34 -2
  86. package/dist/test-setup.js +9 -3
  87. package/dist/virtualization/scroll-scaling.d.ts +17 -0
  88. package/dist/virtualization/scroll-scaling.js +35 -0
  89. package/dist/virtualization/scroll-scaling.test.js +42 -1
  90. package/package.json +2 -1
  91. package/src/GridMenus.svelte +205 -127
  92. package/src/SvGrid.controller.svelte.ts +2352 -2195
  93. package/src/SvGrid.css +2012 -1747
  94. package/src/SvGrid.svelte +2346 -2047
  95. package/src/SvGrid.types.ts +537 -456
  96. package/src/aligned-grids.test.ts +80 -0
  97. package/src/aligned-grids.ts +87 -0
  98. package/src/build-api.ts +683 -663
  99. package/src/clipboard.test.ts +49 -0
  100. package/src/clipboard.ts +51 -23
  101. package/src/column-groups.test.ts +59 -0
  102. package/src/column-groups.ts +80 -0
  103. package/src/column-types.test.ts +68 -0
  104. package/src/column-types.ts +82 -0
  105. package/src/core.ts +78 -0
  106. package/src/editing.ts +669 -513
  107. package/src/index.ts +12 -0
  108. package/src/menus.ts +1 -0
  109. package/src/row-drag.test.ts +168 -0
  110. package/src/row-drag.ts +255 -0
  111. package/src/scroll-sync.ts +2 -0
  112. package/src/selection.multi-range.test.ts +61 -0
  113. package/src/selection.ts +71 -37
  114. package/src/spreadsheet.test.ts +489 -445
  115. package/src/spreadsheet.ts +304 -246
  116. package/src/svgrid-wrapper.types.ts +19 -0
  117. package/src/svgrid.new-features.wrapper.test.ts +2 -2
package/src/editing.ts CHANGED
@@ -1,513 +1,669 @@
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
- if (row?.original && column?.columnDef.field) {
255
- oldValue = (row.original as Record<string, unknown>)[
256
- column.columnDef.field
257
- ];
258
- (row.original as Record<string, unknown>)[column.columnDef.field] =
259
- parsedValue;
260
- }
261
- const key = getCellKey(ctx.editingCell.rowId, ctx.editingCell.columnId);
262
- ctx.editedCellValues = {
263
- ...ctx.editedCellValues,
264
- [key]: parsedValue,
265
- };
266
- ctx.grid.store.setState((prev: any) => ({ ...prev }));
267
- // Record into the history at the current pointer. Any forward
268
- // history (steps the user could have redone) is truncated - this
269
- // is the standard "edit invalidates redo" rule.
270
- if (oldValue !== parsedValue && row?.original && column?.columnDef.field) {
271
- const step: HistoryStep = {
272
- rowId: ctx.editingCell.rowId,
273
- columnId: ctx.editingCell.columnId,
274
- field: column.columnDef.field as string,
275
- before: oldValue,
276
- after: parsedValue,
277
- }
278
- const truncated = ctx.history.slice(0, ctx.historyPtr + 1)
279
- truncated.push(step)
280
- // Cap the buffer at UNDO_LIMIT; drop the OLDEST entries so the
281
- // pointer stays valid relative to the newest steps.
282
- if (truncated.length > ctx.UNDO_LIMIT) {
283
- const drop = truncated.length - ctx.UNDO_LIMIT
284
- ctx.history = truncated.slice(drop)
285
- ctx.historyPtr = ctx.history.length - 1
286
- } else {
287
- ctx.history = truncated
288
- ctx.historyPtr = ctx.history.length - 1
289
- }
290
- ctx.historyVersion += 1
291
- }
292
- // Notify the consumer AFTER the row has been updated so any callback-
293
- // driven recompute (cascade totals, server save, undo stack) sees the
294
- // post-write state. `rowIndex` matches the position in `props.data`.
295
- if (ctx.props.onCellValueChange && row?.original && column) {
296
- const rowIndex = ctx.internalData.indexOf(row.original as TData);
297
- ctx.props.onCellValueChange({
298
- rowIndex,
299
- columnId: column.id,
300
- oldValue,
301
- newValue: parsedValue,
302
- row: row.original as TData,
303
- });
304
- }
305
- ctx.editingCell = null;
306
- }
307
-
308
- /** Apply an undo / redo step directly to the underlying row, bypassing
309
- * the editor pipeline so we don't accidentally re-push to the stack. */
310
- function applyHistoryStep(step: HistoryStep, direction: 'undo' | 'redo') {
311
- const row = ctx.allRows.find((r: any) => r.id === step.rowId)
312
- const col = ctx.allColumns.find((c: any) => c.id === step.columnId)
313
- if (!row?.original || !col) return
314
- const value = direction === 'undo' ? step.before : step.after
315
- ;(row.original as Record<string, unknown>)[step.field] = value
316
- const key = getCellKey(step.rowId, step.columnId)
317
- ctx.editedCellValues = { ...ctx.editedCellValues, [key]: value }
318
- ctx.grid.store.setState((prev: any) => ({ ...prev }))
319
- if (ctx.props.onCellValueChange) {
320
- const rowIndex = ctx.internalData.indexOf(row.original as TData)
321
- ctx.props.onCellValueChange({
322
- rowIndex,
323
- columnId: step.columnId,
324
- oldValue: direction === 'undo' ? step.after : step.before,
325
- newValue: value,
326
- row: row.original as TData,
327
- })
328
- }
329
- }
330
-
331
- function updateEditingCellValue(value: string) {
332
- ctx.editingCell = ctx.editingCell ? { ...ctx.editingCell, value } : ctx.editingCell;
333
- }
334
-
335
- function onEditorKeyDown(event: KeyboardEvent) {
336
- event.stopPropagation();
337
- if (event.key === "Enter") {
338
- event.preventDefault();
339
- saveEditingCell();
340
- ctx.gridRootEl?.focus({ preventScroll: true });
341
- } else if (event.key === "Escape") {
342
- event.preventDefault();
343
- ctx.editingCell = null;
344
- ctx.gridRootEl?.focus({ preventScroll: true });
345
- }
346
- }
347
-
348
- function focusOnMount(node: HTMLInputElement | HTMLTextAreaElement) {
349
- const selectAll = ctx.editorSelectAll;
350
- requestAnimationFrame(() => {
351
- node.focus({ preventScroll: true });
352
- try {
353
- if (selectAll) {
354
- node.select();
355
- } else {
356
- const end = node.value.length;
357
- node.setSelectionRange(end, end);
358
- }
359
- } catch {
360
- /* date/number inputs may not support text selection */
361
- }
362
- });
363
- }
364
-
365
- function onCellDoubleClick(rowIndex: number, colIndex: number) {
366
- if (!ctx.editingEnabled) return;
367
- const row = ctx.allRows[rowIndex];
368
- const column = ctx.allColumns[colIndex];
369
- if (!row || !column) return;
370
- if (isGroupRow(row)) return;
371
- if (!isCellEditable(column, row)) return;
372
- if (ctx.editingCell?.rowId === row.id && ctx.editingCell?.columnId === column.id)
373
- return;
374
- const editorType = (column.columnDef.editorType ??
375
- "text") as CellEditorType;
376
- ctx.editorSelectAll = true;
377
- let initialValue = getCellDisplayValue(
378
- row.id,
379
- column.id,
380
- row.getCellValueByColumnId(column.id),
381
- );
382
- if (editorType === "list" || editorType === "chips") {
383
- if (column.columnDef.editorMultiple) {
384
- // Seed with an array so the editor can mutate slot-by-slot.
385
- initialValue = toValueArray(initialValue);
386
- } else if (Array.isArray(initialValue)) {
387
- initialValue = initialValue[0] ?? "";
388
- }
389
- }
390
- ctx.editingCell = {
391
- rowId: row.id,
392
- columnId: column.id,
393
- editorType,
394
- value: initialValue,
395
- };
396
- ctx.setActiveCell(rowIndex, colIndex);
397
- ctx.setSelection(rowIndex, colIndex);
398
- }
399
-
400
- async function pasteFromClipboard() {
401
- // Preferred path: the async Clipboard API. Requires a secure context
402
- // (HTTPS or localhost) AND read permission; it also works on Firefox,
403
- // where the native `paste` event does NOT fire on a non-editable element.
404
- // On plain HTTP (a XAMPP/Apache LAN host) `navigator.clipboard` is
405
- // undefined - there the Ctrl+V keydown handler skips preventDefault and
406
- // lets the browser deliver a native `paste` event to `onGridPaste`.
407
- if (!navigator.clipboard?.readText) return;
408
- let text: string;
409
- try {
410
- text = await navigator.clipboard.readText();
411
- } catch {
412
- return;
413
- }
414
- applyPastedText(text);
415
- }
416
-
417
- /**
418
- * Native `paste` ClipboardEvent fallback (insecure-context path). A real
419
- * Ctrl/Cmd+V on the focused grid root fires this with `clipboardData`
420
- * readable even over plain HTTP and with no permission prompt. Wired on the
421
- * grid root in SvGrid.svelte; the keydown handler lets the gesture through
422
- * (no preventDefault) whenever the async API is unavailable.
423
- */
424
- function onGridPaste(event: ClipboardEvent) {
425
- // When the async API is available the keydown handler already pasted via
426
- // pasteFromClipboard(); ignore the (suppressed) native event so we don't
427
- // paste twice.
428
- if (typeof navigator.clipboard?.readText === "function") return;
429
- const text = event.clipboardData?.getData("text/plain") ?? "";
430
- if (!text) return;
431
- event.preventDefault();
432
- applyPastedText(text);
433
- }
434
-
435
- function applyPastedText(text: string) {
436
- const anchor = ctx.selectionRange.anchor ?? ctx.grid.getState().activeCell;
437
- if (!anchor) return;
438
- const focus = ctx.selectionRange.focus ?? anchor;
439
- const startRow = Math.min(anchor.rowIndex, focus.rowIndex);
440
- const startCol = Math.min(anchor.colIndex, focus.colIndex);
441
- const endRow = Math.max(anchor.rowIndex, focus.rowIndex);
442
- const endCol = Math.max(anchor.colIndex, focus.colIndex);
443
- const lines = text.replace(/\r\n/g, "\n").split("\n");
444
- if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
445
- if (!lines.length) return;
446
-
447
- // Excel/Sheets behaviour: when the clipboard holds a single cell and
448
- // the selection is a range, fill the entire range with that value.
449
- // For larger clipboards (multi-row/col TSV), paste at the top-left
450
- // corner and let the clipboard determine the span (the original
451
- // behaviour).
452
- const clipboardIsSingleCell =
453
- lines.length === 1 && (lines[0]?.split("\t").length ?? 0) === 1;
454
- const selectionIsRange = startRow !== endRow || startCol !== endCol;
455
- const fillRange = clipboardIsSingleCell && selectionIsRange;
456
-
457
- const rowSpan = fillRange ? endRow - startRow + 1 : lines.length;
458
- const colSpan = fillRange
459
- ? endCol - startCol + 1
460
- : Math.max(...lines.map((l) => l.split("\t").length));
461
-
462
- const next = ctx.internalData.slice() as Array<TData>;
463
- for (let i = 0; i < rowSpan; i += 1) {
464
- const targetRowIndex = startRow + i;
465
- const row = ctx.allRows[targetRowIndex];
466
- if (!row || isGroupRow(row)) continue;
467
- // Map the visible row back to its index in the data array via row.id (default = String(index)).
468
- const dataIndex = Number(row.id);
469
- if (
470
- !Number.isInteger(dataIndex) ||
471
- dataIndex < 0 ||
472
- dataIndex >= next.length
473
- )
474
- continue;
475
- const originalRow = next[dataIndex];
476
- if (!originalRow) continue;
477
- const sourceCells = fillRange
478
- ? null
479
- : lines[i]?.split("\t") ?? [];
480
- const updated: Record<string, unknown> = {
481
- ...(originalRow as Record<string, unknown>),
482
- };
483
- for (let j = 0; j < colSpan; j += 1) {
484
- const column = ctx.allColumns[startCol + j];
485
- if (!column?.columnDef.field) continue;
486
- if (!isCellEditableAt(targetRowIndex, startCol + j)) continue;
487
- const editorType = (column.columnDef.editorType ??
488
- "text") as CellEditorType;
489
- const raw = fillRange ? lines[0]! : sourceCells?.[j] ?? "";
490
- updated[column.columnDef.field] = parseEditorValue(editorType, raw);
491
- }
492
- next[dataIndex] = updated as TData;
493
- }
494
- ctx.internalData = next;
495
- ctx.grid.store.setState((prev: any) => ({ ...prev }));
496
- }
497
-
498
- return {
499
- isCellEditable,
500
- isCellEditableAt,
501
- getRowColumnValue,
502
- getCellDisplayValue,
503
- startEditingWithChar,
504
- saveEditingCell,
505
- applyHistoryStep,
506
- updateEditingCellValue,
507
- onEditorKeyDown,
508
- focusOnMount,
509
- onCellDoubleClick,
510
- pasteFromClipboard,
511
- onGridPaste,
512
- };
513
- }
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: string) {
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
+ // When the async API is available the keydown handler already pasted via
446
+ // pasteFromClipboard(); ignore the (suppressed) native event so we don't
447
+ // paste twice.
448
+ if (typeof navigator.clipboard?.readText === "function") return;
449
+ const text = event.clipboardData?.getData("text/plain") ?? "";
450
+ if (!text) return;
451
+ event.preventDefault();
452
+ applyPastedText(text);
453
+ }
454
+
455
+ function applyPastedText(text: string) {
456
+ const anchor = ctx.selectionRange.anchor ?? ctx.grid.getState().activeCell;
457
+ if (!anchor) return;
458
+ const focus = ctx.selectionRange.focus ?? anchor;
459
+ const startRow = Math.min(anchor.rowIndex, focus.rowIndex);
460
+ const startCol = Math.min(anchor.colIndex, focus.colIndex);
461
+ const endRow = Math.max(anchor.rowIndex, focus.rowIndex);
462
+ const endCol = Math.max(anchor.colIndex, focus.colIndex);
463
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
464
+ if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
465
+ if (!lines.length) return;
466
+
467
+ // Excel/Sheets behaviour: when the clipboard holds a single cell and
468
+ // the selection is a range, fill the entire range with that value.
469
+ // For larger clipboards (multi-row/col TSV), paste at the top-left
470
+ // corner and let the clipboard determine the span (the original
471
+ // behaviour).
472
+ const clipboardIsSingleCell =
473
+ lines.length === 1 && (lines[0]?.split("\t").length ?? 0) === 1;
474
+ const selectionIsRange = startRow !== endRow || startCol !== endCol;
475
+ const fillRange = clipboardIsSingleCell && selectionIsRange;
476
+
477
+ const rowSpan = fillRange ? endRow - startRow + 1 : lines.length;
478
+ const colSpan = fillRange
479
+ ? endCol - startCol + 1
480
+ : Math.max(...lines.map((l) => l.split("\t").length));
481
+
482
+ const next = ctx.internalData.slice() as Array<TData>;
483
+ for (let i = 0; i < rowSpan; i += 1) {
484
+ const targetRowIndex = startRow + i;
485
+ const row = ctx.allRows[targetRowIndex];
486
+ if (!row || isGroupRow(row)) continue;
487
+ // Map the visible row back to its index in the data array via row.id (default = String(index)).
488
+ const dataIndex = Number(row.id);
489
+ if (
490
+ !Number.isInteger(dataIndex) ||
491
+ dataIndex < 0 ||
492
+ dataIndex >= next.length
493
+ )
494
+ continue;
495
+ const originalRow = next[dataIndex];
496
+ if (!originalRow) continue;
497
+ const sourceCells = fillRange
498
+ ? null
499
+ : lines[i]?.split("\t") ?? [];
500
+ const updated: Record<string, unknown> = {
501
+ ...(originalRow as Record<string, unknown>),
502
+ };
503
+ for (let j = 0; j < colSpan; j += 1) {
504
+ const column = ctx.allColumns[startCol + j];
505
+ if (!column?.columnDef.field) continue;
506
+ if (!isCellEditableAt(targetRowIndex, startCol + j)) continue;
507
+ const editorType = (column.columnDef.editorType ??
508
+ "text") as CellEditorType;
509
+ const raw = fillRange ? lines[0]! : sourceCells?.[j] ?? "";
510
+ updated[column.columnDef.field] = parseEditorValue(editorType, raw);
511
+ }
512
+ next[dataIndex] = updated as TData;
513
+ }
514
+ ctx.internalData = next;
515
+ ctx.grid.store.setState((prev: any) => ({ ...prev }));
516
+ }
517
+
518
+ /** Programmatically begin editing a cell (mirrors a double-click). */
519
+ function startEditing(rowIndex: number, columnId: string): boolean {
520
+ if (!ctx.editingEnabled) return false;
521
+ const row = ctx.allRows[rowIndex];
522
+ if (!row || isGroupRow(row)) return false;
523
+ const colIndex = ctx.allColumns.findIndex((c: any) => c.id === columnId);
524
+ if (colIndex < 0) return false;
525
+ const column = ctx.allColumns[colIndex];
526
+ if (!isCellEditable(column, row)) return false;
527
+ if (
528
+ ctx.editingCell?.rowId === row.id &&
529
+ ctx.editingCell?.columnId === columnId
530
+ )
531
+ return true;
532
+ onCellDoubleClick(rowIndex, colIndex);
533
+ return (
534
+ ctx.editingCell?.rowId === row.id &&
535
+ ctx.editingCell?.columnId === columnId
536
+ );
537
+ }
538
+
539
+ /** Commit (default) or cancel the active edit, if any. */
540
+ function stopEditing(cancel = false): boolean {
541
+ if (!ctx.editingCell) return false;
542
+ if (cancel) {
543
+ ctx.editingCell = null;
544
+ } else {
545
+ saveEditingCell();
546
+ }
547
+ return true;
548
+ }
549
+
550
+ // ---- Full-row editing -------------------------------------------------
551
+ /** Put the whole row into edit mode, seeding a draft per editable column. */
552
+ function startFullRowEdit(rowIndex: number): boolean {
553
+ if (!ctx.editingEnabled || !ctx.props.fullRowEditing) return false;
554
+ const row = ctx.allRows[rowIndex];
555
+ if (!row || isGroupRow(row)) return false;
556
+ if (ctx.fullRowEdit && ctx.fullRowEdit.rowId !== row.id) commitFullRowEdit();
557
+ ctx.editingCell = null; // never both at once
558
+ const draft: Record<string, unknown> = {};
559
+ for (const column of ctx.allColumns) {
560
+ if (!column.columnDef.field) continue;
561
+ if (!isCellEditable(column, row)) continue;
562
+ draft[column.id] = getCellDisplayValue(
563
+ row.id,
564
+ column.id,
565
+ row.getCellValueByColumnId(column.id),
566
+ );
567
+ }
568
+ ctx.fullRowEdit = { rowId: row.id, draft };
569
+ ctx.setActiveCell(rowIndex, Math.max(0, ctx.allColumns.findIndex((c: any) => c.id in draft)));
570
+ return true;
571
+ }
572
+
573
+ /** Stage one column's draft value during full-row editing. */
574
+ function setFullRowDraft(columnId: string, value: unknown): void {
575
+ const fr = ctx.fullRowEdit;
576
+ if (!fr) return;
577
+ ctx.fullRowEdit = { rowId: fr.rowId, draft: { ...fr.draft, [columnId]: value } };
578
+ }
579
+
580
+ /** Commit every drafted column of the full-row edit in one data update. */
581
+ function commitFullRowEdit(): void {
582
+ const fr = ctx.fullRowEdit;
583
+ if (!fr) return;
584
+ const row = ctx.allRows.find((r: any) => r.id === fr.rowId);
585
+ if (!row?.original) {
586
+ ctx.fullRowEdit = null;
587
+ return;
588
+ }
589
+ const changed: Array<{ columnId: string; field: string; before: unknown; after: unknown }> = [];
590
+ for (const column of ctx.allColumns) {
591
+ if (!(column.id in fr.draft)) continue;
592
+ const field = column.columnDef.field as string | undefined;
593
+ if (!field) continue;
594
+ const editorType = (column.columnDef.editorType ?? "text") as CellEditorType;
595
+ const parsed = parseEditorValue(editorType, fr.draft[column.id], {
596
+ multiple: column.columnDef.editorMultiple === true,
597
+ });
598
+ const oldValue = (row.original as Record<string, unknown>)[field];
599
+ const parser = (column.columnDef as { valueParser?: (p: unknown) => unknown }).valueParser;
600
+ const finalValue = parser
601
+ ? parser({
602
+ newValue: parsed,
603
+ oldValue,
604
+ rawInput: String(fr.draft[column.id] ?? ""),
605
+ data: row.original,
606
+ columnId: column.id,
607
+ })
608
+ : parsed;
609
+ if (oldValue !== finalValue) {
610
+ (row.original as Record<string, unknown>)[field] = finalValue;
611
+ const key = getCellKey(fr.rowId, column.id);
612
+ ctx.editedCellValues = { ...ctx.editedCellValues, [key]: finalValue };
613
+ changed.push({ columnId: column.id, field, before: oldValue, after: finalValue });
614
+ }
615
+ }
616
+ // Record the whole-row change as consecutive history steps.
617
+ if (changed.length) {
618
+ let hist = ctx.history.slice(0, ctx.historyPtr + 1);
619
+ for (const c of changed) {
620
+ hist.push({ rowId: fr.rowId, columnId: c.columnId, field: c.field, before: c.before, after: c.after });
621
+ }
622
+ if (hist.length > ctx.UNDO_LIMIT) hist = hist.slice(hist.length - ctx.UNDO_LIMIT);
623
+ ctx.history = hist;
624
+ ctx.historyPtr = ctx.history.length - 1;
625
+ ctx.historyVersion += 1;
626
+ }
627
+ ctx.grid.store.setState((prev: any) => ({ ...prev }));
628
+ if (ctx.props.onCellValueChange && changed.length) {
629
+ const rowIndex = ctx.internalData.indexOf(row.original as TData);
630
+ for (const c of changed) {
631
+ ctx.props.onCellValueChange({
632
+ rowIndex,
633
+ columnId: c.columnId,
634
+ oldValue: c.before,
635
+ newValue: c.after,
636
+ row: row.original as TData,
637
+ });
638
+ }
639
+ }
640
+ ctx.fullRowEdit = null;
641
+ }
642
+
643
+ /** Discard the full-row edit. */
644
+ function cancelFullRowEdit(): void {
645
+ ctx.fullRowEdit = null;
646
+ }
647
+
648
+ return {
649
+ isCellEditable,
650
+ isCellEditableAt,
651
+ getRowColumnValue,
652
+ getCellDisplayValue,
653
+ startEditingWithChar,
654
+ startEditing,
655
+ stopEditing,
656
+ startFullRowEdit,
657
+ setFullRowDraft,
658
+ commitFullRowEdit,
659
+ cancelFullRowEdit,
660
+ saveEditingCell,
661
+ applyHistoryStep,
662
+ updateEditingCellValue,
663
+ onEditorKeyDown,
664
+ focusOnMount,
665
+ onCellDoubleClick,
666
+ pasteFromClipboard,
667
+ onGridPaste,
668
+ };
669
+ }