@svgrid/grid 2.2.0 → 2.2.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 (114) hide show
  1. package/dist/FlexRender.svelte +96 -96
  2. package/dist/GridFooter.svelte +178 -178
  3. package/dist/SvCarousel.svelte +141 -141
  4. package/dist/SvColorInput.svelte +187 -187
  5. package/dist/SvContextMenu.svelte +116 -116
  6. package/dist/SvDrawer.svelte +250 -250
  7. package/dist/SvGrid.svelte +3131 -3131
  8. package/dist/SvGridBoard.svelte +2339 -2339
  9. package/dist/SvGridChart.svelte +1724 -1724
  10. package/dist/SvGridChartPanel.svelte +485 -485
  11. package/dist/SvGridDropdown.svelte +689 -689
  12. package/dist/SvGroupCell.svelte +109 -109
  13. package/dist/SvMenu.svelte +124 -124
  14. package/dist/SvMenuList.svelte +117 -117
  15. package/dist/SvNumberInput.svelte +131 -131
  16. package/dist/SvOtpInput.svelte +158 -158
  17. package/dist/SvPopover.svelte +139 -139
  18. package/dist/SvRowGroupPanel.svelte +170 -170
  19. package/dist/SvScrollArea.svelte +61 -61
  20. package/dist/SvTooltip.svelte +127 -127
  21. package/dist/SvTour.svelte +204 -204
  22. package/dist/SvTree.svelte +377 -377
  23. package/dist/SvTreeSelect.svelte +230 -230
  24. package/dist/cdn/svgrid.js +8 -8
  25. package/dist/cdn/svgrid.svelte-external.js +8 -8
  26. package/dist/chart-export.js +8 -8
  27. package/package.json +10 -10
  28. package/src/FlexRender.svelte +96 -96
  29. package/src/GridFooter.svelte +178 -178
  30. package/src/SvCarousel.svelte +141 -141
  31. package/src/SvColorInput.svelte +187 -187
  32. package/src/SvContextMenu.svelte +116 -116
  33. package/src/SvDrawer.svelte +250 -250
  34. package/src/SvGrid.controller.svelte.ts +3158 -3158
  35. package/src/SvGrid.svelte +3131 -3131
  36. package/src/SvGrid.types.ts +1489 -1489
  37. package/src/SvGridBoard.svelte +2339 -2339
  38. package/src/SvGridChart.svelte +1724 -1724
  39. package/src/SvGridChartPanel.svelte +485 -485
  40. package/src/SvGridDropdown.svelte +689 -689
  41. package/src/SvGroupCell.svelte +109 -109
  42. package/src/SvMenu.svelte +124 -124
  43. package/src/SvMenu.test.ts +97 -97
  44. package/src/SvMenuList.svelte +117 -117
  45. package/src/SvNumberInput.svelte +131 -131
  46. package/src/SvOtpInput.svelte +158 -158
  47. package/src/SvPopover.svelte +139 -139
  48. package/src/SvRowGroupPanel.svelte +170 -170
  49. package/src/SvScrollArea.svelte +61 -61
  50. package/src/SvTooltip.svelte +127 -127
  51. package/src/SvTour.svelte +204 -204
  52. package/src/SvTree.svelte +377 -377
  53. package/src/SvTreeSelect.svelte +230 -230
  54. package/src/a11y.contract.test.ts +49 -49
  55. package/src/a11y.test.ts +59 -59
  56. package/src/a11y.ts +61 -61
  57. package/src/build-api.ts +870 -870
  58. package/src/cell-formatting.ts +169 -169
  59. package/src/cell-render.ts +469 -469
  60. package/src/chart-export.ts +201 -201
  61. package/src/chart.ts +2296 -2296
  62. package/src/collaboration.test.ts +104 -104
  63. package/src/collaboration.ts +167 -167
  64. package/src/core.performance.test.ts +30 -30
  65. package/src/core.ts +1111 -1111
  66. package/src/createAutocomplete.svelte.ts +132 -132
  67. package/src/createCombobox.svelte.ts +179 -179
  68. package/src/createCountryInput.svelte.ts +157 -157
  69. package/src/createDropdownList.svelte.ts +162 -162
  70. package/src/createGrid.svelte.ts +42 -42
  71. package/src/createGrid.test.ts +10 -10
  72. package/src/createGridState.svelte.ts +17 -17
  73. package/src/createMenu.svelte.ts +202 -202
  74. package/src/createPopoverSelect.svelte.ts +206 -206
  75. package/src/createTree.svelte.ts +319 -319
  76. package/src/editing.test.ts +859 -859
  77. package/src/editing.ts +675 -675
  78. package/src/export-data-api.test.ts +126 -126
  79. package/src/export-format.test.ts +107 -107
  80. package/src/export-format.ts +598 -598
  81. package/src/flex-render.ts +3 -3
  82. package/src/index.ts +623 -623
  83. package/src/keyboard.test.ts +59 -59
  84. package/src/keyboard.ts +97 -97
  85. package/src/list-nav.test.ts +49 -49
  86. package/src/list-nav.ts +29 -29
  87. package/src/menus.ts +639 -639
  88. package/src/merge-objects.ts +48 -48
  89. package/src/overlays.test.ts +90 -90
  90. package/src/render-component.ts +28 -28
  91. package/src/selection.test.ts +754 -754
  92. package/src/selection.ts +600 -600
  93. package/src/server-data-source.test.ts +289 -289
  94. package/src/server-data-source.ts +413 -413
  95. package/src/sparkline.test.ts +68 -68
  96. package/src/sparkline.ts +169 -169
  97. package/src/spreadsheet.test.ts +489 -489
  98. package/src/spreadsheet.ts +312 -312
  99. package/src/static-functions.ts +11 -11
  100. package/src/subscribe.ts +38 -38
  101. package/src/svgrid-wrapper.types.ts +501 -501
  102. package/src/svgrid.behavior.test.ts +706 -706
  103. package/src/svgrid.charting.test.ts +527 -527
  104. package/src/svgrid.features.test.ts +157 -157
  105. package/src/svgrid.new-features.wrapper.test.ts +251 -251
  106. package/src/svgrid.wrapper.test.ts +40 -40
  107. package/src/test-setup.ts +62 -62
  108. package/src/themes/index.ts +159 -159
  109. package/src/virtualization/column-virtualizer.test.ts +27 -27
  110. package/src/virtualization/column-virtualizer.ts +30 -30
  111. package/src/virtualization/svelte-virtualizer.svelte.ts +26 -26
  112. package/src/virtualization/types.ts +30 -30
  113. package/src/virtualization/virtualizer.test.ts +47 -47
  114. package/src/virtualization/virtualizer.ts +296 -296
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
+ }