• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

glideapps / glide-data-grid / 7310496627

23 Dec 2023 09:09PM UTC coverage: 90.583% (+0.02%) from 90.561%
7310496627

Pull #829

github

jassmith
Cleanup
Pull Request #829: Allow control of cell activation behavior

2594 of 3246 branches covered (0.0%)

49 of 50 new or added lines in 3 files covered. (98.0%)

211 existing lines in 2 files now uncovered.

15746 of 17383 relevant lines covered (90.58%)

3167.92 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.37
/packages/core/src/data-editor/data-editor.tsx
1
/* eslint-disable sonarjs/no-duplicate-string */
1✔
2
import * as React from "react";
1✔
3
import { assert, assertNever, maybe } from "../common/support.js";
1✔
4
import clamp from "lodash/clamp.js";
1✔
5
import uniq from "lodash/uniq.js";
1✔
6
import flatten from "lodash/flatten.js";
1✔
7
import range from "lodash/range.js";
1✔
8
import debounce from "lodash/debounce.js";
1✔
9
import {
1✔
10
    type EditableGridCell,
1✔
11
    type GridCell,
1✔
12
    GridCellKind,
1✔
13
    type GridSelection,
1✔
14
    isEditableGridCell,
1✔
15
    type Rectangle,
1✔
16
    isReadWriteCell,
1✔
17
    type InnerGridCell,
1✔
18
    InnerGridCellKind,
1✔
19
    CompactSelection,
1✔
20
    type Slice,
1✔
21
    isInnerOnlyCell,
1✔
22
    type ProvideEditorCallback,
1✔
23
    type GridColumn,
1✔
24
    isObjectEditorCallbackResult,
1✔
25
    type Item,
1✔
26
    type MarkerCell,
1✔
27
    headerCellUnheckedMarker,
1✔
28
    headerCellCheckedMarker,
1✔
29
    headerCellIndeterminateMarker,
1✔
30
    type ValidatedGridCell,
1✔
31
    type ImageEditorType,
1✔
32
    type CustomCell,
1✔
33
    BooleanEmpty,
1✔
34
    BooleanIndeterminate,
1✔
35
    type FillHandleDirection,
1✔
36
    type EditListItem,
1✔
37
} from "../internal/data-grid/data-grid-types.js";
1✔
38
import DataGridSearch, { type DataGridSearchProps } from "../internal/data-grid-search/data-grid-search.js";
1✔
39
import { browserIsOSX } from "../common/browser-detect.js";
1✔
40
import {
1✔
41
    getDataEditorTheme,
1✔
42
    makeCSSStyle,
1✔
43
    type FullTheme,
1✔
44
    type Theme,
1✔
45
    ThemeContext,
1✔
46
    mergeAndRealizeTheme,
1✔
47
} from "../common/styles.js";
1✔
48
import type { DataGridRef } from "../internal/data-grid/data-grid.js";
1✔
49
import { getScrollBarWidth, useEventListener, useStateWithReactiveInput, whenDefined } from "../common/utils.js";
1✔
50
import {
1✔
51
    isGroupEqual,
1✔
52
    itemsAreEqual,
1✔
53
    itemIsInRect,
1✔
54
    gridSelectionHasItem,
1✔
55
} from "../internal/data-grid/data-grid-lib.js";
1✔
56
import { GroupRename } from "./group-rename.js";
1✔
57
import { measureColumn, useColumnSizer } from "./use-column-sizer.js";
1✔
58
import { isHotkey } from "../common/is-hotkey.js";
1✔
59
import { type SelectionBlending, useSelectionBehavior } from "../internal/data-grid/use-selection-behavior.js";
1✔
60
import { useCellsForSelection } from "./use-cells-for-selection.js";
1✔
61
import { unquote, expandSelection, copyToClipboard, toggleBoolean } from "./data-editor-fns.js";
1✔
62
import { DataEditorContainer } from "../internal/data-editor-container/data-grid-container.js";
1✔
63
import { useAutoscroll } from "./use-autoscroll.js";
1✔
64
import type { CustomRenderer, CellRenderer, InternalCellRenderer } from "../cells/cell-types.js";
1✔
65
import { decodeHTML, type CopyBuffer } from "./copy-paste.js";
1✔
66
import { useRemAdjuster } from "./use-rem-adjuster.js";
1✔
67
import { type Highlight } from "../internal/data-grid/data-grid-render.js";
1✔
68
import { withAlpha } from "../internal/data-grid/color-parser.js";
1✔
69
import { combineRects, getClosestRect } from "../common/math.js";
1✔
70
import {
1✔
71
    type HeaderClickedEventArgs,
1✔
72
    type GroupHeaderClickedEventArgs,
1✔
73
    type CellClickedEventArgs,
1✔
74
    type FillPatternEventArgs,
1✔
75
    type GridMouseEventArgs,
1✔
76
    groupHeaderKind,
1✔
77
    outOfBoundsKind,
1✔
78
    type GridMouseCellEventArgs,
1✔
79
    headerKind,
1✔
80
    type GridDragEventArgs,
1✔
81
    mouseEventArgsAreEqual,
1✔
82
    type GridKeyEventArgs,
1✔
83
} from "../internal/data-grid/event-args.js";
1✔
84

1✔
85
const DataGridOverlayEditor = React.lazy(
1✔
86
    async () => await import("../internal/data-grid-overlay-editor/data-grid-overlay-editor.js")
1✔
87
);
1✔
88

1✔
89
let idCounter = 0;
1✔
90

1✔
91
interface MouseState {
1✔
92
    readonly previousSelection?: GridSelection;
1✔
93
    readonly fillHandle?: boolean;
1✔
94
}
1✔
95

1✔
96
type Props = Partial<
1✔
97
    Omit<
1✔
98
        DataGridSearchProps,
1✔
99
        | "accessibilityHeight"
1✔
100
        | "canvasRef"
1✔
101
        | "cellXOffset"
1✔
102
        | "cellYOffset"
1✔
103
        | "className"
1✔
104
        | "clientSize"
1✔
105
        | "columns"
1✔
106
        | "disabledRows"
1✔
107
        | "enableGroups"
1✔
108
        | "firstColAccessible"
1✔
109
        | "firstColSticky"
1✔
110
        | "freezeColumns"
1✔
111
        | "getCellContent"
1✔
112
        | "getCellRenderer"
1✔
113
        | "getCellsForSelection"
1✔
114
        | "gridRef"
1✔
115
        | "groupHeaderHeight"
1✔
116
        | "headerHeight"
1✔
117
        | "isFilling"
1✔
118
        | "isFocused"
1✔
119
        | "imageWindowLoader"
1✔
120
        | "lockColumns"
1✔
121
        | "maxColumnWidth"
1✔
122
        | "minColumnWidth"
1✔
123
        | "nonGrowWidth"
1✔
124
        | "onCanvasBlur"
1✔
125
        | "onCanvasFocused"
1✔
126
        | "onCellFocused"
1✔
127
        | "onContextMenu"
1✔
128
        | "onDragEnd"
1✔
129
        | "onMouseDown"
1✔
130
        | "onMouseMove"
1✔
131
        | "onMouseUp"
1✔
132
        | "onVisibleRegionChanged"
1✔
133
        | "rowHeight"
1✔
134
        | "rows"
1✔
135
        | "scrollRef"
1✔
136
        | "searchInputRef"
1✔
137
        | "selectedColumns"
1✔
138
        | "selection"
1✔
139
        | "theme"
1✔
140
        | "trailingRowType"
1✔
141
        | "translateX"
1✔
142
        | "translateY"
1✔
143
        | "verticalBorder"
1✔
144
    >
1✔
145
>;
1✔
146

1✔
147
type EmitEvents = "copy" | "paste" | "delete" | "fill-right" | "fill-down";
1✔
148

1✔
149
function getSpanStops(cells: readonly (readonly GridCell[])[]): number[] {
5✔
150
    return uniq(
5✔
151
        flatten(
5✔
152
            flatten(cells)
5✔
153
                .filter(c => c.span !== undefined)
5✔
154
                .map(c => range((c.span?.[0] ?? 0) + 1, (c.span?.[1] ?? 0) + 1))
5✔
155
        )
5✔
156
    );
5✔
157
}
5✔
158

1✔
159
function shiftSelection(input: GridSelection, offset: number): GridSelection {
283✔
160
    if (input === undefined || offset === 0 || (input.columns.length === 0 && input.current === undefined))
283✔
161
        return input;
283✔
162

35✔
163
    return {
35✔
164
        current:
35✔
165
            input.current === undefined
35✔
166
                ? undefined
1✔
167
                : {
34✔
168
                      cell: [input.current.cell[0] + offset, input.current.cell[1]],
34✔
169
                      range: {
34✔
170
                          ...input.current.range,
34✔
171
                          x: input.current.range.x + offset,
34✔
172
                      },
34✔
173
                      rangeStack: input.current.rangeStack.map(r => ({
34✔
174
                          ...r,
×
175
                          x: r.x + offset,
×
176
                      })),
34✔
177
                  },
34✔
178
        rows: input.rows,
283✔
179
        columns: input.columns.offset(offset),
283✔
180
    };
283✔
181
}
283✔
182

1✔
183
export interface Keybinds {
1✔
184
    readonly selectAll: boolean;
1✔
185
    readonly selectRow: boolean;
1✔
186
    readonly selectColumn: boolean;
1✔
187
    readonly downFill: boolean;
1✔
188
    readonly rightFill: boolean;
1✔
189
    readonly pageUp: boolean;
1✔
190
    readonly pageDown: boolean;
1✔
191
    readonly clear: boolean;
1✔
192
    readonly copy: boolean;
1✔
193
    readonly paste: boolean;
1✔
194
    readonly cut: boolean;
1✔
195
    readonly search: boolean;
1✔
196
    readonly first: boolean;
1✔
197
    readonly last: boolean;
1✔
198
}
1✔
199

1✔
200
const keybindingDefaults: Keybinds = {
1✔
201
    selectAll: true,
1✔
202
    selectRow: true,
1✔
203
    selectColumn: true,
1✔
204
    downFill: false,
1✔
205
    rightFill: false,
1✔
206
    pageUp: true,
1✔
207
    pageDown: true,
1✔
208
    clear: true,
1✔
209
    copy: true,
1✔
210
    paste: true,
1✔
211
    cut: true,
1✔
212
    search: false,
1✔
213
    first: true,
1✔
214
    last: true,
1✔
215
};
1✔
216

1✔
217
/**
1✔
218
 * @category DataEditor
1✔
219
 */
1✔
220
export interface DataEditorProps extends Props, Pick<DataGridSearchProps, "imageWindowLoader"> {
1✔
221
    /** Emitted whenever the user has requested the deletion of the selection.
1✔
222
     * @group Editing
1✔
223
     */
1✔
224
    readonly onDelete?: (selection: GridSelection) => boolean | GridSelection;
1✔
225
    /** Emitted whenever a cell edit is completed.
1✔
226
     * @group Editing
1✔
227
     */
1✔
228
    readonly onCellEdited?: (cell: Item, newValue: EditableGridCell) => void;
1✔
229
    /** Emitted whenever a cell mutation is completed and provides all edits inbound as a single batch.
1✔
230
     * @group Editing
1✔
231
     */
1✔
232
    readonly onCellsEdited?: (newValues: readonly EditListItem[]) => boolean | void;
1✔
233
    /** Emitted whenever a row append operation is requested. Append location can be set in callback.
1✔
234
     * @group Editing
1✔
235
     */
1✔
236
    readonly onRowAppended?: () => Promise<"top" | "bottom" | number | undefined> | void;
1✔
237
    /** Emitted when a column header should show a context menu. Usually right click.
1✔
238
     * @group Events
1✔
239
     */
1✔
240
    readonly onHeaderClicked?: (colIndex: number, event: HeaderClickedEventArgs) => void;
1✔
241
    /** Emitted when a group header is clicked.
1✔
242
     * @group Events
1✔
243
     */
1✔
244
    readonly onGroupHeaderClicked?: (colIndex: number, event: GroupHeaderClickedEventArgs) => void;
1✔
245
    /** Emitted whe the user wishes to rename a group.
1✔
246
     * @group Events
1✔
247
     */
1✔
248
    readonly onGroupHeaderRenamed?: (groupName: string, newVal: string) => void;
1✔
249
    /** Emitted when a cell is clicked.
1✔
250
     * @group Events
1✔
251
     */
1✔
252
    readonly onCellClicked?: (cell: Item, event: CellClickedEventArgs) => void;
1✔
253
    /** Emitted when a cell is activated, by pressing Enter, Space or double clicking it.
1✔
254
     * @group Events
1✔
255
     */
1✔
256
    readonly onCellActivated?: (cell: Item) => void;
1✔
257

1✔
258
    /**
1✔
259
     * Emitted whenever the user initiats a pattern fill using the fill handle. This event provides both
1✔
260
     * a patternSource region and a fillDestination region, and can be prevented.
1✔
261
     * @group Editing
1✔
262
     */
1✔
263
    readonly onFillPattern?: (event: FillPatternEventArgs) => void;
1✔
264
    /** Emitted when editing has finished, regardless of data changing or not.
1✔
265
     * @group Editing
1✔
266
     */
1✔
267
    readonly onFinishedEditing?: (newValue: GridCell | undefined, movement: Item) => void;
1✔
268
    /** Emitted when a column header should show a context menu. Usually right click.
1✔
269
     * @group Events
1✔
270
     */
1✔
271
    readonly onHeaderContextMenu?: (colIndex: number, event: HeaderClickedEventArgs) => void;
1✔
272
    /** Emitted when a group header should show a context menu. Usually right click.
1✔
273
     * @group Events
1✔
274
     */
1✔
275
    readonly onGroupHeaderContextMenu?: (colIndex: number, event: GroupHeaderClickedEventArgs) => void;
1✔
276
    /** Emitted when a cell should show a context menu. Usually right click.
1✔
277
     * @group Events
1✔
278
     */
1✔
279
    readonly onCellContextMenu?: (cell: Item, event: CellClickedEventArgs) => void;
1✔
280
    /** Used for validating cell values during editing.
1✔
281
     * @group Editing
1✔
282
     * @param cell The cell which is being validated.
1✔
283
     * @param newValue The new value being proposed.
1✔
284
     * @param prevValue The previous value before the edit.
1✔
285
     * @returns A return of false indicates the value will not be accepted. A value of
1✔
286
     * true indicates the value will be accepted. Returning a new GridCell will immediately coerce the value to match.
1✔
287
     */
1✔
288
    readonly validateCell?: (
1✔
289
        cell: Item,
1✔
290
        newValue: EditableGridCell,
1✔
291
        prevValue: GridCell
1✔
292
    ) => boolean | ValidatedGridCell;
1✔
293

1✔
294
    /** The columns to display in the data grid.
1✔
295
     * @group Data
1✔
296
     */
1✔
297
    readonly columns: readonly GridColumn[];
1✔
298

1✔
299
    /** Controls the trailing row used to insert new data into the grid.
1✔
300
     * @group Editing
1✔
301
     */
1✔
302
    readonly trailingRowOptions?: {
1✔
303
        /** If the trailing row should be tinted */
1✔
304
        readonly tint?: boolean;
1✔
305
        /** A hint string displayed on hover. Usually something like "New row" */
1✔
306
        readonly hint?: string;
1✔
307
        /** When set to true, the trailing row is always visible. */
1✔
308
        readonly sticky?: boolean;
1✔
309
        /** The icon to use for the cell. Either a GridColumnIcon or a member of the passed headerIcons */
1✔
310
        readonly addIcon?: string;
1✔
311
        /** Overrides the column to focus when a new row is created. */
1✔
312
        readonly targetColumn?: number | GridColumn;
1✔
313
    };
1✔
314
    /** Controls the height of the header row
1✔
315
     * @defaultValue 36
1✔
316
     * @group Style
1✔
317
     */
1✔
318
    readonly headerHeight?: number;
1✔
319
    /** Controls the header of the group header row
1✔
320
     * @defaultValue `headerHeight`
1✔
321
     * @group Style
1✔
322
     */
1✔
323
    readonly groupHeaderHeight?: number;
1✔
324

1✔
325
    /**
1✔
326
     * The number of rows in the grid.
1✔
327
     * @group Data
1✔
328
     */
1✔
329
    readonly rows: number;
1✔
330

1✔
331
    /** Determines if row markers should be automatically added to the grid.
1✔
332
     * Interactive row markers allow the user to select a row.
1✔
333
     *
1✔
334
     * - "clickable-number" renders a number that can be clicked to
1✔
335
     *   select the row
1✔
336
     * - "both" causes the row marker to show up as a number but
1✔
337
     *   reveal a checkbox when the marker is hovered.
1✔
338
     *
1✔
339
     * @defaultValue `none`
1✔
340
     * @group Style
1✔
341
     */
1✔
342
    readonly rowMarkers?: "checkbox" | "number" | "clickable-number" | "checkbox-visible" | "both" | "none";
1✔
343
    /**
1✔
344
     * Sets the width of row markers in pixels, if unset row markers will automatically size.
1✔
345
     * @group Style
1✔
346
     */
1✔
347
    readonly rowMarkerWidth?: number;
1✔
348
    /** Changes the starting index for row markers.
1✔
349
     * @defaultValue 1
1✔
350
     * @group Style
1✔
351
     */
1✔
352
    readonly rowMarkerStartIndex?: number;
1✔
353

1✔
354
    /** Changes the theme of the row marker column
1✔
355
     * @group Style
1✔
356
     */
1✔
357
    readonly rowMarkerTheme?: Partial<Theme>;
1✔
358

1✔
359
    /** Sets the width of the data grid.
1✔
360
     * @group Style
1✔
361
     */
1✔
362
    readonly width?: number | string;
1✔
363
    /** Sets the height of the data grid.
1✔
364
     * @group Style
1✔
365
     */
1✔
366
    readonly height?: number | string;
1✔
367
    /** Custom classname for data grid wrapper.
1✔
368
     * @group Style
1✔
369
     */
1✔
370
    readonly className?: string;
1✔
371

1✔
372
    /** If set to `default`, `gridSelection` will be coerced to always include full spans.
1✔
373
     * @group Selection
1✔
374
     * @defaultValue `default`
1✔
375
     */
1✔
376
    readonly spanRangeBehavior?: "default" | "allowPartial";
1✔
377

1✔
378
    /** Controls which types of selections can exist at the same time in the grid. If selection blending is set to
1✔
379
     * exclusive, the grid will clear other types of selections when the exclusive selection is made. By default row,
1✔
380
     * column, and range selections are exclusive.
1✔
381
     * @group Selection
1✔
382
     * @defaultValue `exclusive`
1✔
383
     * */
1✔
384
    readonly rangeSelectionBlending?: SelectionBlending;
1✔
385
    /** {@inheritDoc rangeSelectionBlending}
1✔
386
     * @group Selection
1✔
387
     */
1✔
388
    readonly columnSelectionBlending?: SelectionBlending;
1✔
389
    /** {@inheritDoc rangeSelectionBlending}
1✔
390
     * @group Selection
1✔
391
     */
1✔
392
    readonly rowSelectionBlending?: SelectionBlending;
1✔
393
    /** Controls if multi-selection is allowed. If disabled, shift/ctrl/command clicking will work as if no modifiers
1✔
394
     * are pressed.
1✔
395
     *
1✔
396
     * When range select is set to cell, only one cell may be selected at a time. When set to rect one one rect at a
1✔
397
     * time. The multi variants allow for multiples of the rect or cell to be selected.
1✔
398
     * @group Selection
1✔
399
     * @defaultValue `rect`
1✔
400
     */
1✔
401
    readonly rangeSelect?: "none" | "cell" | "rect" | "multi-cell" | "multi-rect";
1✔
402
    /** {@inheritDoc rangeSelect}
1✔
403
     * @group Selection
1✔
404
     * @defaultValue `multi`
1✔
405
     */
1✔
406
    readonly columnSelect?: "none" | "single" | "multi";
1✔
407
    /** {@inheritDoc rangeSelect}
1✔
408
     * @group Selection
1✔
409
     * @defaultValue `multi`
1✔
410
     */
1✔
411
    readonly rowSelect?: "none" | "single" | "multi";
1✔
412

1✔
413
    /** Sets the initial scroll Y offset.
1✔
414
     * @see {@link scrollOffsetX}
1✔
415
     * @group Advanced
1✔
416
     */
1✔
417
    readonly scrollOffsetY?: number;
1✔
418
    /** Sets the initial scroll X offset
1✔
419
     * @see {@link scrollOffsetY}
1✔
420
     * @group Advanced
1✔
421
     */
1✔
422
    readonly scrollOffsetX?: number;
1✔
423

1✔
424
    /** Determins the height of each row.
1✔
425
     * @group Style
1✔
426
     * @defaultValue 34
1✔
427
     */
1✔
428
    readonly rowHeight?: DataGridSearchProps["rowHeight"];
1✔
429
    /** Fires whenever the mouse moves
1✔
430
     * @group Events
1✔
431
     * @param args
1✔
432
     */
1✔
433
    readonly onMouseMove?: DataGridSearchProps["onMouseMove"];
1✔
434

1✔
435
    /**
1✔
436
     * The minimum width a column can be resized to.
1✔
437
     * @defaultValue 50
1✔
438
     * @group Style
1✔
439
     */
1✔
440
    readonly minColumnWidth?: DataGridSearchProps["minColumnWidth"];
1✔
441
    /**
1✔
442
     * The maximum width a column can be resized to.
1✔
443
     * @defaultValue 500
1✔
444
     * @group Style
1✔
445
     */
1✔
446
    readonly maxColumnWidth?: DataGridSearchProps["maxColumnWidth"];
1✔
447
    /**
1✔
448
     * The maximum width a column can be automatically sized to.
1✔
449
     * @defaultValue `maxColumnWidth`
1✔
450
     * @group Style
1✔
451
     */
1✔
452
    readonly maxColumnAutoWidth?: number;
1✔
453

1✔
454
    /**
1✔
455
     * Used to provide an override to the default image editor for the data grid. `provideEditor` may be a better
1✔
456
     * choice for most people.
1✔
457
     * @group Advanced
1✔
458
     * */
1✔
459
    readonly imageEditorOverride?: ImageEditorType;
1✔
460
    /**
1✔
461
     * If specified, it will be used to render Markdown, instead of the default Markdown renderer used by the Grid.
1✔
462
     * You'll want to use this if you need to process your Markdown for security purposes, or if you want to use a
1✔
463
     * renderer with different Markdown features.
1✔
464
     * @group Advanced
1✔
465
     */
1✔
466
    readonly markdownDivCreateNode?: (content: string) => DocumentFragment;
1✔
467

1✔
468
    /** Callback for providing a custom editor for a cell.
1✔
469
     * @group Editing
1✔
470
     */
1✔
471
    readonly provideEditor?: ProvideEditorCallback<GridCell>;
1✔
472
    /**
1✔
473
     * Allows coercion of pasted values.
1✔
474
     * @group Editing
1✔
475
     * @param val The pasted value
1✔
476
     * @param cell The cell being pasted into
1✔
477
     * @returns `undefined` to accept default behavior or a `GridCell` which should be used to represent the pasted value.
1✔
478
     */
1✔
479
    readonly coercePasteValue?: (val: string, cell: GridCell) => GridCell | undefined;
1✔
480

1✔
481
    /**
1✔
482
     * Emitted when the grid selection is cleared.
1✔
483
     * @group Selection
1✔
484
     */
1✔
485
    readonly onSelectionCleared?: () => void;
1✔
486

1✔
487
    /**
1✔
488
     * The current selection of the data grid. Contains all selected cells, ranges, rows, and columns.
1✔
489
     * Used in conjunction with {@link onGridSelectionChange}
1✔
490
     * method to implement a controlled selection.
1✔
491
     * @group Selection
1✔
492
     */
1✔
493
    readonly gridSelection?: GridSelection;
1✔
494
    /**
1✔
495
     * Emitted whenever the grid selection changes. Specifying
1✔
496
     * this function will make the grid’s selection controlled, so
1✔
497
     * so you will need to specify {@link gridSelection} as well. See
1✔
498
     * the "Controlled Selection" example for details.
1✔
499
     *
1✔
500
     * @param newSelection The new gridSelection as created by user input.
1✔
501
     * @group Selection
1✔
502
     */
1✔
503
    readonly onGridSelectionChange?: (newSelection: GridSelection) => void;
1✔
504
    /**
1✔
505
     * Emitted whenever the visible cells change, usually due to scrolling.
1✔
506
     * @group Events
1✔
507
     * @param range An inclusive range of all visible cells. May include cells obscured by UI elements such
1✔
508
     * as headers.
1✔
509
     * @param tx The x transform of the cell region.
1✔
510
     * @param ty The y transform of the cell region.
1✔
511
     * @param extras Contains information about the selected cell and
1✔
512
     * any visible freeze columns.
1✔
513
     */
1✔
514
    readonly onVisibleRegionChanged?: (
1✔
515
        range: Rectangle,
1✔
516
        tx: number,
1✔
517
        ty: number,
1✔
518
        extras: {
1✔
519
            /** The selected item if visible */
1✔
520
            selected?: Item;
1✔
521
            /** A selection of visible freeze columns */
1✔
522
            freezeRegion?: Rectangle;
1✔
523
        }
1✔
524
    ) => void;
1✔
525

1✔
526
    /**
1✔
527
     * The primary callback for getting cell data into the data grid.
1✔
528
     * @group Data
1✔
529
     * @param cell The location of the cell being requested.
1✔
530
     * @returns A valid GridCell to be rendered by the Grid.
1✔
531
     */
1✔
532
    readonly getCellContent: (cell: Item) => GridCell;
1✔
533
    /**
1✔
534
     * Determines if row selection requires a modifier key to enable multi-selection or not. In auto mode it adapts to
1✔
535
     * touch or mouse environments automatically, in multi-mode it always acts as if the multi key (Ctrl) is pressed.
1✔
536
     * @group Editing
1✔
537
     * @defaultValue `auto`
1✔
538
     */
1✔
539
    readonly rowSelectionMode?: "auto" | "multi";
1✔
540

1✔
541
    /**
1✔
542
     * Add table headers to copied data.
1✔
543
     * @group Editing
1✔
544
     * @defaultValue `false`
1✔
545
     */
1✔
546
    readonly copyHeaders?: boolean;
1✔
547

1✔
548
    /**
1✔
549
     * Determins which keybindings are enabled.
1✔
550
     * @group Editing
1✔
551
     * @defaultValue is
1✔
552

1✔
553
            {
1✔
554
                selectAll: true,
1✔
555
                selectRow: true,
1✔
556
                selectColumn: true,
1✔
557
                downFill: false,
1✔
558
                rightFill: false,
1✔
559
                pageUp: false,
1✔
560
                pageDown: false,
1✔
561
                clear: true,
1✔
562
                copy: true,
1✔
563
                paste: true,
1✔
564
                search: false,
1✔
565
                first: true,
1✔
566
                last: true,
1✔
567
            }
1✔
568
     */
1✔
569
    readonly keybindings?: Partial<Keybinds>;
1✔
570

1✔
571
    /**
1✔
572
     * Used to fetch large amounts of cells at once. Used for copy/paste, if unset copy will not work.
1✔
573
     *
1✔
574
     * `getCellsForSelection` is called when the user copies a selection to the clipboard or the data editor needs to
1✔
575
     * inspect data which may be outside the curently visible range. It must return a two-dimensional array (an array of
1✔
576
     * rows, where each row is an array of cells) of the cells in the selection's rectangle. Note that the rectangle can
1✔
577
     * include cells that are not currently visible.
1✔
578
     *
1✔
579
     * If `true` is passed instead of a callback, the data grid will internally use the `getCellContent` callback to
1✔
580
     * provide a basic implementation of `getCellsForSelection`. This can make it easier to light up more data grid
1✔
581
     * functionality, but may have negative side effects if your data source is not able to handle being queried for
1✔
582
     * data outside the normal window.
1✔
583
     *
1✔
584
     * If `getCellsForSelection` returns a thunk, the data may be loaded asynchronously, however the data grid may be
1✔
585
     * unable to properly react to column spans when performing range selections. Copying large amounts of data out of
1✔
586
     * the grid will depend on the performance of the thunk as well.
1✔
587
     * @group Data
1✔
588
     * @param {Rectangle} selection The range of requested cells
1✔
589
     * @param {AbortSignal} abortSignal A signal indicating the requested cells are no longer needed
1✔
590
     * @returns A row-major collection of cells or an async thunk which returns a row-major collection.
1✔
591
     */
1✔
592
    readonly getCellsForSelection?: DataGridSearchProps["getCellsForSelection"] | true;
1✔
593

1✔
594
    /** The number of columns which should remain in place when scrolling horizontally. The row marker column, if
1✔
595
     * enabled is always frozen and is not included in this count.
1✔
596
     * @defaultValue 0
1✔
597
     * @group Style
1✔
598
     */
1✔
599
    readonly freezeColumns?: DataGridSearchProps["freezeColumns"];
1✔
600

1✔
601
    /**
1✔
602
     * Controls the drawing of the left hand vertical border of a column. If set to a boolean value it controls all
1✔
603
     * borders.
1✔
604
     * @defaultValue `true`
1✔
605
     * @group Style
1✔
606
     */
1✔
607
    readonly verticalBorder?: DataGridSearchProps["verticalBorder"] | boolean;
1✔
608

1✔
609
    /**
1✔
610
     * Called when data is pasted into the grid. If left undefined, the `DataEditor` will operate in a
1✔
611
     * fallback mode and attempt to paste the text buffer into the current cell assuming the current cell is not
1✔
612
     * readonly and can accept the data type. If `onPaste` is set to false or the function returns false, the grid will
1✔
613
     * simply ignore paste. If `onPaste` evaluates to true the grid will attempt to split the data by tabs and newlines
1✔
614
     * and paste into available cells.
1✔
615
     *
1✔
616
     * The grid will not attempt to add additional rows if more data is pasted then can fit. In that case it is
1✔
617
     * advisable to simply return false from onPaste and handle the paste manually.
1✔
618
     * @group Editing
1✔
619
     */
1✔
620
    readonly onPaste?: ((target: Item, values: readonly (readonly string[])[]) => boolean) | boolean;
1✔
621

1✔
622
    /**
1✔
623
     * The theme used by the data grid to get all color and font information
1✔
624
     * @group Style
1✔
625
     */
1✔
626
    readonly theme?: Partial<Theme>;
1✔
627

1✔
628
    readonly renderers?: readonly InternalCellRenderer<InnerGridCell>[];
1✔
629

1✔
630
    /**
1✔
631
     * An array of custom renderers which can be used to extend the data grid.
1✔
632
     * @group Advanced
1✔
633
     */
1✔
634
    readonly customRenderers?: readonly CustomRenderer<any>[];
1✔
635

1✔
636
    /**
1✔
637
     * Scales most elements in the theme to match rem scaling automatically
1✔
638
     * @defaultValue false
1✔
639
     */
1✔
640
    readonly scaleToRem?: boolean;
1✔
641

1✔
642
    /**
1✔
643
     * Custom predicate function to decide whether the click event occurred outside the grid
1✔
644
     * Especially used when custom editor is opened with the portal and is outside the grid, but there is no possibility
1✔
645
     * to add a class "click-outside-ignore"
1✔
646
     * If this function is supplied and returns false, the click event is ignored
1✔
647
     */
1✔
648
    readonly isOutsideClick?: (e: MouseEvent | TouchEvent) => boolean;
1✔
649

1✔
650
    /**
1✔
651
     * Controls which directions fill is allowed in.
1✔
652
     */
1✔
653
    readonly allowedFillDirections?: FillHandleDirection;
1✔
654

1✔
655
    /**
1✔
656
     * Determins when a cell is considered activated
1✔
657
     */
1✔
658
    readonly cellActivationBehavior?: "double-click" | "single-click" | "second-click";
1✔
659
}
1✔
660

1✔
661
type ScrollToFn = (
1✔
662
    col: number | { amount: number; unit: "cell" | "px" },
1✔
663
    row: number | { amount: number; unit: "cell" | "px" },
1✔
664
    dir?: "horizontal" | "vertical" | "both",
1✔
665
    paddingX?: number,
1✔
666
    paddingY?: number,
1✔
667
    options?: {
1✔
668
        hAlign?: "start" | "center" | "end";
1✔
669
        vAlign?: "start" | "center" | "end";
1✔
670
    }
1✔
671
) => void;
1✔
672

1✔
673
/** @category DataEditor */
1✔
674
export interface DataEditorRef {
1✔
675
    /**
1✔
676
     * Programatically appends a row.
1✔
677
     * @param col The column index to focus in the new row.
1✔
678
     * @returns A promise which waits for the append to complete.
1✔
679
     */
1✔
680
    appendRow: (col: number, openOverlay?: boolean) => Promise<void>;
1✔
681
    /**
1✔
682
     * Triggers cells to redraw.
1✔
683
     */
1✔
684
    updateCells: DataGridRef["damage"];
1✔
685
    /**
1✔
686
     * Gets the screen space bounds of the requested item.
1✔
687
     */
1✔
688
    getBounds: DataGridRef["getBounds"];
1✔
689
    /**
1✔
690
     * Triggers the data grid to focus itself or the correct accessibility element.
1✔
691
     */
1✔
692
    focus: DataGridRef["focus"];
1✔
693
    /**
1✔
694
     * Generic API for emitting events as if they had been triggered via user interaction.
1✔
695
     */
1✔
696
    emit: (eventName: EmitEvents) => Promise<void>;
1✔
697
    /**
1✔
698
     * Scrolls to the desired cell or location in the grid.
1✔
699
     */
1✔
700
    scrollTo: ScrollToFn;
1✔
701
    /**
1✔
702
     * Causes the columns in the selection to have their natural size recomputed and re-emitted as a resize event.
1✔
703
     */
1✔
704
    remeasureColumns: (cols: CompactSelection) => void;
1✔
705
}
1✔
706

1✔
707
const loadingCell: GridCell = {
1✔
708
    kind: GridCellKind.Loading,
1✔
709
    allowOverlay: false,
1✔
710
};
1✔
711

1✔
712
const emptyGridSelection: GridSelection = {
1✔
713
    columns: CompactSelection.empty(),
1✔
714
    rows: CompactSelection.empty(),
1✔
715
    current: undefined,
1✔
716
};
1✔
717

1✔
718
const DataEditorImpl: React.ForwardRefRenderFunction<DataEditorRef, DataEditorProps> = (p, forwardedRef) => {
1✔
719
    const [gridSelectionInner, setGridSelectionInner] = React.useState<GridSelection>(emptyGridSelection);
678✔
720
    const [overlay, setOverlay] = React.useState<{
678✔
721
        target: Rectangle;
678✔
722
        content: GridCell;
678✔
723
        theme: FullTheme;
678✔
724
        initialValue: string | undefined;
678✔
725
        cell: Item;
678✔
726
        highlight: boolean;
678✔
727
        forceEditMode: boolean;
678✔
728
    }>();
678✔
729
    const searchInputRef = React.useRef<HTMLInputElement | null>(null);
678✔
730
    const canvasRef = React.useRef<HTMLCanvasElement | null>(null);
678✔
731
    const [mouseState, setMouseState] = React.useState<MouseState>();
678✔
732
    const scrollRef = React.useRef<HTMLDivElement | null>(null);
678✔
733
    const lastSent = React.useRef<[number, number]>();
678✔
734

678✔
735
    const safeWindow = typeof window === "undefined" ? null : window;
678!
736

678✔
737
    const {
678✔
738
        rowMarkers = "none",
678✔
739
        rowMarkerWidth: rowMarkerWidthRaw,
678✔
740
        imageEditorOverride,
678✔
741
        getRowThemeOverride,
678✔
742
        markdownDivCreateNode,
678✔
743
        width,
678✔
744
        height,
678✔
745
        columns: columnsIn,
678✔
746
        rows,
678✔
747
        getCellContent,
678✔
748
        onCellClicked,
678✔
749
        onCellActivated,
678✔
750
        onFillPattern,
678✔
751
        onFinishedEditing,
678✔
752
        coercePasteValue,
678✔
753
        drawHeader: drawHeaderIn,
678✔
754
        drawCell: drawCellIn,
678✔
755
        onHeaderClicked,
678✔
756
        onColumnProposeMove,
678✔
757
        spanRangeBehavior = "default",
678✔
758
        onGroupHeaderClicked,
678✔
759
        onCellContextMenu,
678✔
760
        className,
678✔
761
        onHeaderContextMenu,
678✔
762
        getCellsForSelection: getCellsForSelectionIn,
678✔
763
        onGroupHeaderContextMenu,
678✔
764
        onGroupHeaderRenamed,
678✔
765
        onCellEdited,
678✔
766
        onCellsEdited,
678✔
767
        onSearchResultsChanged: onSearchResultsChangedIn,
678✔
768
        searchResults,
678✔
769
        onSearchValueChange,
678✔
770
        searchValue,
678✔
771
        onKeyDown: onKeyDownIn,
678✔
772
        onKeyUp: onKeyUpIn,
678✔
773
        keybindings: keybindingsIn,
678✔
774
        onRowAppended,
678✔
775
        onColumnMoved,
678✔
776
        validateCell: validateCellIn,
678✔
777
        highlightRegions: highlightRegionsIn,
678✔
778
        rangeSelect = "rect",
678✔
779
        columnSelect = "multi",
678✔
780
        rowSelect = "multi",
678✔
781
        rangeSelectionBlending = "exclusive",
678✔
782
        columnSelectionBlending = "exclusive",
678✔
783
        rowSelectionBlending = "exclusive",
678✔
784
        onDelete: onDeleteIn,
678✔
785
        onDragStart,
678✔
786
        onMouseMove,
678✔
787
        onPaste,
678✔
788
        copyHeaders = false,
678✔
789
        freezeColumns = 0,
678✔
790
        cellActivationBehavior = "second-click",
678✔
791
        rowSelectionMode = "auto",
678✔
792
        rowMarkerStartIndex = 1,
678✔
793
        rowMarkerTheme,
678✔
794
        onHeaderMenuClick,
678✔
795
        getGroupDetails,
678✔
796
        onSearchClose: onSearchCloseIn,
678✔
797
        onItemHovered,
678✔
798
        onSelectionCleared,
678✔
799
        showSearch: showSearchIn,
678✔
800
        onVisibleRegionChanged,
678✔
801
        gridSelection: gridSelectionOuter,
678✔
802
        onGridSelectionChange,
678✔
803
        minColumnWidth: minColumnWidthIn = 50,
678✔
804
        maxColumnWidth: maxColumnWidthIn = 500,
678✔
805
        maxColumnAutoWidth: maxColumnAutoWidthIn,
678✔
806
        provideEditor,
678✔
807
        trailingRowOptions,
678✔
808
        allowedFillDirections = "orthogonal",
678✔
809
        scrollOffsetX,
678✔
810
        scrollOffsetY,
678✔
811
        verticalBorder,
678✔
812
        onDragOverCell,
678✔
813
        onDrop,
678✔
814
        onColumnResize: onColumnResizeIn,
678✔
815
        onColumnResizeEnd: onColumnResizeEndIn,
678✔
816
        onColumnResizeStart: onColumnResizeStartIn,
678✔
817
        customRenderers: additionalRenderers,
678✔
818
        fillHandle,
678✔
819
        drawFocusRing,
678✔
820
        experimental,
678✔
821
        fixedShadowX,
678✔
822
        fixedShadowY,
678✔
823
        headerIcons,
678✔
824
        imageWindowLoader,
678✔
825
        initialSize,
678✔
826
        isDraggable,
678✔
827
        onDragLeave,
678✔
828
        onRowMoved,
678✔
829
        overscrollX: overscrollXIn,
678✔
830
        overscrollY: overscrollYIn,
678✔
831
        preventDiagonalScrolling,
678✔
832
        rightElement,
678✔
833
        rightElementProps,
678✔
834
        smoothScrollX,
678✔
835
        smoothScrollY,
678✔
836
        scaleToRem = false,
678✔
837
        rowHeight: rowHeightIn = 34,
678✔
838
        headerHeight: headerHeightIn = 36,
678✔
839
        groupHeaderHeight: groupHeaderHeightIn = headerHeightIn,
678✔
840
        theme: themeIn,
678✔
841
        isOutsideClick,
678✔
842
        renderers,
678✔
843
    } = p;
678✔
844

678✔
845
    const minColumnWidth = Math.max(minColumnWidthIn, 20);
678✔
846
    const maxColumnWidth = Math.max(maxColumnWidthIn, minColumnWidth);
678✔
847
    const maxColumnAutoWidth = Math.max(maxColumnAutoWidthIn ?? maxColumnWidth, minColumnWidth);
678✔
848

678✔
849
    const docStyle = React.useMemo(() => {
678✔
850
        if (typeof window === "undefined") return { fontSize: "16px" };
137!
851
        return window.getComputedStyle(document.documentElement);
137✔
852
    }, []);
678✔
853

678✔
854
    const fontSizeStr = docStyle.fontSize;
678✔
855

678✔
856
    const remSize = React.useMemo(() => Number.parseFloat(fontSizeStr), [fontSizeStr]);
678✔
857

678✔
858
    const { rowHeight, headerHeight, groupHeaderHeight, theme, overscrollX, overscrollY } = useRemAdjuster({
678✔
859
        groupHeaderHeight: groupHeaderHeightIn,
678✔
860
        headerHeight: headerHeightIn,
678✔
861
        overscrollX: overscrollXIn,
678✔
862
        overscrollY: overscrollYIn,
678✔
863
        remSize,
678✔
864
        rowHeight: rowHeightIn,
678✔
865
        scaleToRem,
678✔
866
        theme: themeIn,
678✔
867
    });
678✔
868

678✔
869
    const keybindings = React.useMemo(() => {
678✔
870
        return keybindingsIn === undefined
137✔
871
            ? keybindingDefaults
134✔
872
            : {
3✔
873
                  ...keybindingDefaults,
3✔
874
                  ...keybindingsIn,
3✔
875
              };
3✔
876
    }, [keybindingsIn]);
678✔
877

678✔
878
    const rowMarkerWidth = rowMarkerWidthRaw ?? (rows > 10_000 ? 48 : rows > 1000 ? 44 : rows > 100 ? 36 : 32);
678!
879
    const hasRowMarkers = rowMarkers !== "none";
678✔
880
    const rowMarkerOffset = hasRowMarkers ? 1 : 0;
678✔
881
    const showTrailingBlankRow = onRowAppended !== undefined;
678✔
882
    const lastRowSticky = trailingRowOptions?.sticky === true;
678✔
883

678✔
884
    const [showSearchInner, setShowSearchInner] = React.useState(false);
678✔
885
    const showSearch = showSearchIn ?? showSearchInner;
678✔
886

678✔
887
    const onSearchClose = React.useCallback(() => {
678✔
888
        if (onSearchCloseIn !== undefined) {
2✔
889
            onSearchCloseIn();
2✔
890
        } else {
2!
UNCOV
891
            setShowSearchInner(false);
×
892
        }
×
893
    }, [onSearchCloseIn]);
678✔
894

678✔
895
    const gridSelectionOuterMangled: GridSelection | undefined = React.useMemo((): GridSelection | undefined => {
678✔
896
        return gridSelectionOuter === undefined ? undefined : shiftSelection(gridSelectionOuter, rowMarkerOffset);
262✔
897
    }, [gridSelectionOuter, rowMarkerOffset]);
678✔
898
    const gridSelection = gridSelectionOuterMangled ?? gridSelectionInner;
678✔
899

678✔
900
    const abortControllerRef = React.useRef(new AbortController());
678✔
901
    React.useEffect(() => {
678✔
902
        return () => {
137✔
903
            // eslint-disable-next-line react-hooks/exhaustive-deps
137✔
904
            abortControllerRef?.current.abort();
137✔
905
        };
137✔
906
    }, []);
678✔
907

678✔
908
    const [getCellsForSelection, getCellsForSeletionDirect] = useCellsForSelection(
678✔
909
        getCellsForSelectionIn,
678✔
910
        getCellContent,
678✔
911
        rowMarkerOffset,
678✔
912
        abortControllerRef.current,
678✔
913
        rows
678✔
914
    );
678✔
915

678✔
916
    const validateCell = React.useCallback<NonNullable<typeof validateCellIn>>(
678✔
917
        (cell, newValue, prevValue) => {
678✔
918
            if (validateCellIn === undefined) return true;
12✔
919
            const item: Item = [cell[0] - rowMarkerOffset, cell[1]];
1✔
920
            return validateCellIn?.(item, newValue, prevValue);
1✔
921
        },
12✔
922
        [rowMarkerOffset, validateCellIn]
678✔
923
    );
678✔
924

678✔
925
    const expectedExternalGridSelection = React.useRef<GridSelection | undefined>(gridSelectionOuter);
678✔
926
    const setGridSelection = React.useCallback(
678✔
927
        (newVal: GridSelection, expand: boolean): void => {
678✔
928
            if (expand) {
172✔
929
                newVal = expandSelection(
130✔
930
                    newVal,
130✔
931
                    getCellsForSelection,
130✔
932
                    rowMarkerOffset,
130✔
933
                    spanRangeBehavior,
130✔
934
                    abortControllerRef.current
130✔
935
                );
130✔
936
            }
130✔
937
            if (onGridSelectionChange !== undefined) {
172✔
938
                expectedExternalGridSelection.current = shiftSelection(newVal, -rowMarkerOffset);
129✔
939
                onGridSelectionChange(expectedExternalGridSelection.current);
129✔
940
            } else {
172✔
941
                setGridSelectionInner(newVal);
43✔
942
            }
43✔
943
        },
172✔
944
        [onGridSelectionChange, getCellsForSelection, rowMarkerOffset, spanRangeBehavior]
678✔
945
    );
678✔
946

678✔
947
    const onColumnResize = whenDefined(
678✔
948
        onColumnResizeIn,
678✔
949
        React.useCallback<NonNullable<typeof onColumnResizeIn>>(
678✔
950
            (_, w, ind, wg) => {
678✔
951
                onColumnResizeIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
11✔
952
            },
11✔
953
            [onColumnResizeIn, rowMarkerOffset, columnsIn]
678✔
954
        )
678✔
955
    );
678✔
956

678✔
957
    const onColumnResizeEnd = whenDefined(
678✔
958
        onColumnResizeEndIn,
678✔
959
        React.useCallback<NonNullable<typeof onColumnResizeEndIn>>(
678✔
960
            (_, w, ind, wg) => {
678✔
961
                onColumnResizeEndIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
2✔
962
            },
2✔
963
            [onColumnResizeEndIn, rowMarkerOffset, columnsIn]
678✔
964
        )
678✔
965
    );
678✔
966

678✔
967
    const onColumnResizeStart = whenDefined(
678✔
968
        onColumnResizeStartIn,
678✔
969
        React.useCallback<NonNullable<typeof onColumnResizeStartIn>>(
678✔
970
            (_, w, ind, wg) => {
678✔
UNCOV
971
                onColumnResizeStartIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
×
972
            },
×
973
            [onColumnResizeStartIn, rowMarkerOffset, columnsIn]
678✔
974
        )
678✔
975
    );
678✔
976

678✔
977
    const drawHeader = whenDefined(
678✔
978
        drawHeaderIn,
678✔
979
        React.useCallback<NonNullable<typeof drawHeaderIn>>(
678✔
980
            (args, draw) => {
678✔
UNCOV
981
                return drawHeaderIn?.({ ...args, columnIndex: args.columnIndex - rowMarkerOffset }, draw) ?? false;
×
982
            },
×
983
            [drawHeaderIn, rowMarkerOffset]
678✔
984
        )
678✔
985
    );
678✔
986

678✔
987
    const drawCell = whenDefined(
678✔
988
        drawCellIn,
678✔
989
        React.useCallback<NonNullable<typeof drawCellIn>>(
678✔
990
            (args, draw) => {
678✔
UNCOV
991
                return drawCellIn?.({ ...args, col: args.col - rowMarkerOffset }, draw) ?? false;
×
992
            },
×
993
            [drawCellIn, rowMarkerOffset]
678✔
994
        )
678✔
995
    );
678✔
996

678✔
997
    const onDelete = React.useCallback<NonNullable<DataEditorProps["onDelete"]>>(
678✔
998
        sel => {
678✔
999
            if (onDeleteIn !== undefined) {
9✔
1000
                const result = onDeleteIn(shiftSelection(sel, -rowMarkerOffset));
5✔
1001
                if (typeof result === "boolean") {
5!
UNCOV
1002
                    return result;
×
1003
                }
×
1004
                return shiftSelection(result, rowMarkerOffset);
5✔
1005
            }
5✔
1006
            return true;
4✔
1007
        },
9✔
1008
        [onDeleteIn, rowMarkerOffset]
678✔
1009
    );
678✔
1010

678✔
1011
    const [setCurrent, setSelectedRows, setSelectedColumns] = useSelectionBehavior(
678✔
1012
        gridSelection,
678✔
1013
        setGridSelection,
678✔
1014
        rangeSelectionBlending,
678✔
1015
        columnSelectionBlending,
678✔
1016
        rowSelectionBlending,
678✔
1017
        rangeSelect
678✔
1018
    );
678✔
1019

678✔
1020
    const mergedTheme = React.useMemo(() => {
678✔
1021
        return mergeAndRealizeTheme(getDataEditorTheme(), theme);
137✔
1022
    }, [theme]);
678✔
1023

678✔
1024
    const [clientSize, setClientSize] = React.useState<readonly [number, number, number]>([10, 10, 0]);
678✔
1025

678✔
1026
    const rendererMap = React.useMemo(() => {
678✔
1027
        if (renderers === undefined) return {};
137!
1028
        const result: Partial<Record<InnerGridCellKind | GridCellKind, InternalCellRenderer<InnerGridCell>>> = {};
137✔
1029
        for (const r of renderers) {
137✔
1030
            result[r.kind] = r;
1,781✔
1031
        }
1,781✔
1032
        return result;
137✔
1033
    }, [renderers]);
678✔
1034

678✔
1035
    const getCellRenderer: <T extends InnerGridCell>(cell: T) => CellRenderer<T> | undefined = React.useCallback(
678✔
1036
        <T extends InnerGridCell>(cell: T) => {
678✔
1037
            if (cell.kind !== GridCellKind.Custom) {
143,157✔
1038
                return rendererMap[cell.kind] as unknown as CellRenderer<T>;
139,427✔
1039
            }
139,427✔
1040
            return additionalRenderers?.find(x => x.isMatch(cell)) as CellRenderer<T>;
143,157✔
1041
        },
143,157✔
1042
        [additionalRenderers, rendererMap]
678✔
1043
    );
678✔
1044

678✔
1045
    const { sizedColumns: columns, nonGrowWidth } = useColumnSizer(
678✔
1046
        columnsIn,
678✔
1047
        rows,
678✔
1048
        getCellsForSeletionDirect,
678✔
1049
        clientSize[0] - (rowMarkerOffset === 0 ? 0 : rowMarkerWidth) - clientSize[2],
678✔
1050
        minColumnWidth,
678✔
1051
        maxColumnAutoWidth,
678✔
1052
        mergedTheme,
678✔
1053
        getCellRenderer,
678✔
1054
        abortControllerRef.current
678✔
1055
    );
678✔
1056

678✔
1057
    const enableGroups = React.useMemo(() => {
678✔
1058
        return columns.some(c => c.group !== undefined);
137✔
1059
    }, [columns]);
678✔
1060

678✔
1061
    const totalHeaderHeight = enableGroups ? headerHeight + groupHeaderHeight : headerHeight;
678✔
1062

678✔
1063
    const numSelectedRows = gridSelection.rows.length;
678✔
1064
    const rowMarkerHeader =
678✔
1065
        rowMarkers === "none"
678✔
1066
            ? ""
547✔
1067
            : numSelectedRows === 0
130✔
1068
            ? headerCellUnheckedMarker
86✔
1069
            : numSelectedRows === rows
44✔
1070
            ? headerCellCheckedMarker
6✔
1071
            : headerCellIndeterminateMarker;
38✔
1072

678✔
1073
    const mangledCols = React.useMemo(() => {
678✔
1074
        if (rowMarkers === "none") return columns;
151✔
1075
        return [
45✔
1076
            {
45✔
1077
                title: rowMarkerHeader,
45✔
1078
                width: rowMarkerWidth,
45✔
1079
                icon: undefined,
45✔
1080
                hasMenu: false,
45✔
1081
                style: "normal" as const,
45✔
1082
                themeOverride: rowMarkerTheme,
45✔
1083
            },
45✔
1084
            ...columns,
45✔
1085
        ];
45✔
1086
    }, [columns, rowMarkerWidth, rowMarkers, rowMarkerHeader, rowMarkerTheme]);
678✔
1087

678✔
1088
    const [visibleRegionY, visibleRegionTy] = React.useMemo(() => {
678✔
1089
        return [
137✔
1090
            scrollOffsetY !== undefined && typeof rowHeight === "number" ? Math.floor(scrollOffsetY / rowHeight) : 0,
137!
1091
            scrollOffsetY !== undefined && typeof rowHeight === "number" ? -(scrollOffsetY % rowHeight) : 0,
137!
1092
        ];
137✔
1093
    }, [scrollOffsetY, rowHeight]);
678✔
1094

678✔
1095
    type VisibleRegion = Rectangle & {
678✔
1096
        /** value in px */
678✔
1097
        tx?: number;
678✔
1098
        /** value in px */
678✔
1099
        ty?: number;
678✔
1100
        extras?: {
678✔
1101
            selected?: Item;
678✔
1102
            freezeRegion?: Rectangle;
678✔
1103
        };
678✔
1104
    };
678✔
1105

678✔
1106
    const visibleRegionRef = React.useRef<VisibleRegion>({
678✔
1107
        height: 1,
678✔
1108
        width: 1,
678✔
1109
        x: 0,
678✔
1110
        y: 0,
678✔
1111
    });
678✔
1112
    const visibleRegionInput = React.useMemo<VisibleRegion>(
678✔
1113
        () => ({
678✔
1114
            x: visibleRegionRef.current.x,
137✔
1115
            y: visibleRegionY,
137✔
1116
            width: visibleRegionRef.current.width ?? 1,
137!
1117
            height: visibleRegionRef.current.height ?? 1,
137!
1118
            // tx: 'TODO',
137✔
1119
            ty: visibleRegionTy,
137✔
1120
        }),
137✔
1121
        [visibleRegionTy, visibleRegionY]
678✔
1122
    );
678✔
1123

678✔
1124
    const hasJustScrolled = React.useRef(false);
678✔
1125

678✔
1126
    const [visibleRegion, setVisibleRegion, empty] = useStateWithReactiveInput<VisibleRegion>(visibleRegionInput);
678✔
1127

678✔
1128
    const vScrollReady = (visibleRegion.height ?? 1) > 1;
678!
1129
    React.useLayoutEffect(() => {
678✔
1130
        if (scrollOffsetY !== undefined && scrollRef.current !== null && vScrollReady) {
274!
UNCOV
1131
            if (scrollRef.current.scrollTop === scrollOffsetY) return;
×
1132
            scrollRef.current.scrollTop = scrollOffsetY;
×
1133
            if (scrollRef.current.scrollTop !== scrollOffsetY) {
×
1134
                empty();
×
1135
            }
×
1136
            hasJustScrolled.current = true;
×
1137
        }
×
1138
    }, [scrollOffsetY, vScrollReady, empty]);
678✔
1139

678✔
1140
    const hScrollReady = (visibleRegion.width ?? 1) > 1;
678!
1141
    React.useLayoutEffect(() => {
678✔
1142
        if (scrollOffsetX !== undefined && scrollRef.current !== null && hScrollReady) {
274!
UNCOV
1143
            if (scrollRef.current.scrollLeft === scrollOffsetX) return;
×
1144
            scrollRef.current.scrollLeft = scrollOffsetX;
×
1145
            if (scrollRef.current.scrollLeft !== scrollOffsetX) {
×
1146
                empty();
×
1147
            }
×
1148
            hasJustScrolled.current = true;
×
1149
        }
×
1150
    }, [scrollOffsetX, hScrollReady, empty]);
678✔
1151

678✔
1152
    const cellXOffset = visibleRegion.x + rowMarkerOffset;
678✔
1153
    const cellYOffset = visibleRegion.y;
678✔
1154

678✔
1155
    const gridRef = React.useRef<DataGridRef | null>(null);
678✔
1156

678✔
1157
    const focus = React.useCallback((immediate?: boolean) => {
678✔
1158
        if (immediate === true) {
125✔
1159
            gridRef.current?.focus();
7✔
1160
        } else {
125✔
1161
            window.requestAnimationFrame(() => {
118✔
1162
                gridRef.current?.focus();
117✔
1163
            });
118✔
1164
        }
118✔
1165
    }, []);
678✔
1166

678✔
1167
    const mangledRows = showTrailingBlankRow ? rows + 1 : rows;
678!
1168

678✔
1169
    const mangledOnCellsEdited = React.useCallback<NonNullable<typeof onCellsEdited>>(
678✔
1170
        (items: readonly EditListItem[]) => {
678✔
1171
            const mangledItems =
27✔
1172
                rowMarkerOffset === 0
27✔
1173
                    ? items
22✔
1174
                    : items.map(x => ({
5✔
1175
                          ...x,
29✔
1176
                          location: [x.location[0] - rowMarkerOffset, x.location[1]] as const,
29✔
1177
                      }));
5✔
1178
            const r = onCellsEdited?.(mangledItems);
27✔
1179

27✔
1180
            if (r !== true) {
27✔
1181
                for (const i of mangledItems) onCellEdited?.(i.location, i.value);
26✔
1182
            }
26✔
1183

27✔
1184
            return r;
27✔
1185
        },
27✔
1186
        [onCellEdited, onCellsEdited, rowMarkerOffset]
678✔
1187
    );
678✔
1188

678✔
1189
    const [fillHighlightRegion, setFillHighlightRegion] = React.useState<Rectangle | undefined>();
678✔
1190

678✔
1191
    // this will generally be undefined triggering the memo less often
678✔
1192
    const highlightRange =
678✔
1193
        gridSelection.current !== undefined &&
678✔
1194
        gridSelection.current.range.width * gridSelection.current.range.height > 1
321✔
1195
            ? gridSelection.current.range
41✔
1196
            : undefined;
636✔
1197
    const highlightRegions = React.useMemo(() => {
678✔
1198
        if (
172✔
1199
            (highlightRegionsIn === undefined || highlightRegionsIn.length === 0) &&
172✔
1200
            highlightRange === undefined &&
171✔
1201
            fillHighlightRegion === undefined
144✔
1202
        )
172✔
1203
            return undefined;
172✔
1204

33✔
1205
        const regions: Highlight[] = [];
33✔
1206

33✔
1207
        if (highlightRegionsIn !== undefined) {
166✔
1208
            for (const r of highlightRegionsIn) {
1✔
1209
                const maxWidth = mangledCols.length - r.range.x - rowMarkerOffset;
1✔
1210
                if (maxWidth > 0) {
1✔
1211
                    regions.push({
1✔
1212
                        color: r.color,
1✔
1213
                        range: {
1✔
1214
                            ...r.range,
1✔
1215
                            x: r.range.x + rowMarkerOffset,
1✔
1216
                            width: Math.min(maxWidth, r.range.width),
1✔
1217
                        },
1✔
1218
                        style: r.style,
1✔
1219
                    });
1✔
1220
                }
1✔
1221
            }
1✔
1222
        }
1✔
1223

33✔
1224
        if (fillHighlightRegion !== undefined) {
166✔
1225
            regions.push({
5✔
1226
                color: withAlpha(mergedTheme.accentColor, 0),
5✔
1227
                range: fillHighlightRegion,
5✔
1228
                style: "dashed",
5✔
1229
            });
5✔
1230
        }
5✔
1231

33✔
1232
        if (highlightRange !== undefined) {
166✔
1233
            regions.push({
27✔
1234
                color: withAlpha(mergedTheme.accentColor, 0.5),
27✔
1235
                range: highlightRange,
27✔
1236
                style: "solid-outline",
27✔
1237
            });
27✔
1238
        }
27✔
1239

33✔
1240
        return regions.length > 0 ? regions : undefined;
172!
1241
    }, [
678✔
1242
        fillHighlightRegion,
678✔
1243
        highlightRange,
678✔
1244
        highlightRegionsIn,
678✔
1245
        mangledCols.length,
678✔
1246
        mergedTheme.accentColor,
678✔
1247
        rowMarkerOffset,
678✔
1248
    ]);
678✔
1249

678✔
1250
    const mangledColsRef = React.useRef(mangledCols);
678✔
1251
    mangledColsRef.current = mangledCols;
678✔
1252
    const getMangledCellContent = React.useCallback(
678✔
1253
        ([col, row]: Item, forceStrict: boolean = false): InnerGridCell => {
678✔
1254
            const isTrailing = showTrailingBlankRow && row === mangledRows - 1;
144,269✔
1255
            const isRowMarkerCol = col === 0 && hasRowMarkers;
144,269✔
1256
            if (isRowMarkerCol) {
144,269✔
1257
                if (isTrailing) {
2,589✔
1258
                    return loadingCell;
98✔
1259
                }
98✔
1260
                return {
2,491✔
1261
                    kind: InnerGridCellKind.Marker,
2,491✔
1262
                    allowOverlay: false,
2,491✔
1263
                    checked: gridSelection?.rows.hasIndex(row) === true,
2,589✔
1264
                    markerKind: rowMarkers === "clickable-number" ? "number" : rowMarkers,
2,589!
1265
                    row: rowMarkerStartIndex + row,
2,589✔
1266
                    drawHandle: onRowMoved !== undefined,
2,589✔
1267
                    cursor: rowMarkers === "clickable-number" ? "pointer" : undefined,
2,589!
1268
                };
2,589✔
1269
            } else if (isTrailing) {
144,269✔
1270
                //If the grid is empty, we will return text
3,883✔
1271
                const isFirst = col === rowMarkerOffset;
3,883✔
1272

3,883✔
1273
                const maybeFirstColumnHint = isFirst ? trailingRowOptions?.hint ?? "" : "";
3,883✔
1274
                const c = mangledColsRef.current[col];
3,883✔
1275

3,883✔
1276
                if (c?.trailingRowOptions?.disabled === true) {
3,883!
UNCOV
1277
                    return loadingCell;
×
1278
                } else {
3,883✔
1279
                    const hint = c?.trailingRowOptions?.hint ?? maybeFirstColumnHint;
3,883!
1280
                    const icon = c?.trailingRowOptions?.addIcon ?? trailingRowOptions?.addIcon;
3,883!
1281
                    return {
3,883✔
1282
                        kind: InnerGridCellKind.NewRow,
3,883✔
1283
                        hint,
3,883✔
1284
                        allowOverlay: false,
3,883✔
1285
                        icon,
3,883✔
1286
                    };
3,883✔
1287
                }
3,883✔
1288
            } else {
141,680✔
1289
                const outerCol = col - rowMarkerOffset;
137,797✔
1290
                if (forceStrict || experimental?.strict === true) {
137,797✔
1291
                    const vr = visibleRegionRef.current;
24,901✔
1292
                    const isOutsideMainArea =
24,901✔
1293
                        vr.x > outerCol ||
24,901✔
1294
                        outerCol > vr.x + vr.width ||
24,901✔
1295
                        vr.y > row ||
24,901✔
1296
                        row > vr.y + vr.height ||
24,901✔
1297
                        row >= rowsRef.current;
24,901✔
1298
                    const isSelected = outerCol === vr.extras?.selected?.[0] && row === vr.extras?.selected[1];
24,901!
1299
                    const isOutsideFreezeArea =
24,901✔
1300
                        vr.extras?.freezeRegion === undefined ||
24,901!
UNCOV
1301
                        vr.extras.freezeRegion.x > outerCol ||
×
1302
                        outerCol > vr.extras.freezeRegion.x + vr.extras.freezeRegion.width ||
×
1303
                        vr.extras.freezeRegion.y > row ||
×
1304
                        row > vr.extras.freezeRegion.y + vr.extras.freezeRegion.height;
×
1305
                    if (isOutsideMainArea && !isSelected && isOutsideFreezeArea) {
24,901!
UNCOV
1306
                        return loadingCell;
×
1307
                    }
×
1308
                }
24,901✔
1309
                let result = getCellContent([outerCol, row]);
137,797✔
1310
                if (rowMarkerOffset !== 0 && result.span !== undefined) {
137,797!
UNCOV
1311
                    result = {
×
1312
                        ...result,
×
1313
                        span: [result.span[0] + rowMarkerOffset, result.span[1] + rowMarkerOffset],
×
1314
                    };
×
1315
                }
×
1316
                return result;
137,797✔
1317
            }
137,797✔
1318
        },
144,269✔
1319
        [
678✔
1320
            showTrailingBlankRow,
678✔
1321
            mangledRows,
678✔
1322
            hasRowMarkers,
678✔
1323
            gridSelection?.rows,
678✔
1324
            onRowMoved,
678✔
1325
            rowMarkers,
678✔
1326
            rowMarkerOffset,
678✔
1327
            trailingRowOptions?.hint,
678✔
1328
            trailingRowOptions?.addIcon,
678✔
1329
            experimental?.strict,
678✔
1330
            getCellContent,
678✔
1331
            rowMarkerStartIndex,
678✔
1332
        ]
678✔
1333
    );
678✔
1334

678✔
1335
    const mangledGetGroupDetails = React.useCallback<NonNullable<DataEditorProps["getGroupDetails"]>>(
678✔
1336
        group => {
678✔
1337
            let result = getGroupDetails?.(group) ?? { name: group };
8,283✔
1338
            if (onGroupHeaderRenamed !== undefined && group !== "") {
8,283✔
1339
                result = {
91✔
1340
                    icon: result.icon,
91✔
1341
                    name: result.name,
91✔
1342
                    overrideTheme: result.overrideTheme,
91✔
1343
                    actions: [
91✔
1344
                        ...(result.actions ?? []),
91✔
1345
                        {
91✔
1346
                            title: "Rename",
91✔
1347
                            icon: "renameIcon",
91✔
1348
                            onClick: e =>
91✔
1349
                                setRenameGroup({
2✔
1350
                                    group: result.name,
2✔
1351
                                    bounds: e.bounds,
2✔
1352
                                }),
2✔
1353
                        },
91✔
1354
                    ],
91✔
1355
                };
91✔
1356
            }
91✔
1357
            return result;
8,283✔
1358
        },
8,283✔
1359
        [getGroupDetails, onGroupHeaderRenamed]
678✔
1360
    );
678✔
1361

678✔
1362
    const setOverlaySimple = React.useCallback(
678✔
1363
        (val: Omit<NonNullable<typeof overlay>, "theme">) => {
678✔
1364
            const [col, row] = val.cell;
19✔
1365
            const column = mangledCols[col];
19✔
1366
            const groupTheme =
19✔
1367
                column?.group !== undefined ? mangledGetGroupDetails(column.group)?.overrideTheme : undefined;
19!
1368
            const colTheme = column?.themeOverride;
19✔
1369
            const rowTheme = getRowThemeOverride?.(row);
19!
1370

19✔
1371
            setOverlay({
19✔
1372
                ...val,
19✔
1373
                theme: mergeAndRealizeTheme(mergedTheme, groupTheme, colTheme, rowTheme, val.content.themeOverride),
19✔
1374
            });
19✔
1375
        },
19✔
1376
        [getRowThemeOverride, mangledCols, mangledGetGroupDetails, mergedTheme]
678✔
1377
    );
678✔
1378

678✔
1379
    const reselect = React.useCallback(
678✔
1380
        (bounds: Rectangle, fromKeyboard: boolean, initialValue?: string) => {
678✔
1381
            if (gridSelection.current === undefined) return;
19!
1382

19✔
1383
            const [col, row] = gridSelection.current.cell;
19✔
1384
            const c = getMangledCellContent([col, row]);
19✔
1385
            if (c.kind !== GridCellKind.Boolean && c.allowOverlay) {
19✔
1386
                let content = c;
18✔
1387
                if (initialValue !== undefined) {
18✔
1388
                    switch (content.kind) {
7✔
1389
                        case GridCellKind.Number: {
7!
UNCOV
1390
                            const d = maybe(() => (initialValue === "-" ? -0 : Number.parseFloat(initialValue)), 0);
×
1391
                            content = {
×
1392
                                ...content,
×
1393
                                data: Number.isNaN(d) ? 0 : d,
×
1394
                            };
×
1395
                            break;
×
1396
                        }
×
1397
                        case GridCellKind.Text:
7✔
1398
                        case GridCellKind.Markdown:
7✔
1399
                        case GridCellKind.Uri:
7✔
1400
                            content = {
7✔
1401
                                ...content,
7✔
1402
                                data: initialValue,
7✔
1403
                            };
7✔
1404
                            break;
7✔
1405
                    }
7✔
1406
                }
7✔
1407

18✔
1408
                setOverlaySimple({
18✔
1409
                    target: bounds,
18✔
1410
                    content,
18✔
1411
                    initialValue,
18✔
1412
                    cell: [col, row],
18✔
1413
                    highlight: initialValue === undefined,
18✔
1414
                    forceEditMode: initialValue !== undefined,
18✔
1415
                });
18✔
1416
            } else if (c.kind === GridCellKind.Boolean && fromKeyboard && c.readonly !== true) {
19!
UNCOV
1417
                mangledOnCellsEdited([
×
1418
                    {
×
1419
                        location: gridSelection.current.cell,
×
1420
                        value: {
×
1421
                            ...c,
×
1422
                            data: toggleBoolean(c.data),
×
1423
                        },
×
1424
                    },
×
1425
                ]);
×
1426
                gridRef.current?.damage([{ cell: gridSelection.current.cell }]);
×
1427
            }
×
1428
        },
19✔
1429
        [getMangledCellContent, gridSelection, mangledOnCellsEdited, setOverlaySimple]
678✔
1430
    );
678✔
1431

678✔
1432
    const focusOnRowFromTrailingBlankRow = React.useCallback(
678✔
1433
        (col: number, row: number) => {
678✔
1434
            const bounds = gridRef.current?.getBounds(col, row);
1✔
1435
            if (bounds === undefined || scrollRef.current === null) {
1!
UNCOV
1436
                return;
×
1437
            }
×
1438

1✔
1439
            const content = getMangledCellContent([col, row]);
1✔
1440
            if (!content.allowOverlay) {
1!
UNCOV
1441
                return;
×
1442
            }
×
1443

1✔
1444
            setOverlaySimple({
1✔
1445
                target: bounds,
1✔
1446
                content,
1✔
1447
                initialValue: undefined,
1✔
1448
                highlight: true,
1✔
1449
                cell: [col, row],
1✔
1450
                forceEditMode: true,
1✔
1451
            });
1✔
1452
        },
1✔
1453
        [getMangledCellContent, setOverlaySimple]
678✔
1454
    );
678✔
1455

678✔
1456
    const scrollTo = React.useCallback<ScrollToFn>(
678✔
1457
        (col, row, dir = "both", paddingX = 0, paddingY = 0, options = undefined): void => {
678✔
1458
            if (scrollRef.current !== null) {
43✔
1459
                const grid = gridRef.current;
43✔
1460
                const canvas = canvasRef.current;
43✔
1461

43✔
1462
                const trueCol = typeof col !== "number" ? (col.unit === "cell" ? col.amount : undefined) : col;
43!
1463
                const trueRow = typeof row !== "number" ? (row.unit === "cell" ? row.amount : undefined) : row;
43!
1464
                const desiredX = typeof col !== "number" && col.unit === "px" ? col.amount : undefined;
43!
1465
                const desiredY = typeof row !== "number" && row.unit === "px" ? row.amount : undefined;
43✔
1466
                if (grid !== null && canvas !== null) {
43✔
1467
                    let targetRect: Rectangle = {
43✔
1468
                        x: 0,
43✔
1469
                        y: 0,
43✔
1470
                        width: 0,
43✔
1471
                        height: 0,
43✔
1472
                    };
43✔
1473

43✔
1474
                    let scrollX = 0;
43✔
1475
                    let scrollY = 0;
43✔
1476

43✔
1477
                    if (trueCol !== undefined || trueRow !== undefined) {
43!
1478
                        targetRect = grid.getBounds((trueCol ?? 0) + rowMarkerOffset, trueRow ?? 0) ?? targetRect;
43!
1479
                        if (targetRect.width === 0 || targetRect.height === 0) return;
43!
1480
                    }
43✔
1481

43✔
1482
                    const scrollBounds = canvas.getBoundingClientRect();
43✔
1483
                    const scale = scrollBounds.width / canvas.offsetWidth;
43✔
1484

43✔
1485
                    if (desiredX !== undefined) {
43!
UNCOV
1486
                        targetRect = {
×
1487
                            ...targetRect,
×
1488
                            x: desiredX - scrollBounds.left - scrollRef.current.scrollLeft,
×
1489
                            width: 1,
×
1490
                        };
×
1491
                    }
×
1492
                    if (desiredY !== undefined) {
43✔
1493
                        targetRect = {
4✔
1494
                            ...targetRect,
4✔
1495
                            y: desiredY + scrollBounds.top - scrollRef.current.scrollTop,
4✔
1496
                            height: 1,
4✔
1497
                        };
4✔
1498
                    }
4✔
1499

43✔
1500
                    if (targetRect !== undefined) {
43✔
1501
                        const bounds = {
43✔
1502
                            x: targetRect.x - paddingX,
43✔
1503
                            y: targetRect.y - paddingY,
43✔
1504
                            width: targetRect.width + 2 * paddingX,
43✔
1505
                            height: targetRect.height + 2 * paddingY,
43✔
1506
                        };
43✔
1507

43✔
1508
                        let frozenWidth = 0;
43✔
1509
                        for (let i = 0; i < freezeColumns; i++) {
43!
UNCOV
1510
                            frozenWidth += columns[i].width;
×
1511
                        }
×
1512
                        let trailingRowHeight = 0;
43✔
1513
                        if (lastRowSticky) {
43✔
1514
                            trailingRowHeight = typeof rowHeight === "number" ? rowHeight : rowHeight(rows);
43!
1515
                        }
43✔
1516

43✔
1517
                        // scrollBounds is already scaled
43✔
1518
                        let sLeft = frozenWidth * scale + scrollBounds.left + rowMarkerOffset * rowMarkerWidth * scale;
43✔
1519
                        let sRight = scrollBounds.right;
43✔
1520
                        let sTop = scrollBounds.top + totalHeaderHeight * scale;
43✔
1521
                        let sBottom = scrollBounds.bottom - trailingRowHeight * scale;
43✔
1522

43✔
1523
                        const minx = targetRect.width + paddingX * 2;
43✔
1524
                        switch (options?.hAlign) {
43✔
1525
                            case "start":
43!
UNCOV
1526
                                sRight = sLeft + minx;
×
1527
                                break;
×
1528
                            case "end":
43!
UNCOV
1529
                                sLeft = sRight - minx;
×
1530
                                break;
×
1531
                            case "center":
43!
UNCOV
1532
                                sLeft = Math.floor((sLeft + sRight) / 2) - minx / 2;
×
1533
                                sRight = sLeft + minx;
×
1534
                                break;
×
1535
                        }
43✔
1536

43✔
1537
                        const miny = targetRect.height + paddingY * 2;
43✔
1538
                        switch (options?.vAlign) {
43✔
1539
                            case "start":
43✔
1540
                                sBottom = sTop + miny;
1✔
1541
                                break;
1✔
1542
                            case "end":
43✔
1543
                                sTop = sBottom - miny;
1✔
1544
                                break;
1✔
1545
                            case "center":
43✔
1546
                                sTop = Math.floor((sTop + sBottom) / 2) - miny / 2;
1✔
1547
                                sBottom = sTop + miny;
1✔
1548
                                break;
1✔
1549
                        }
43✔
1550

43✔
1551
                        if (sLeft > bounds.x) {
43!
UNCOV
1552
                            scrollX = bounds.x - sLeft;
×
1553
                        } else if (sRight < bounds.x + bounds.width) {
43✔
1554
                            scrollX = bounds.x + bounds.width - sRight;
4✔
1555
                        }
4✔
1556

43✔
1557
                        if (sTop > bounds.y) {
43!
UNCOV
1558
                            scrollY = bounds.y - sTop;
×
1559
                        } else if (sBottom < bounds.y + bounds.height) {
43✔
1560
                            scrollY = bounds.y + bounds.height - sBottom;
12✔
1561
                        }
12✔
1562

43✔
1563
                        if (dir === "vertical" || (typeof col === "number" && col < freezeColumns)) {
43✔
1564
                            scrollX = 0;
2✔
1565
                        } else if (dir === "horizontal") {
43✔
1566
                            scrollY = 0;
6✔
1567
                        }
6✔
1568

43✔
1569
                        if (scrollX !== 0 || scrollY !== 0) {
43✔
1570
                            // Remove scaling as scrollTo method is unaffected by transform scale.
15✔
1571
                            if (scale !== 1) {
15!
UNCOV
1572
                                scrollX /= scale;
×
1573
                                scrollY /= scale;
×
1574
                            }
×
1575
                            scrollRef.current.scrollTo(
15✔
1576
                                scrollX + scrollRef.current.scrollLeft,
15✔
1577
                                scrollY + scrollRef.current.scrollTop
15✔
1578
                            );
15✔
1579
                        }
15✔
1580
                    }
43✔
1581
                }
43✔
1582
            }
43✔
1583
        },
43✔
1584
        [rowMarkerOffset, rowMarkerWidth, totalHeaderHeight, lastRowSticky, freezeColumns, columns, rowHeight, rows]
678✔
1585
    );
678✔
1586

678✔
1587
    const focusCallback = React.useRef(focusOnRowFromTrailingBlankRow);
678✔
1588
    const getCellContentRef = React.useRef(getCellContent);
678✔
1589
    const rowsRef = React.useRef(rows);
678✔
1590
    focusCallback.current = focusOnRowFromTrailingBlankRow;
678✔
1591
    getCellContentRef.current = getCellContent;
678✔
1592
    rowsRef.current = rows;
678✔
1593
    const appendRow = React.useCallback(
678✔
1594
        async (col: number, openOverlay: boolean = true): Promise<void> => {
678✔
1595
            const c = mangledCols[col];
1✔
1596
            if (c?.trailingRowOptions?.disabled === true) {
1!
UNCOV
1597
                return;
×
1598
            }
×
1599
            const appendResult = onRowAppended?.();
1✔
1600

1✔
1601
            let r: "top" | "bottom" | number | undefined = undefined;
1✔
1602
            let bottom = true;
1✔
1603
            if (appendResult !== undefined) {
1!
UNCOV
1604
                r = await appendResult;
×
1605
                if (r === "top") bottom = false;
×
1606
                if (typeof r === "number") bottom = false;
×
1607
            }
×
1608

1✔
1609
            let backoff = 0;
1✔
1610
            const doFocus = () => {
1✔
1611
                if (rowsRef.current <= rows) {
2✔
1612
                    if (backoff < 500) {
1✔
1613
                        window.setTimeout(doFocus, backoff);
1✔
1614
                    }
1✔
1615
                    backoff = 50 + backoff * 2;
1✔
1616
                    return;
1✔
1617
                }
1✔
1618

1✔
1619
                const row = typeof r === "number" ? r : bottom ? rows : 0;
2!
1620
                scrollTo(col - rowMarkerOffset, row);
2✔
1621
                setCurrent(
2✔
1622
                    {
2✔
1623
                        cell: [col, row],
2✔
1624
                        range: {
2✔
1625
                            x: col,
2✔
1626
                            y: row,
2✔
1627
                            width: 1,
2✔
1628
                            height: 1,
2✔
1629
                        },
2✔
1630
                    },
2✔
1631
                    false,
2✔
1632
                    false,
2✔
1633
                    "edit"
2✔
1634
                );
2✔
1635

2✔
1636
                const cell = getCellContentRef.current([col - rowMarkerOffset, row]);
2✔
1637
                if (cell.allowOverlay && isReadWriteCell(cell) && cell.readonly !== true && openOverlay) {
2✔
1638
                    // wait for scroll to have a chance to process
1✔
1639
                    window.setTimeout(() => {
1✔
1640
                        focusCallback.current(col, row);
1✔
1641
                    }, 0);
1✔
1642
                }
1✔
1643
            };
2✔
1644
            // Queue up to allow the consumer to react to the event and let us check if they did
1✔
1645
            doFocus();
1✔
1646
        },
1✔
1647
        [mangledCols, onRowAppended, rowMarkerOffset, rows, scrollTo, setCurrent]
678✔
1648
    );
678✔
1649

678✔
1650
    const getCustomNewRowTargetColumn = React.useCallback(
678✔
1651
        (col: number): number | undefined => {
678✔
1652
            const customTargetColumn =
1✔
1653
                columns[col]?.trailingRowOptions?.targetColumn ?? trailingRowOptions?.targetColumn;
1!
1654

1✔
1655
            if (typeof customTargetColumn === "number") {
1!
UNCOV
1656
                const customTargetOffset = hasRowMarkers ? 1 : 0;
×
1657
                return customTargetColumn + customTargetOffset;
×
1658
            }
×
1659

1✔
1660
            if (typeof customTargetColumn === "object") {
1!
UNCOV
1661
                const maybeIndex = columnsIn.indexOf(customTargetColumn);
×
1662
                if (maybeIndex >= 0) {
×
1663
                    const customTargetOffset = hasRowMarkers ? 1 : 0;
×
1664
                    return maybeIndex + customTargetOffset;
×
1665
                }
×
1666
            }
×
1667

1✔
1668
            return undefined;
1✔
1669
        },
1✔
1670
        [columns, columnsIn, hasRowMarkers, trailingRowOptions?.targetColumn]
678✔
1671
    );
678✔
1672

678✔
1673
    const lastSelectedRowRef = React.useRef<number>();
678✔
1674
    const lastSelectedColRef = React.useRef<number>();
678✔
1675

678✔
1676
    const themeForCell = React.useCallback(
678✔
1677
        (cell: InnerGridCell, pos: Item): FullTheme => {
678✔
1678
            const [col, row] = pos;
20✔
1679
            return mergeAndRealizeTheme(
20✔
1680
                mergedTheme,
20✔
1681
                mangledCols[col]?.themeOverride,
20✔
1682
                getRowThemeOverride?.(row),
20!
1683
                cell.themeOverride
20✔
1684
            );
20✔
1685
        },
20✔
1686
        [getRowThemeOverride, mangledCols, mergedTheme]
678✔
1687
    );
678✔
1688

678✔
1689
    const handleSelect = React.useCallback(
678✔
1690
        (args: GridMouseEventArgs) => {
678✔
1691
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
118!
1692
            const isMultiRow = isMultiKey && rowSelect === "multi";
118✔
1693
            const isMultiCol = isMultiKey && columnSelect === "multi";
118✔
1694
            const [col, row] = args.location;
118✔
1695
            const selectedColumns = gridSelection.columns;
118✔
1696
            const selectedRows = gridSelection.rows;
118✔
1697
            const [cellCol, cellRow] = gridSelection.current?.cell ?? [];
118✔
1698
            // eslint-disable-next-line unicorn/prefer-switch
118✔
1699
            if (args.kind === "cell") {
118✔
1700
                lastSelectedColRef.current = undefined;
102✔
1701

102✔
1702
                lastMouseSelectLocation.current = [col, row];
102✔
1703

102✔
1704
                if (col === 0 && hasRowMarkers) {
102✔
1705
                    if (
15✔
1706
                        (showTrailingBlankRow === true && row === rows) ||
15✔
1707
                        rowMarkers === "number" ||
15✔
1708
                        rowSelect === "none"
14✔
1709
                    )
15✔
1710
                        return;
15✔
1711

14✔
1712
                    const markerCell = getMangledCellContent(args.location);
14✔
1713
                    if (markerCell.kind !== InnerGridCellKind.Marker) {
15!
UNCOV
1714
                        return;
×
1715
                    }
✔
1716

14✔
1717
                    if (onRowMoved !== undefined) {
15!
UNCOV
1718
                        const renderer = getCellRenderer(markerCell);
×
1719
                        assert(renderer?.kind === InnerGridCellKind.Marker);
×
1720
                        const postClick = renderer?.onClick?.({
×
1721
                            ...args,
×
1722
                            cell: markerCell,
×
1723
                            posX: args.localEventX,
×
1724
                            posY: args.localEventY,
×
1725
                            bounds: args.bounds,
×
1726
                            theme: themeForCell(markerCell, args.location),
×
1727
                            preventDefault: () => undefined,
×
1728
                        }) as MarkerCell | undefined;
×
1729
                        if (postClick === undefined || postClick.checked === markerCell.checked) return;
×
1730
                    }
✔
1731

14✔
1732
                    setOverlay(undefined);
14✔
1733
                    focus();
14✔
1734
                    const isSelected = selectedRows.hasIndex(row);
14✔
1735

14✔
1736
                    const lastHighlighted = lastSelectedRowRef.current;
14✔
1737
                    if (
14✔
1738
                        rowSelect === "multi" &&
14✔
1739
                        (args.shiftKey || args.isLongTouch === true) &&
8✔
1740
                        lastHighlighted !== undefined &&
1✔
1741
                        selectedRows.hasIndex(lastHighlighted)
1✔
1742
                    ) {
15✔
1743
                        const newSlice: Slice = [Math.min(lastHighlighted, row), Math.max(lastHighlighted, row) + 1];
1✔
1744

1✔
1745
                        if (isMultiRow || rowSelectionMode === "multi") {
1!
UNCOV
1746
                            setSelectedRows(undefined, newSlice, true);
×
1747
                        } else {
1✔
1748
                            setSelectedRows(CompactSelection.fromSingleSelection(newSlice), undefined, isMultiRow);
1✔
1749
                        }
1✔
1750
                    } else if (isMultiRow || args.isTouch || rowSelectionMode === "multi") {
15✔
1751
                        if (isSelected) {
3✔
1752
                            setSelectedRows(selectedRows.remove(row), undefined, true);
1✔
1753
                        } else {
2✔
1754
                            setSelectedRows(undefined, row, true);
2✔
1755
                            lastSelectedRowRef.current = row;
2✔
1756
                        }
2✔
1757
                    } else if (isSelected && selectedRows.length === 1) {
13✔
1758
                        setSelectedRows(CompactSelection.empty(), undefined, isMultiKey);
1✔
1759
                    } else {
10✔
1760
                        setSelectedRows(CompactSelection.fromSingleSelection(row), undefined, isMultiKey);
9✔
1761
                        lastSelectedRowRef.current = row;
9✔
1762
                    }
9✔
1763
                } else if (col >= rowMarkerOffset && showTrailingBlankRow && row === rows) {
102✔
1764
                    const customTargetColumn = getCustomNewRowTargetColumn(col);
1✔
1765
                    void appendRow(customTargetColumn ?? col);
1✔
1766
                } else {
87✔
1767
                    if (cellCol !== col || cellRow !== row) {
86✔
1768
                        const cell = getMangledCellContent(args.location);
80✔
1769
                        const renderer = getCellRenderer(cell);
80✔
1770

80✔
1771
                        if (renderer?.onSelect !== undefined) {
80!
UNCOV
1772
                            let prevented = false;
×
1773
                            renderer.onSelect({
×
1774
                                ...args,
×
1775
                                cell,
×
1776
                                posX: args.localEventX,
×
1777
                                posY: args.localEventY,
×
1778
                                bounds: args.bounds,
×
1779
                                preventDefault: () => (prevented = true),
×
1780
                                theme: themeForCell(cell, args.location),
×
1781
                            });
×
1782
                            if (prevented) {
×
1783
                                return;
×
1784
                            }
×
1785
                        }
×
1786
                        const isLastStickyRow = lastRowSticky && row === rows;
80✔
1787

80✔
1788
                        const startedFromLastSticky =
80✔
1789
                            lastRowSticky && gridSelection !== undefined && gridSelection.current?.cell[1] === rows;
80✔
1790

80✔
1791
                        if (
80✔
1792
                            (args.shiftKey || args.isLongTouch === true) &&
80✔
1793
                            cellCol !== undefined &&
6✔
1794
                            cellRow !== undefined &&
6✔
1795
                            gridSelection.current !== undefined &&
6✔
1796
                            !startedFromLastSticky
6✔
1797
                        ) {
80✔
1798
                            if (isLastStickyRow) {
6!
UNCOV
1799
                                // If we're making a selection and shift click in to the last sticky row,
×
1800
                                // just drop the event. Don't kill the selection.
×
1801
                                return;
×
1802
                            }
×
1803

6✔
1804
                            const left = Math.min(col, cellCol);
6✔
1805
                            const right = Math.max(col, cellCol);
6✔
1806
                            const top = Math.min(row, cellRow);
6✔
1807
                            const bottom = Math.max(row, cellRow);
6✔
1808
                            setCurrent(
6✔
1809
                                {
6✔
1810
                                    ...gridSelection.current,
6✔
1811
                                    range: {
6✔
1812
                                        x: left,
6✔
1813
                                        y: top,
6✔
1814
                                        width: right - left + 1,
6✔
1815
                                        height: bottom - top + 1,
6✔
1816
                                    },
6✔
1817
                                },
6✔
1818
                                true,
6✔
1819
                                isMultiKey,
6✔
1820
                                "click"
6✔
1821
                            );
6✔
1822
                            lastSelectedRowRef.current = undefined;
6✔
1823
                            focus();
6✔
1824
                        } else {
80✔
1825
                            setCurrent(
74✔
1826
                                {
74✔
1827
                                    cell: [col, row],
74✔
1828
                                    range: { x: col, y: row, width: 1, height: 1 },
74✔
1829
                                },
74✔
1830
                                true,
74✔
1831
                                isMultiKey,
74✔
1832
                                "click"
74✔
1833
                            );
74✔
1834
                            lastSelectedRowRef.current = undefined;
74✔
1835
                            setOverlay(undefined);
74✔
1836
                            focus();
74✔
1837
                        }
74✔
1838
                    }
80✔
1839
                }
86✔
1840
            } else if (args.kind === "header") {
118✔
1841
                lastMouseSelectLocation.current = [col, row];
12✔
1842
                setOverlay(undefined);
12✔
1843
                if (hasRowMarkers && col === 0) {
12✔
1844
                    lastSelectedRowRef.current = undefined;
4✔
1845
                    lastSelectedColRef.current = undefined;
4✔
1846
                    if (rowSelect === "multi") {
4✔
1847
                        if (selectedRows.length !== rows) {
4✔
1848
                            setSelectedRows(CompactSelection.fromSingleSelection([0, rows]), undefined, isMultiKey);
3✔
1849
                        } else {
4✔
1850
                            setSelectedRows(CompactSelection.empty(), undefined, isMultiKey);
1✔
1851
                        }
1✔
1852
                        focus();
4✔
1853
                    }
4✔
1854
                } else {
12✔
1855
                    const lastCol = lastSelectedColRef.current;
8✔
1856
                    if (
8✔
1857
                        columnSelect === "multi" &&
8✔
1858
                        (args.shiftKey || args.isLongTouch === true) &&
7!
UNCOV
1859
                        lastCol !== undefined &&
×
1860
                        selectedColumns.hasIndex(lastCol)
×
1861
                    ) {
8!
UNCOV
1862
                        const newSlice: Slice = [Math.min(lastCol, col), Math.max(lastCol, col) + 1];
×
1863

×
1864
                        if (isMultiCol) {
×
1865
                            setSelectedColumns(undefined, newSlice, isMultiKey);
×
1866
                        } else {
×
1867
                            setSelectedColumns(CompactSelection.fromSingleSelection(newSlice), undefined, isMultiKey);
×
1868
                        }
×
1869
                    } else if (isMultiCol) {
8✔
1870
                        if (selectedColumns.hasIndex(col)) {
1!
UNCOV
1871
                            setSelectedColumns(selectedColumns.remove(col), undefined, isMultiKey);
×
1872
                        } else {
1✔
1873
                            setSelectedColumns(undefined, col, isMultiKey);
1✔
1874
                        }
1✔
1875
                        lastSelectedColRef.current = col;
1✔
1876
                    } else if (columnSelect !== "none") {
8✔
1877
                        setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, isMultiKey);
7✔
1878
                        lastSelectedColRef.current = col;
7✔
1879
                    }
7✔
1880
                    lastSelectedRowRef.current = undefined;
8✔
1881
                    focus();
8✔
1882
                }
8✔
1883
            } else if (args.kind === groupHeaderKind) {
16✔
1884
                lastMouseSelectLocation.current = [col, row];
3✔
1885
            } else if (args.kind === outOfBoundsKind && !args.isMaybeScrollbar) {
4✔
1886
                setGridSelection(emptyGridSelection, false);
1✔
1887
                setOverlay(undefined);
1✔
1888
                focus();
1✔
1889
                onSelectionCleared?.();
1!
1890
                lastSelectedRowRef.current = undefined;
1✔
1891
                lastSelectedColRef.current = undefined;
1✔
1892
            }
1✔
1893
        },
118✔
1894
        [
678✔
1895
            appendRow,
678✔
1896
            columnSelect,
678✔
1897
            focus,
678✔
1898
            getCellRenderer,
678✔
1899
            getCustomNewRowTargetColumn,
678✔
1900
            getMangledCellContent,
678✔
1901
            gridSelection,
678✔
1902
            hasRowMarkers,
678✔
1903
            lastRowSticky,
678✔
1904
            onSelectionCleared,
678✔
1905
            onRowMoved,
678✔
1906
            rowMarkerOffset,
678✔
1907
            rowMarkers,
678✔
1908
            rowSelect,
678✔
1909
            rowSelectionMode,
678✔
1910
            rows,
678✔
1911
            setCurrent,
678✔
1912
            setGridSelection,
678✔
1913
            setSelectedColumns,
678✔
1914
            setSelectedRows,
678✔
1915
            showTrailingBlankRow,
678✔
1916
            themeForCell,
678✔
1917
        ]
678✔
1918
    );
678✔
1919
    const isActivelyDraggingHeader = React.useRef(false);
678✔
1920
    const lastMouseSelectLocation = React.useRef<readonly [number, number]>();
678✔
1921
    const touchDownArgs = React.useRef(visibleRegion);
678✔
1922
    const mouseDownData = React.useRef<{
678✔
1923
        wasDoubleClick: boolean;
678✔
1924
        time: number;
678✔
1925
        button: number;
678✔
1926
        location: Item;
678✔
1927
    }>();
678✔
1928
    const onMouseDown = React.useCallback(
678✔
1929
        (args: GridMouseEventArgs) => {
678✔
1930
            isPrevented.current = false;
135✔
1931
            touchDownArgs.current = visibleRegionRef.current;
135✔
1932
            if (args.button !== 0 && args.button !== 1) {
135✔
1933
                mouseDownData.current = undefined;
1✔
1934
                return;
1✔
1935
            }
1✔
1936

134✔
1937
            const time = performance.now();
134✔
1938
            const wasDoubleClick = time - (mouseDownData.current?.time ?? -1000) < 250;
135✔
1939
            mouseDownData.current = {
135✔
1940
                wasDoubleClick,
135✔
1941
                button: args.button,
135✔
1942
                time,
135✔
1943
                location: args.location,
135✔
1944
            };
135✔
1945

135✔
1946
            if (args?.kind === "header") {
135✔
1947
                isActivelyDraggingHeader.current = true;
18✔
1948
            }
18✔
1949

134✔
1950
            const fh = args.kind === "cell" && args.isFillHandle;
135✔
1951

135✔
1952
            if (!fh && args.kind !== "cell" && args.isEdge) return;
135✔
1953

127✔
1954
            setMouseState({
127✔
1955
                previousSelection: gridSelection,
127✔
1956
                fillHandle: fh,
127✔
1957
            });
127✔
1958
            lastMouseSelectLocation.current = undefined;
127✔
1959

127✔
1960
            if (!args.isTouch && args.button === 0 && !fh) {
135✔
1961
                handleSelect(args);
115✔
1962
            } else if (!args.isTouch && args.button === 1) {
135✔
1963
                lastMouseSelectLocation.current = args.location;
4✔
1964
            }
4✔
1965
        },
135✔
1966
        [gridSelection, handleSelect]
678✔
1967
    );
678✔
1968

678✔
1969
    const [renameGroup, setRenameGroup] = React.useState<{
678✔
1970
        group: string;
678✔
1971
        bounds: Rectangle;
678✔
1972
    }>();
678✔
1973

678✔
1974
    const handleGroupHeaderSelection = React.useCallback(
678✔
1975
        (args: GridMouseEventArgs) => {
678✔
1976
            if (args.kind !== groupHeaderKind || columnSelect !== "multi") {
3!
UNCOV
1977
                return;
×
UNCOV
1978
            }
×
1979
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
3!
1980
            const [col] = args.location;
3✔
1981
            const selectedColumns = gridSelection.columns;
3✔
1982

3✔
1983
            if (col < rowMarkerOffset) return;
3!
1984

3✔
1985
            const needle = mangledCols[col];
3✔
1986
            let start = col;
3✔
1987
            let end = col;
3✔
1988
            for (let i = col - 1; i >= rowMarkerOffset; i--) {
3✔
1989
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
3!
1990
                start--;
3✔
1991
            }
3✔
1992

3✔
1993
            for (let i = col + 1; i < mangledCols.length; i++) {
3✔
1994
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
27!
1995
                end++;
27✔
1996
            }
27✔
1997

3✔
1998
            focus();
3✔
1999

3✔
2000
            if (isMultiKey) {
3✔
2001
                if (selectedColumns.hasAll([start, end + 1])) {
2✔
2002
                    let newVal = selectedColumns;
1✔
2003
                    for (let index = start; index <= end; index++) {
1✔
2004
                        newVal = newVal.remove(index);
11✔
2005
                    }
11✔
2006
                    setSelectedColumns(newVal, undefined, isMultiKey);
1✔
2007
                } else {
1✔
2008
                    setSelectedColumns(undefined, [start, end + 1], isMultiKey);
1✔
2009
                }
1✔
2010
            } else {
3✔
2011
                setSelectedColumns(CompactSelection.fromSingleSelection([start, end + 1]), undefined, isMultiKey);
1✔
2012
            }
1✔
2013
        },
3✔
2014
        [columnSelect, focus, gridSelection.columns, mangledCols, rowMarkerOffset, setSelectedColumns]
678✔
2015
    );
678✔
2016

678✔
2017
    const fillDown = React.useCallback(
678✔
2018
        (reverse: boolean) => {
678✔
2019
            if (gridSelection.current === undefined) return;
1!
2020
            const v: EditListItem[] = [];
1✔
2021
            const r = gridSelection.current.range;
1✔
2022
            for (let x = 0; x < r.width; x++) {
1✔
2023
                const fillCol = x + r.x;
2✔
2024
                const fillVal = getMangledCellContent([fillCol, reverse ? r.y + r.height - 1 : r.y]);
2!
2025
                if (isInnerOnlyCell(fillVal) || !isReadWriteCell(fillVal)) continue;
2!
2026
                for (let y = 1; y < r.height; y++) {
2✔
2027
                    const fillRow = reverse ? r.y + r.height - (y + 1) : y + r.y;
8!
2028
                    const target = [fillCol, fillRow] as const;
8✔
2029
                    v.push({
8✔
2030
                        location: target,
8✔
2031
                        value: { ...fillVal },
8✔
2032
                    });
8✔
2033
                }
8✔
2034
            }
2✔
2035

1✔
2036
            mangledOnCellsEdited(v);
1✔
2037

1✔
2038
            gridRef.current?.damage(
1✔
2039
                v.map(c => ({
1✔
2040
                    cell: c.location,
8✔
2041
                }))
1✔
2042
            );
1✔
2043
        },
1✔
2044
        [getMangledCellContent, gridSelection, mangledOnCellsEdited]
678✔
2045
    );
678✔
2046

678✔
2047
    const isPrevented = React.useRef(false);
678✔
2048

678✔
2049
    const normalSizeColumn = React.useCallback(
678✔
2050
        async (col: number, force: boolean = false): Promise<void> => {
678✔
2051
            if (
3✔
2052
                (mouseDownData.current?.wasDoubleClick === true || force) &&
3✔
2053
                getCellsForSelection !== undefined &&
2✔
2054
                onColumnResize !== undefined
2✔
2055
            ) {
3✔
2056
                const start = visibleRegionRef.current.y;
2✔
2057
                const end = visibleRegionRef.current.height;
2✔
2058
                let cells = getCellsForSelection(
2✔
2059
                    {
2✔
2060
                        x: col,
2✔
2061
                        y: start,
2✔
2062
                        width: 1,
2✔
2063
                        height: Math.min(end, rows - start),
2✔
2064
                    },
2✔
2065
                    abortControllerRef.current.signal
2✔
2066
                );
2✔
2067
                if (typeof cells !== "object") {
2!
UNCOV
2068
                    cells = await cells();
×
UNCOV
2069
                }
×
2070
                const inputCol = columns[col - rowMarkerOffset];
2✔
2071
                const offscreen = document.createElement("canvas");
2✔
2072
                const ctx = offscreen.getContext("2d", { alpha: false });
2✔
2073
                if (ctx !== null) {
2✔
2074
                    ctx.font = mergedTheme.baseFontFull;
2✔
2075
                    const newCol = measureColumn(
2✔
2076
                        ctx,
2✔
2077
                        mergedTheme,
2✔
2078
                        inputCol,
2✔
2079
                        0,
2✔
2080
                        cells,
2✔
2081
                        minColumnWidth,
2✔
2082
                        maxColumnWidth,
2✔
2083
                        false,
2✔
2084
                        getCellRenderer
2✔
2085
                    );
2✔
2086
                    onColumnResize?.(inputCol, newCol.width, col, newCol.width);
2✔
2087
                }
2✔
2088
            }
2✔
2089
        },
3✔
2090
        [
678✔
2091
            columns,
678✔
2092
            getCellsForSelection,
678✔
2093
            maxColumnWidth,
678✔
2094
            mergedTheme,
678✔
2095
            minColumnWidth,
678✔
2096
            onColumnResize,
678✔
2097
            rowMarkerOffset,
678✔
2098
            rows,
678✔
2099
            getCellRenderer,
678✔
2100
        ]
678✔
2101
    );
678✔
2102

678✔
2103
    const [scrollDir, setScrollDir] = React.useState<GridMouseEventArgs["scrollEdge"]>();
678✔
2104

678✔
2105
    const fillPattern = React.useCallback(
678✔
2106
        async (previousSelection: GridSelection, currentSelection: GridSelection) => {
678✔
2107
            const patternRange = previousSelection.current?.range;
4✔
2108

4✔
2109
            if (
4✔
2110
                patternRange === undefined ||
4✔
2111
                getCellsForSelection === undefined ||
4✔
2112
                currentSelection.current === undefined
4✔
2113
            ) {
4!
2114
                return;
×
2115
            }
×
2116
            const currentRange = currentSelection.current.range;
4✔
2117

4✔
2118
            if (onFillPattern !== undefined) {
4!
2119
                let canceled = false;
×
2120
                onFillPattern({
×
UNCOV
2121
                    fillDestination: { ...currentRange, x: currentRange.x - rowMarkerOffset },
×
UNCOV
2122
                    patternSource: { ...patternRange, x: patternRange.x - rowMarkerOffset },
×
UNCOV
2123
                    preventDefault: () => (canceled = true),
×
UNCOV
2124
                });
×
UNCOV
2125
                if (canceled) return;
×
UNCOV
2126
            }
×
2127

4✔
2128
            let cells = getCellsForSelection(patternRange, abortControllerRef.current.signal);
4✔
2129
            if (typeof cells !== "object") cells = await cells();
4!
2130

4✔
2131
            const pattern = cells;
4✔
2132

4✔
2133
            // loop through all cells in currentSelection.current.range
4✔
2134
            const editItemList: EditListItem[] = [];
4✔
2135
            for (let x = 0; x < currentRange.width; x++) {
4✔
2136
                for (let y = 0; y < currentRange.height; y++) {
4✔
2137
                    const cell: Item = [currentRange.x + x, currentRange.y + y];
15✔
2138
                    if (itemIsInRect(cell, patternRange)) continue;
15✔
2139
                    const patternCell = pattern[y % patternRange.height][x % patternRange.width];
11✔
2140
                    if (isInnerOnlyCell(patternCell) || !isReadWriteCell(patternCell)) continue;
15!
2141
                    editItemList.push({
11✔
2142
                        location: cell,
11✔
2143
                        value: { ...patternCell },
11✔
2144
                    });
11✔
2145
                }
11✔
2146
            }
4✔
2147
            mangledOnCellsEdited(editItemList);
4✔
2148

4✔
2149
            gridRef.current?.damage(
4✔
2150
                editItemList.map(c => ({
4✔
2151
                    cell: c.location,
11✔
2152
                }))
4✔
2153
            );
4✔
2154
        },
4✔
2155
        [getCellsForSelection, mangledOnCellsEdited, onFillPattern, rowMarkerOffset]
678✔
2156
    );
678✔
2157

678✔
2158
    const onMouseUp = React.useCallback(
678✔
2159
        (args: GridMouseEventArgs, isOutside: boolean) => {
678✔
2160
            const mouse = mouseState;
134✔
2161
            setMouseState(undefined);
134✔
2162
            setFillHighlightRegion(undefined);
134✔
2163
            setScrollDir(undefined);
134✔
2164
            isActivelyDraggingHeader.current = false;
134✔
2165

134✔
2166
            if (isOutside) return;
134✔
2167

133✔
2168
            if (
133✔
2169
                mouse?.fillHandle === true &&
134✔
2170
                gridSelection.current !== undefined &&
4✔
2171
                mouse.previousSelection?.current !== undefined
4✔
2172
            ) {
134✔
2173
                if (fillHighlightRegion === undefined) return;
4!
2174
                const newRange = {
4✔
2175
                    ...gridSelection,
4✔
2176
                    current: {
4✔
2177
                        ...gridSelection.current,
4✔
2178
                        range: combineRects(mouse.previousSelection.current.range, fillHighlightRegion),
4✔
2179
                    },
4✔
2180
                };
4✔
2181
                void fillPattern(mouse.previousSelection, newRange);
4✔
2182
                setGridSelection(newRange, true);
4✔
2183
                return;
4✔
2184
            }
4✔
2185

129✔
2186
            const [col, row] = args.location;
129✔
2187
            const [lastMouseDownCol, lastMouseDownRow] = lastMouseSelectLocation.current ?? [];
134✔
2188

134✔
2189
            const preventDefault = () => {
134✔
UNCOV
2190
                isPrevented.current = true;
×
UNCOV
2191
            };
×
2192

134✔
2193
            const handleMaybeClick = (a: GridMouseCellEventArgs): boolean => {
134✔
2194
                const isValidClick = a.isTouch || (lastMouseDownCol === col && lastMouseDownRow === row);
104✔
2195
                if (isValidClick) {
104✔
2196
                    onCellClicked?.([col - rowMarkerOffset, row], {
94✔
2197
                        ...a,
4✔
2198
                        preventDefault,
4✔
2199
                    });
4✔
2200
                }
94✔
2201
                if (a.button === 1) return !isPrevented.current;
104✔
2202
                if (!isPrevented.current) {
101✔
2203
                    const c = getMangledCellContent(args.location);
101✔
2204
                    const r = getCellRenderer(c);
101✔
2205
                    if (r !== undefined && r.onClick !== undefined && isValidClick) {
101✔
2206
                        const newVal = r.onClick({
20✔
2207
                            ...a,
20✔
2208
                            cell: c,
20✔
2209
                            posX: a.localEventX,
20✔
2210
                            posY: a.localEventY,
20✔
2211
                            bounds: a.bounds,
20✔
2212
                            theme: themeForCell(c, args.location),
20✔
2213
                            preventDefault,
20✔
2214
                        });
20✔
2215
                        if (newVal !== undefined && !isInnerOnlyCell(newVal) && isEditableGridCell(newVal)) {
20✔
2216
                            mangledOnCellsEdited([{ location: a.location, value: newVal }]);
4✔
2217
                            gridRef.current?.damage([
4✔
2218
                                {
4✔
2219
                                    cell: a.location,
4✔
2220
                                },
4✔
2221
                            ]);
4✔
2222
                        }
4✔
2223
                    }
20✔
2224
                    if (isPrevented.current || gridSelection.current === undefined) return false;
101✔
2225

85✔
2226
                    let shouldActivate = false;
85✔
2227
                    switch (cellActivationBehavior) {
85✔
2228
                        case "double-click":
101✔
2229
                        case "second-click": {
101✔
2230
                            if (mouse?.previousSelection?.current?.cell === undefined) break;
84✔
2231
                            const [selectedCol, selectedRow] = gridSelection.current.cell;
22✔
2232
                            const [prevCol, prevRow] = mouse.previousSelection.current.cell;
22✔
2233
                            const isClickOnSelected =
22✔
2234
                                col === selectedCol && col === prevCol && row === selectedRow && row === prevRow;
84✔
2235
                            shouldActivate =
84✔
2236
                                isClickOnSelected &&
84✔
2237
                                (a.isDoubleClick === true || cellActivationBehavior === "second-click");
6✔
2238
                            break;
84✔
2239
                        }
84✔
2240
                        case "single-click": {
101✔
2241
                            shouldActivate = true;
1✔
2242
                            break;
1✔
2243
                        }
1✔
2244
                    }
101✔
2245
                    if (shouldActivate) {
101✔
2246
                        onCellActivated?.([col - rowMarkerOffset, row]);
6✔
2247
                        reselect(a.bounds, false);
6✔
2248
                        return true;
6✔
2249
                    }
6✔
2250
                }
101✔
2251
                return false;
79✔
2252
            };
104✔
2253

134✔
2254
            const clickLocation = args.location[0] - rowMarkerOffset;
134✔
2255
            if (args.isTouch) {
134✔
2256
                const vr = visibleRegionRef.current;
4✔
2257
                const touchVr = touchDownArgs.current;
4✔
2258
                if (vr.x !== touchVr.x || vr.y !== touchVr.y) {
4!
2259
                    // we scrolled, abort
×
2260
                    return;
×
2261
                }
×
2262
                // take care of context menus first if long pressed item is already selected
4✔
2263
                if (args.isLongTouch === true) {
4!
2264
                    if (args.kind === "cell" && itemsAreEqual(gridSelection.current?.cell, args.location)) {
×
2265
                        onCellContextMenu?.([clickLocation, args.location[1]], {
×
2266
                            ...args,
×
2267
                            preventDefault,
×
2268
                        });
×
2269
                        return;
×
2270
                    } else if (args.kind === "header" && gridSelection.columns.hasIndex(col)) {
×
2271
                        onHeaderContextMenu?.(clickLocation, { ...args, preventDefault });
×
2272
                        return;
×
2273
                    } else if (args.kind === groupHeaderKind) {
×
2274
                        if (clickLocation < 0) {
×
2275
                            return;
×
UNCOV
2276
                        }
×
UNCOV
2277

×
UNCOV
2278
                        onGroupHeaderContextMenu?.(clickLocation, { ...args, preventDefault });
×
UNCOV
2279
                        return;
×
UNCOV
2280
                    }
×
UNCOV
2281
                }
×
2282
                if (args.kind === "cell") {
4✔
2283
                    // click that cell
2✔
2284
                    if (!handleMaybeClick(args)) {
2✔
2285
                        handleSelect(args);
2✔
2286
                    }
2✔
2287
                } else if (args.kind === groupHeaderKind) {
2✔
2288
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
1✔
2289
                } else {
1✔
2290
                    if (args.kind === headerKind) {
1✔
2291
                        onHeaderClicked?.(clickLocation, {
1✔
2292
                            ...args,
1✔
2293
                            preventDefault,
1✔
2294
                        });
1✔
2295
                    }
1✔
2296
                    handleSelect(args);
1✔
2297
                }
1✔
2298
                return;
4✔
2299
            }
4✔
2300

125✔
2301
            if (args.kind === "header") {
134✔
2302
                if (clickLocation < 0) {
16✔
2303
                    return;
3✔
2304
                }
3✔
2305

13✔
2306
                if (args.isEdge) {
16✔
2307
                    void normalSizeColumn(col);
2✔
2308
                } else if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
16✔
2309
                    onHeaderClicked?.(clickLocation, { ...args, preventDefault });
5✔
2310
                }
5✔
2311
            }
16✔
2312

122✔
2313
            if (args.kind === groupHeaderKind) {
134✔
2314
                if (clickLocation < 0) {
3!
UNCOV
2315
                    return;
×
UNCOV
2316
                }
×
2317

3✔
2318
                if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
3✔
2319
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
3!
2320
                    if (!isPrevented.current) {
3✔
2321
                        handleGroupHeaderSelection(args);
3✔
2322
                    }
3✔
2323
                }
3✔
2324
            }
3✔
2325

122✔
2326
            if (args.kind === "cell" && (args.button === 0 || args.button === 1)) {
134✔
2327
                handleMaybeClick(args);
102✔
2328
            }
102✔
2329

122✔
2330
            lastMouseSelectLocation.current = undefined;
122✔
2331
        },
134✔
2332
        [
678✔
2333
            mouseState,
678✔
2334
            gridSelection,
678✔
2335
            rowMarkerOffset,
678✔
2336
            fillHighlightRegion,
678✔
2337
            fillPattern,
678✔
2338
            setGridSelection,
678✔
2339
            onCellClicked,
678✔
2340
            getMangledCellContent,
678✔
2341
            getCellRenderer,
678✔
2342
            cellActivationBehavior,
678✔
2343
            themeForCell,
678✔
2344
            mangledOnCellsEdited,
678✔
2345
            onCellActivated,
678✔
2346
            reselect,
678✔
2347
            onCellContextMenu,
678✔
2348
            onHeaderContextMenu,
678✔
2349
            onGroupHeaderContextMenu,
678✔
2350
            handleSelect,
678✔
2351
            onGroupHeaderClicked,
678✔
2352
            onHeaderClicked,
678✔
2353
            normalSizeColumn,
678✔
2354
            handleGroupHeaderSelection,
678✔
2355
        ]
678✔
2356
    );
678✔
2357

678✔
2358
    const onMouseMoveImpl = React.useCallback(
678✔
2359
        (args: GridMouseEventArgs) => {
678✔
2360
            const a: GridMouseEventArgs = {
38✔
2361
                ...args,
38✔
2362
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
38✔
2363
            };
38✔
2364
            onMouseMove?.(a);
38✔
2365
            setScrollDir(cv => {
38✔
2366
                if (isActivelyDraggingHeader.current) return [args.scrollEdge[0], 0];
38✔
2367
                if (args.scrollEdge[0] === cv?.[0] && args.scrollEdge[1] === cv[1]) return cv;
38✔
2368
                return mouseState === undefined || (mouseDownData.current?.location[0] ?? 0) < rowMarkerOffset
36!
2369
                    ? undefined
13✔
2370
                    : args.scrollEdge;
13✔
2371
            });
38✔
2372
        },
38✔
2373
        [mouseState, onMouseMove, rowMarkerOffset]
678✔
2374
    );
678✔
2375

678✔
2376
    const onHeaderMenuClickInner = React.useCallback(
678✔
2377
        (col: number, screenPosition: Rectangle) => {
678✔
2378
            onHeaderMenuClick?.(col - rowMarkerOffset, screenPosition);
1✔
2379
        },
1✔
2380
        [onHeaderMenuClick, rowMarkerOffset]
678✔
2381
    );
678✔
2382

678✔
2383
    const currentCell = gridSelection?.current?.cell;
678✔
2384
    const onVisibleRegionChangedImpl = React.useCallback(
678✔
2385
        (
678✔
2386
            region: Rectangle,
141✔
2387
            clientWidth: number,
141✔
2388
            clientHeight: number,
141✔
2389
            rightElWidth: number,
141✔
2390
            tx: number,
141✔
2391
            ty: number
141✔
2392
        ) => {
141✔
2393
            hasJustScrolled.current = false;
141✔
2394
            let selected = currentCell;
141✔
2395
            if (selected !== undefined) {
141✔
2396
                selected = [selected[0] - rowMarkerOffset, selected[1]];
10✔
2397
            }
10✔
2398
            const newRegion = {
141✔
2399
                x: region.x - rowMarkerOffset,
141✔
2400
                y: region.y,
141✔
2401
                width: region.width,
141✔
2402
                height: showTrailingBlankRow && region.y + region.height >= rows ? region.height - 1 : region.height,
141✔
2403
                tx,
141✔
2404
                ty,
141✔
2405
                extras: {
141✔
2406
                    selected,
141✔
2407
                    freezeRegion:
141✔
2408
                        freezeColumns === 0
141✔
2409
                            ? undefined
141!
2410
                            : {
×
2411
                                  x: 0,
×
UNCOV
2412
                                  y: region.y,
×
UNCOV
2413
                                  width: freezeColumns,
×
UNCOV
2414
                                  height: region.height,
×
UNCOV
2415
                              },
×
2416
                },
141✔
2417
            };
141✔
2418
            visibleRegionRef.current = newRegion;
141✔
2419
            setVisibleRegion(newRegion);
141✔
2420
            setClientSize([clientWidth, clientHeight, rightElWidth]);
141✔
2421
            onVisibleRegionChanged?.(newRegion, newRegion.tx, newRegion.ty, newRegion.extras);
141!
2422
        },
141✔
2423
        [
678✔
2424
            currentCell,
678✔
2425
            rowMarkerOffset,
678✔
2426
            showTrailingBlankRow,
678✔
2427
            rows,
678✔
2428
            freezeColumns,
678✔
2429
            setVisibleRegion,
678✔
2430
            onVisibleRegionChanged,
678✔
2431
        ]
678✔
2432
    );
678✔
2433

678✔
2434
    const onColumnMovedImpl = whenDefined(
678✔
2435
        onColumnMoved,
678✔
2436
        React.useCallback(
678✔
2437
            (startIndex: number, endIndex: number) => {
678✔
2438
                onColumnMoved?.(startIndex - rowMarkerOffset, endIndex - rowMarkerOffset);
1✔
2439
                if (columnSelect !== "none") {
1✔
2440
                    setSelectedColumns(CompactSelection.fromSingleSelection(endIndex), undefined, true);
1✔
2441
                }
1✔
2442
            },
1✔
2443
            [columnSelect, onColumnMoved, rowMarkerOffset, setSelectedColumns]
678✔
2444
        )
678✔
2445
    );
678✔
2446

678✔
2447
    const isActivelyDragging = React.useRef(false);
678✔
2448
    const onDragStartImpl = React.useCallback(
678✔
2449
        (args: GridDragEventArgs) => {
678✔
2450
            if (args.location[0] === 0 && rowMarkerOffset > 0) {
1!
UNCOV
2451
                args.preventDefault();
×
UNCOV
2452
                return;
×
UNCOV
2453
            }
×
2454
            onDragStart?.({
1✔
2455
                ...args,
1✔
2456
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
1✔
2457
            });
1✔
2458

1✔
2459
            if (!args.defaultPrevented()) {
1✔
2460
                isActivelyDragging.current = true;
1✔
2461
            }
1✔
2462
            setMouseState(undefined);
1✔
2463
        },
1✔
2464
        [onDragStart, rowMarkerOffset]
678✔
2465
    );
678✔
2466

678✔
2467
    const onDragEnd = React.useCallback(() => {
678✔
UNCOV
2468
        isActivelyDragging.current = false;
×
2469
    }, []);
678✔
2470

678✔
2471
    const hoveredRef = React.useRef<GridMouseEventArgs>();
678✔
2472
    const onItemHoveredImpl = React.useCallback(
678✔
2473
        (args: GridMouseEventArgs) => {
678✔
2474
            if (mouseEventArgsAreEqual(args, hoveredRef.current)) return;
33!
2475
            hoveredRef.current = args;
33✔
2476
            if (mouseDownData?.current?.button !== undefined && mouseDownData.current.button >= 1) return;
33✔
2477
            if (
32✔
2478
                mouseState !== undefined &&
32✔
2479
                mouseDownData.current?.location[0] === 0 &&
19✔
2480
                args.location[0] === 0 &&
3✔
2481
                rowMarkerOffset === 1 &&
3✔
2482
                rowSelect === "multi" &&
3✔
2483
                mouseState.previousSelection &&
2✔
2484
                !mouseState.previousSelection.rows.hasIndex(mouseDownData.current.location[1]) &&
2✔
2485
                gridSelection.rows.hasIndex(mouseDownData.current.location[1])
2✔
2486
            ) {
33✔
2487
                const start = Math.min(mouseDownData.current.location[1], args.location[1]);
2✔
2488
                const end = Math.max(mouseDownData.current.location[1], args.location[1]) + 1;
2✔
2489
                setSelectedRows(CompactSelection.fromSingleSelection([start, end]), undefined, false);
2✔
2490
            }
2✔
2491
            if (
32✔
2492
                mouseState !== undefined &&
32✔
2493
                gridSelection.current !== undefined &&
19✔
2494
                !isActivelyDragging.current &&
17✔
2495
                !isActivelyDraggingHeader.current &&
17✔
2496
                (rangeSelect === "rect" || rangeSelect === "multi-rect")
15✔
2497
            ) {
33✔
2498
                const [selectedCol, selectedRow] = gridSelection.current.cell;
11✔
2499
                // eslint-disable-next-line prefer-const
11✔
2500
                let [col, row] = args.location;
11✔
2501

11✔
2502
                if (row < 0) {
11✔
2503
                    row = visibleRegionRef.current.y;
1✔
2504
                }
1✔
2505

11✔
2506
                if (mouseState.fillHandle === true && mouseState.previousSelection?.current !== undefined) {
11✔
2507
                    const prevRange = mouseState.previousSelection.current.range;
5✔
2508
                    row = Math.min(row, lastRowSticky ? rows - 1 : rows);
5!
2509
                    const rect = getClosestRect(prevRange, col, row, allowedFillDirections);
5✔
2510
                    setFillHighlightRegion(rect);
5✔
2511
                } else {
11✔
2512
                    const startedFromLastStickyRow = lastRowSticky && selectedRow === rows;
6✔
2513
                    if (startedFromLastStickyRow) return;
6!
2514

6✔
2515
                    const landedOnLastStickyRow = lastRowSticky && row === rows;
6✔
2516
                    if (landedOnLastStickyRow) {
6!
UNCOV
2517
                        if (args.kind === outOfBoundsKind) row--;
×
UNCOV
2518
                        else return;
×
UNCOV
2519
                    }
×
2520

6✔
2521
                    col = Math.max(col, rowMarkerOffset);
6✔
2522

6✔
2523
                    const deltaX = col - selectedCol;
6✔
2524
                    const deltaY = row - selectedRow;
6✔
2525

6✔
2526
                    const newRange: Rectangle = {
6✔
2527
                        x: deltaX >= 0 ? selectedCol : col,
6!
2528
                        y: deltaY >= 0 ? selectedRow : row,
6✔
2529
                        width: Math.abs(deltaX) + 1,
6✔
2530
                        height: Math.abs(deltaY) + 1,
6✔
2531
                    };
6✔
2532

6✔
2533
                    setCurrent(
6✔
2534
                        {
6✔
2535
                            ...gridSelection.current,
6✔
2536
                            range: newRange,
6✔
2537
                        },
6✔
2538
                        true,
6✔
2539
                        false,
6✔
2540
                        "drag"
6✔
2541
                    );
6✔
2542
                }
6✔
2543
            }
11✔
2544

32✔
2545
            onItemHovered?.({ ...args, location: [args.location[0] - rowMarkerOffset, args.location[1]] as any });
33✔
2546
        },
33✔
2547
        [
678✔
2548
            allowedFillDirections,
678✔
2549
            mouseState,
678✔
2550
            rowMarkerOffset,
678✔
2551
            rowSelect,
678✔
2552
            gridSelection,
678✔
2553
            rangeSelect,
678✔
2554
            onItemHovered,
678✔
2555
            setSelectedRows,
678✔
2556
            lastRowSticky,
678✔
2557
            rows,
678✔
2558
            setCurrent,
678✔
2559
        ]
678✔
2560
    );
678✔
2561

678✔
2562
    const adjustSelectionOnScroll = React.useCallback(() => {
678✔
2563
        const args = hoveredRef.current;
×
2564
        if (args === undefined) return;
×
2565
        const [xDir, yDir] = args.scrollEdge;
×
2566
        let [col, row] = args.location;
×
2567
        const visible = visibleRegionRef.current;
×
2568
        if (xDir === -1) {
×
2569
            col = visible.x;
×
2570
        } else if (xDir === 1) {
×
2571
            col = visible.x + visible.width;
×
2572
        }
×
2573
        if (yDir === -1) {
×
2574
            row = Math.max(0, visible.y);
×
2575
        } else if (yDir === 1) {
×
2576
            row = Math.min(rows, visible.y + visible.height);
×
2577
        }
×
UNCOV
2578
        onItemHoveredImpl({
×
UNCOV
2579
            ...args,
×
UNCOV
2580
            location: [col, row] as any,
×
UNCOV
2581
        });
×
2582
    }, [onItemHoveredImpl, rows]);
678✔
2583

678✔
2584
    useAutoscroll(scrollDir, scrollRef, adjustSelectionOnScroll);
678✔
2585

678✔
2586
    // 1 === move one
678✔
2587
    // 2 === move to end
678✔
2588
    const adjustSelection = React.useCallback(
678✔
2589
        (direction: [0 | 1 | -1 | 2 | -2, 0 | 1 | -1 | 2 | -2]) => {
678✔
2590
            if (gridSelection.current === undefined) return;
8!
2591

8✔
2592
            const [x, y] = direction;
8✔
2593
            const [col, row] = gridSelection.current.cell;
8✔
2594
            const old = gridSelection.current.range;
8✔
2595
            let left = old.x;
8✔
2596
            let right = old.x + old.width;
8✔
2597
            let top = old.y;
8✔
2598
            let bottom = old.y + old.height;
8✔
2599

8✔
2600
            // take care of vertical first in case new spans come in
8✔
2601
            if (y !== 0) {
8✔
2602
                switch (y) {
2✔
2603
                    case 2: {
2✔
2604
                        // go to end
1✔
2605
                        bottom = rows;
1✔
2606
                        top = row;
1✔
2607
                        scrollTo(0, bottom, "vertical");
1✔
2608

1✔
2609
                        break;
1✔
2610
                    }
1✔
2611
                    case -2: {
2!
2612
                        // go to start
×
2613
                        top = 0;
×
2614
                        bottom = row + 1;
×
UNCOV
2615
                        scrollTo(0, top, "vertical");
×
UNCOV
2616

×
UNCOV
2617
                        break;
×
2618
                    }
×
2619
                    case 1: {
2✔
2620
                        // motion down
1✔
2621
                        if (top < row) {
1!
UNCOV
2622
                            top++;
×
UNCOV
2623
                            scrollTo(0, top, "vertical");
×
2624
                        } else {
1✔
2625
                            bottom = Math.min(rows, bottom + 1);
1✔
2626
                            scrollTo(0, bottom, "vertical");
1✔
2627
                        }
1✔
2628

1✔
2629
                        break;
1✔
2630
                    }
1✔
2631
                    case -1: {
2!
2632
                        // motion up
×
2633
                        if (bottom > row + 1) {
×
2634
                            bottom--;
×
2635
                            scrollTo(0, bottom, "vertical");
×
2636
                        } else {
×
2637
                            top = Math.max(0, top - 1);
×
2638
                            scrollTo(0, top, "vertical");
×
UNCOV
2639
                        }
×
2640

×
2641
                        break;
×
UNCOV
2642
                    }
×
2643
                    default: {
2!
UNCOV
2644
                        assertNever(y);
×
UNCOV
2645
                    }
×
2646
                }
2✔
2647
            }
2✔
2648

8✔
2649
            if (x !== 0) {
8✔
2650
                if (x === 2) {
6✔
2651
                    right = mangledCols.length;
1✔
2652
                    left = col;
1✔
2653
                    scrollTo(right - 1 - rowMarkerOffset, 0, "horizontal");
1✔
2654
                } else if (x === -2) {
6!
UNCOV
2655
                    left = rowMarkerOffset;
×
UNCOV
2656
                    right = col + 1;
×
UNCOV
2657
                    scrollTo(left - rowMarkerOffset, 0, "horizontal");
×
2658
                } else {
5✔
2659
                    let disallowed: number[] = [];
5✔
2660
                    if (getCellsForSelection !== undefined) {
5✔
2661
                        const cells = getCellsForSelection(
5✔
2662
                            {
5✔
2663
                                x: left,
5✔
2664
                                y: top,
5✔
2665
                                width: right - left - rowMarkerOffset,
5✔
2666
                                height: bottom - top,
5✔
2667
                            },
5✔
2668
                            abortControllerRef.current.signal
5✔
2669
                        );
5✔
2670

5✔
2671
                        if (typeof cells === "object") {
5✔
2672
                            disallowed = getSpanStops(cells);
5✔
2673
                        }
5✔
2674
                    }
5✔
2675
                    if (x === 1) {
5✔
2676
                        // motion right
4✔
2677
                        let done = false;
4✔
2678
                        if (left < col) {
4!
2679
                            if (disallowed.length > 0) {
×
2680
                                const target = range(left + 1, col + 1).find(
×
2681
                                    n => !disallowed.includes(n - rowMarkerOffset)
×
2682
                                );
×
2683
                                if (target !== undefined) {
×
2684
                                    left = target;
×
2685
                                    done = true;
×
2686
                                }
×
2687
                            } else {
×
2688
                                left++;
×
UNCOV
2689
                                done = true;
×
UNCOV
2690
                            }
×
UNCOV
2691
                            if (done) scrollTo(left, 0, "horizontal");
×
UNCOV
2692
                        }
×
2693
                        if (!done) {
4✔
2694
                            right = Math.min(mangledCols.length, right + 1);
4✔
2695
                            scrollTo(right - 1 - rowMarkerOffset, 0, "horizontal");
4✔
2696
                        }
4✔
2697
                    } else if (x === -1) {
5✔
2698
                        // motion left
1✔
2699
                        let done = false;
1✔
2700
                        if (right > col + 1) {
1!
2701
                            if (disallowed.length > 0) {
×
2702
                                const target = range(right - 1, col, -1).find(
×
2703
                                    n => !disallowed.includes(n - rowMarkerOffset)
×
2704
                                );
×
2705
                                if (target !== undefined) {
×
2706
                                    right = target;
×
2707
                                    done = true;
×
2708
                                }
×
2709
                            } else {
×
2710
                                right--;
×
UNCOV
2711
                                done = true;
×
UNCOV
2712
                            }
×
UNCOV
2713
                            if (done) scrollTo(right - rowMarkerOffset, 0, "horizontal");
×
UNCOV
2714
                        }
×
2715
                        if (!done) {
1✔
2716
                            left = Math.max(rowMarkerOffset, left - 1);
1✔
2717
                            scrollTo(left - rowMarkerOffset, 0, "horizontal");
1✔
2718
                        }
1✔
2719
                    } else {
1!
UNCOV
2720
                        assertNever(x);
×
UNCOV
2721
                    }
×
2722
                }
5✔
2723
            }
6✔
2724

8✔
2725
            setCurrent(
8✔
2726
                {
8✔
2727
                    cell: gridSelection.current.cell,
8✔
2728
                    range: {
8✔
2729
                        x: left,
8✔
2730
                        y: top,
8✔
2731
                        width: right - left,
8✔
2732
                        height: bottom - top,
8✔
2733
                    },
8✔
2734
                },
8✔
2735
                true,
8✔
2736
                false,
8✔
2737
                "keyboard-select"
8✔
2738
            );
8✔
2739
        },
8✔
2740
        [getCellsForSelection, gridSelection, mangledCols.length, rowMarkerOffset, rows, scrollTo, setCurrent]
678✔
2741
    );
678✔
2742

678✔
2743
    const updateSelectedCell = React.useCallback(
678✔
2744
        (col: number, row: number, fromEditingTrailingRow: boolean, freeMove: boolean): boolean => {
678✔
2745
            const rowMax = mangledRows - (fromEditingTrailingRow ? 0 : 1);
53!
2746
            col = clamp(col, rowMarkerOffset, columns.length - 1 + rowMarkerOffset);
53✔
2747
            row = clamp(row, 0, rowMax);
53✔
2748

53✔
2749
            if (col === currentCell?.[0] && row === currentCell?.[1]) return false;
53✔
2750
            if (freeMove && gridSelection.current !== undefined) {
53✔
2751
                const newStack = [...gridSelection.current.rangeStack];
1✔
2752
                if (gridSelection.current.range.width > 1 || gridSelection.current.range.height > 1) {
1!
2753
                    newStack.push(gridSelection.current.range);
1✔
2754
                }
1✔
2755
                setGridSelection(
1✔
2756
                    {
1✔
2757
                        ...gridSelection,
1✔
2758
                        current: {
1✔
2759
                            cell: [col, row],
1✔
2760
                            range: { x: col, y: row, width: 1, height: 1 },
1✔
2761
                            rangeStack: newStack,
1✔
2762
                        },
1✔
2763
                    },
1✔
2764
                    true
1✔
2765
                );
1✔
2766
            } else {
53✔
2767
                setCurrent(
25✔
2768
                    {
25✔
2769
                        cell: [col, row],
25✔
2770
                        range: { x: col, y: row, width: 1, height: 1 },
25✔
2771
                    },
25✔
2772
                    true,
25✔
2773
                    false,
25✔
2774
                    "keyboard-nav"
25✔
2775
                );
25✔
2776
            }
25✔
2777

26✔
2778
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
53✔
2779
                lastSent.current = undefined;
2✔
2780
            }
2✔
2781

26✔
2782
            scrollTo(col - rowMarkerOffset, row);
26✔
2783

26✔
2784
            return true;
26✔
2785
        },
53✔
2786
        [
678✔
2787
            mangledRows,
678✔
2788
            rowMarkerOffset,
678✔
2789
            columns.length,
678✔
2790
            currentCell,
678✔
2791
            gridSelection,
678✔
2792
            scrollTo,
678✔
2793
            setGridSelection,
678✔
2794
            setCurrent,
678✔
2795
        ]
678✔
2796
    );
678✔
2797

678✔
2798
    const onFinishEditing = React.useCallback(
678✔
2799
        (newValue: GridCell | undefined, movement: readonly [-1 | 0 | 1, -1 | 0 | 1]) => {
678✔
2800
            if (overlay?.cell !== undefined && newValue !== undefined && isEditableGridCell(newValue)) {
7✔
2801
                mangledOnCellsEdited([{ location: overlay.cell, value: newValue }]);
4✔
2802
                window.requestAnimationFrame(() => {
4✔
2803
                    gridRef.current?.damage([
4✔
2804
                        {
4✔
2805
                            cell: overlay.cell,
4✔
2806
                        },
4✔
2807
                    ]);
4✔
2808
                });
4✔
2809
            }
4✔
2810
            focus(true);
7✔
2811
            setOverlay(undefined);
7✔
2812

7✔
2813
            const [movX, movY] = movement;
7✔
2814
            if (gridSelection.current !== undefined && (movX !== 0 || movY !== 0)) {
7✔
2815
                const isEditingTrailingRow =
3✔
2816
                    gridSelection.current.cell[1] === mangledRows - 1 && newValue !== undefined;
3!
2817
                updateSelectedCell(
3✔
2818
                    clamp(gridSelection.current.cell[0] + movX, 0, mangledCols.length - 1),
3✔
2819
                    clamp(gridSelection.current.cell[1] + movY, 0, mangledRows - 1),
3✔
2820
                    isEditingTrailingRow,
3✔
2821
                    false
3✔
2822
                );
3✔
2823
            }
3✔
2824
            onFinishedEditing?.(newValue, movement);
7✔
2825
        },
7✔
2826
        [
678✔
2827
            overlay?.cell,
678✔
2828
            focus,
678✔
2829
            gridSelection,
678✔
2830
            onFinishedEditing,
678✔
2831
            mangledOnCellsEdited,
678✔
2832
            mangledRows,
678✔
2833
            updateSelectedCell,
678✔
2834
            mangledCols.length,
678✔
2835
        ]
678✔
2836
    );
678✔
2837

678✔
2838
    const overlayID = React.useMemo(() => {
678✔
2839
        return `gdg-overlay-${idCounter++}`;
137✔
2840
    }, []);
678✔
2841

678✔
2842
    const deleteRange = React.useCallback(
678✔
2843
        (r: Rectangle) => {
678✔
2844
            focus();
8✔
2845
            const editList: EditListItem[] = [];
8✔
2846
            for (let x = r.x; x < r.x + r.width; x++) {
8✔
2847
                for (let y = r.y; y < r.y + r.height; y++) {
23✔
2848
                    const cellValue = getCellContent([x - rowMarkerOffset, y]);
1,066✔
2849
                    if (!cellValue.allowOverlay && cellValue.kind !== GridCellKind.Boolean) continue;
1,066✔
2850
                    let newVal: InnerGridCell | undefined = undefined;
1,042✔
2851
                    if (cellValue.kind === GridCellKind.Custom) {
1,066✔
2852
                        const toDelete = getCellRenderer(cellValue);
1✔
2853
                        const editor = toDelete?.provideEditor?.(cellValue);
1!
2854
                        if (toDelete?.onDelete !== undefined) {
1✔
2855
                            newVal = toDelete.onDelete(cellValue);
1✔
2856
                        } else if (isObjectEditorCallbackResult(editor)) {
1!
UNCOV
2857
                            newVal = editor?.deletedValue?.(cellValue);
×
UNCOV
2858
                        }
×
2859
                    } else if (
1✔
2860
                        (isEditableGridCell(cellValue) && cellValue.allowOverlay) ||
1,041✔
2861
                        cellValue.kind === GridCellKind.Boolean
1✔
2862
                    ) {
1,041✔
2863
                        const toDelete = getCellRenderer(cellValue);
1,041✔
2864
                        newVal = toDelete?.onDelete?.(cellValue);
1,041✔
2865
                    }
1,041✔
2866
                    if (newVal !== undefined && !isInnerOnlyCell(newVal) && isEditableGridCell(newVal)) {
1,066✔
2867
                        editList.push({ location: [x, y], value: newVal });
1,041✔
2868
                    }
1,041✔
2869
                }
1,066✔
2870
            }
23✔
2871
            mangledOnCellsEdited(editList);
8✔
2872
            gridRef.current?.damage(editList.map(x => ({ cell: x.location })));
8✔
2873
        },
8✔
2874
        [focus, getCellContent, getCellRenderer, mangledOnCellsEdited, rowMarkerOffset]
678✔
2875
    );
678✔
2876

678✔
2877
    const onKeyDown = React.useCallback(
678✔
2878
        (event: GridKeyEventArgs) => {
678✔
2879
            const fn = async () => {
61✔
2880
                let cancelled = false;
61✔
2881
                if (onKeyDownIn !== undefined) {
61✔
2882
                    onKeyDownIn({
1✔
2883
                        ...event,
1✔
2884
                        cancel: () => {
1✔
UNCOV
2885
                            cancelled = true;
×
UNCOV
2886
                        },
×
2887
                    });
1✔
2888
                }
1✔
2889

61✔
2890
                if (cancelled) return;
61!
2891

61✔
2892
                const cancel = () => {
61✔
2893
                    event.stopPropagation();
42✔
2894
                    event.preventDefault();
42✔
2895
                };
42✔
2896

61✔
2897
                const overlayOpen = overlay !== undefined;
61✔
2898
                const { altKey, shiftKey, metaKey, ctrlKey, key, bounds } = event;
61✔
2899
                const isOSX = browserIsOSX.value;
61✔
2900
                const isPrimaryKey = isOSX ? metaKey : ctrlKey;
61!
2901
                const isDeleteKey = key === "Delete" || (isOSX && key === "Backspace");
61!
2902
                const vr = visibleRegionRef.current;
61✔
2903
                const selectedColumns = gridSelection.columns;
61✔
2904
                const selectedRows = gridSelection.rows;
61✔
2905

61✔
2906
                if (key === "Escape") {
61✔
2907
                    if (overlayOpen) {
4✔
2908
                        setOverlay(undefined);
2✔
2909
                    } else if (keybindings.clear) {
2✔
2910
                        setGridSelection(emptyGridSelection, false);
2✔
2911
                        onSelectionCleared?.();
2!
2912
                    }
2✔
2913
                    return;
4✔
2914
                } else if (isHotkey("primary+a", event) && keybindings.selectAll) {
61✔
2915
                    if (!overlayOpen) {
1✔
2916
                        setGridSelection(
1✔
2917
                            {
1✔
2918
                                columns: CompactSelection.empty(),
1✔
2919
                                rows: CompactSelection.empty(),
1✔
2920
                                current: {
1✔
2921
                                    cell: gridSelection.current?.cell ?? [rowMarkerOffset, 0],
1!
2922
                                    range: {
1✔
2923
                                        x: rowMarkerOffset,
1✔
2924
                                        y: 0,
1✔
2925
                                        width: columnsIn.length,
1✔
2926
                                        height: rows,
1✔
2927
                                    },
1✔
2928
                                    rangeStack: [],
1✔
2929
                                },
1✔
2930
                            },
1✔
2931
                            false
1✔
2932
                        );
1✔
2933
                    } else {
1!
2934
                        const el = document.getElementById(overlayID);
×
2935
                        if (el !== null) {
×
2936
                            const s = window.getSelection();
×
2937
                            const r = document.createRange();
×
2938
                            r.selectNodeContents(el);
×
UNCOV
2939
                            s?.removeAllRanges();
×
UNCOV
2940
                            s?.addRange(r);
×
UNCOV
2941
                        }
×
2942
                    }
×
2943
                    cancel();
1✔
2944
                    return;
1✔
2945
                } else if (isHotkey("primary+f", event) && keybindings.search) {
57!
UNCOV
2946
                    cancel();
×
UNCOV
2947
                    searchInputRef?.current?.focus({ preventScroll: true });
×
UNCOV
2948
                    setShowSearchInner(true);
×
UNCOV
2949
                }
✔
2950

56✔
2951
                if (isDeleteKey) {
61✔
2952
                    const callbackResult = onDelete?.(gridSelection) ?? true;
8✔
2953
                    cancel();
8✔
2954
                    if (callbackResult !== false) {
8✔
2955
                        const toDelete = callbackResult === true ? gridSelection : callbackResult;
8✔
2956

8✔
2957
                        // delete order:
8✔
2958
                        // 1) primary range
8✔
2959
                        // 2) secondary ranges
8✔
2960
                        // 3) columns
8✔
2961
                        // 4) rows
8✔
2962

8✔
2963
                        if (toDelete.current !== undefined) {
8✔
2964
                            deleteRange(toDelete.current.range);
5✔
2965
                            for (const r of toDelete.current.rangeStack) {
5!
UNCOV
2966
                                deleteRange(r);
×
UNCOV
2967
                            }
×
2968
                        }
5✔
2969

8✔
2970
                        for (const r of toDelete.rows) {
8✔
2971
                            deleteRange({
1✔
2972
                                x: rowMarkerOffset,
1✔
2973
                                y: r,
1✔
2974
                                width: mangledCols.length - rowMarkerOffset,
1✔
2975
                                height: 1,
1✔
2976
                            });
1✔
2977
                        }
1✔
2978

8✔
2979
                        for (const col of toDelete.columns) {
8✔
2980
                            deleteRange({
1✔
2981
                                x: col,
1✔
2982
                                y: 0,
1✔
2983
                                width: 1,
1✔
2984
                                height: rows,
1✔
2985
                            });
1✔
2986
                        }
1✔
2987
                    }
8✔
2988
                    return;
8✔
2989
                }
8✔
2990

48✔
2991
                if (gridSelection.current === undefined) return;
48✔
2992
                let [col, row] = gridSelection.current.cell;
45✔
2993
                let freeMove = false;
45✔
2994

45✔
2995
                if (keybindings.selectColumn && isHotkey("ctrl+ ", event) && columnSelect !== "none") {
61✔
2996
                    if (selectedColumns.hasIndex(col)) {
2!
UNCOV
2997
                        setSelectedColumns(selectedColumns.remove(col), undefined, true);
×
2998
                    } else {
2✔
2999
                        if (columnSelect === "single") {
2!
UNCOV
3000
                            setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, true);
×
3001
                        } else {
2✔
3002
                            setSelectedColumns(undefined, col, true);
2✔
3003
                        }
2✔
3004
                    }
2✔
3005
                } else if (keybindings.selectRow && isHotkey("shift+ ", event) && rowSelect !== "none") {
61✔
3006
                    if (selectedRows.hasIndex(row)) {
2!
UNCOV
3007
                        setSelectedRows(selectedRows.remove(row), undefined, true);
×
3008
                    } else {
2✔
3009
                        if (rowSelect === "single") {
2!
UNCOV
3010
                            setSelectedRows(CompactSelection.fromSingleSelection(row), undefined, true);
×
3011
                        } else {
2✔
3012
                            setSelectedRows(undefined, row, true);
2✔
3013
                        }
2✔
3014
                    }
2✔
3015
                } else if (
2✔
3016
                    (isHotkey("Enter", event) || isHotkey(" ", event) || isHotkey("shift+Enter", event)) &&
41✔
3017
                    bounds !== undefined
8✔
3018
                ) {
41✔
3019
                    if (overlayOpen) {
8✔
3020
                        setOverlay(undefined);
2✔
3021
                        if (isHotkey("Enter", event)) {
2✔
3022
                            row++;
2✔
3023
                        } else if (isHotkey("shift+Enter", event)) {
2!
3024
                            row--;
×
3025
                        }
×
3026
                    } else if (row === rows && showTrailingBlankRow) {
8!
UNCOV
3027
                        window.setTimeout(() => {
×
UNCOV
3028
                            const customTargetColumn = getCustomNewRowTargetColumn(col);
×
UNCOV
3029
                            void appendRow(customTargetColumn ?? col);
×
UNCOV
3030
                        }, 0);
×
3031
                    } else {
6✔
3032
                        onCellActivated?.([col - rowMarkerOffset, row]);
6✔
3033
                        reselect(bounds, true);
6✔
3034
                        cancel();
6✔
3035
                    }
6✔
3036
                } else if (
8✔
3037
                    keybindings.downFill &&
33✔
3038
                    isHotkey("primary+_68", event) &&
1✔
3039
                    gridSelection.current.range.height > 1
1✔
3040
                ) {
33✔
3041
                    // ctrl/cmd + d
1✔
3042
                    fillDown(false);
1✔
3043
                    cancel();
1✔
3044
                } else if (
1✔
3045
                    keybindings.rightFill &&
32✔
3046
                    isHotkey("primary+_82", event) &&
1✔
3047
                    gridSelection.current.range.width > 1
1✔
3048
                ) {
32✔
3049
                    // ctrl/cmd + r
1✔
3050
                    const editList: EditListItem[] = [];
1✔
3051
                    const r = gridSelection.current.range;
1✔
3052
                    for (let y = 0; y < r.height; y++) {
1✔
3053
                        const fillRow = y + r.y;
5✔
3054
                        const fillVal = getMangledCellContent([r.x, fillRow]);
5✔
3055
                        if (isInnerOnlyCell(fillVal) || !isReadWriteCell(fillVal)) continue;
5!
3056
                        for (let x = 1; x < r.width; x++) {
5✔
3057
                            const fillCol = x + r.x;
5✔
3058
                            const target = [fillCol, fillRow] as const;
5✔
3059
                            editList.push({
5✔
3060
                                location: target,
5✔
3061
                                value: { ...fillVal },
5✔
3062
                            });
5✔
3063
                        }
5✔
3064
                    }
5✔
3065
                    mangledOnCellsEdited(editList);
1✔
3066
                    gridRef.current?.damage(
1✔
3067
                        editList.map(c => ({
1✔
3068
                            cell: c.location,
5✔
3069
                        }))
1✔
3070
                    );
1✔
3071
                    cancel();
1✔
3072
                } else if (keybindings.pageDown && isHotkey("PageDown", event)) {
32!
3073
                    row += Math.max(1, visibleRegionRef.current.height - 4); // partial cell accounting
×
UNCOV
3074
                    cancel();
×
3075
                } else if (keybindings.pageUp && isHotkey("PageUp", event)) {
31!
3076
                    row -= Math.max(1, visibleRegionRef.current.height - 4); // partial cell accounting
×
3077
                    cancel();
×
3078
                } else if (keybindings.first && isHotkey("primary+Home", event)) {
31!
3079
                    setOverlay(undefined);
×
3080
                    row = 0;
×
3081
                    col = 0;
×
3082
                } else if (keybindings.last && isHotkey("primary+End", event)) {
31!
3083
                    setOverlay(undefined);
×
3084
                    row = Number.MAX_SAFE_INTEGER;
×
UNCOV
3085
                    col = Number.MAX_SAFE_INTEGER;
×
3086
                } else if (keybindings.first && isHotkey("primary+shift+Home", event)) {
31!
3087
                    setOverlay(undefined);
×
3088
                    adjustSelection([-2, -2]);
×
3089
                } else if (keybindings.last && isHotkey("primary+shift+End", event)) {
31!
UNCOV
3090
                    setOverlay(undefined);
×
3091
                    adjustSelection([2, 2]);
×
3092
                    // eslint-disable-next-line unicorn/prefer-switch
×
3093
                } else if (key === "ArrowDown") {
31✔
3094
                    if (ctrlKey && altKey) {
8!
UNCOV
3095
                        return;
×
UNCOV
3096
                    }
×
3097
                    setOverlay(undefined);
8✔
3098
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
8!
3099
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
2✔
3100
                        adjustSelection([0, isPrimaryKey && !altKey ? 2 : 1]);
2✔
3101
                    } else {
8✔
3102
                        if (altKey && !isPrimaryKey) {
6!
UNCOV
3103
                            freeMove = true;
×
UNCOV
3104
                        }
×
3105
                        if (isPrimaryKey && !altKey) {
6✔
3106
                            row = rows - 1;
1✔
3107
                        } else {
6✔
3108
                            row += 1;
5✔
3109
                        }
5✔
3110
                    }
6✔
3111
                } else if (key === "ArrowUp" || key === "Home") {
31✔
3112
                    const asPrimary = key === "Home" || isPrimaryKey;
2✔
3113
                    setOverlay(undefined);
2✔
3114
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
2!
3115
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
×
3116
                        adjustSelection([0, asPrimary && !altKey ? -2 : -1]);
×
3117
                    } else {
2✔
3118
                        if (altKey && !asPrimary) {
2!
UNCOV
3119
                            freeMove = true;
×
UNCOV
3120
                        }
×
3121
                        row += asPrimary && !altKey ? Number.MIN_SAFE_INTEGER : -1;
2✔
3122
                    }
2✔
3123
                } else if (key === "ArrowRight" || key === "End") {
23✔
3124
                    const asPrimary = key === "End" || isPrimaryKey;
8✔
3125
                    setOverlay(undefined);
8✔
3126
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
8!
3127
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
5✔
3128
                        adjustSelection([asPrimary && !altKey ? 2 : 1, 0]);
5✔
3129
                    } else {
8✔
3130
                        if (altKey && !asPrimary) {
3!
UNCOV
3131
                            freeMove = true;
×
UNCOV
3132
                        }
×
3133
                        col += asPrimary && !altKey ? Number.MAX_SAFE_INTEGER : 1;
3✔
3134
                    }
3✔
3135
                } else if (key === "ArrowLeft") {
21✔
3136
                    setOverlay(undefined);
4✔
3137
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
4!
3138
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
1✔
3139
                        adjustSelection([isPrimaryKey && !altKey ? -2 : -1, 0]);
1!
3140
                    } else {
4✔
3141
                        if (altKey && !isPrimaryKey) {
3✔
3142
                            freeMove = true;
1✔
3143
                        }
1✔
3144
                        col += isPrimaryKey && !altKey ? Number.MIN_SAFE_INTEGER : -1;
3✔
3145
                    }
3✔
3146
                } else if (key === "Tab") {
13✔
3147
                    setOverlay(undefined);
2✔
3148
                    if (shiftKey) {
2✔
3149
                        col--;
1✔
3150
                    } else {
1✔
3151
                        col++;
1✔
3152
                    }
1✔
3153
                } else if (
2✔
3154
                    !metaKey &&
7✔
3155
                    !ctrlKey &&
7✔
3156
                    gridSelection.current !== undefined &&
7✔
3157
                    key.length === 1 &&
7✔
3158
                    /[ -~]/g.test(key) &&
7✔
3159
                    bounds !== undefined &&
7✔
3160
                    isReadWriteCell(getCellContent([col - rowMarkerOffset, Math.max(0, Math.min(row, rows - 1))]))
7✔
3161
                ) {
7✔
3162
                    if (
7✔
3163
                        (!lastRowSticky || row !== rows) &&
7✔
3164
                        (vr.y > row || row > vr.y + vr.height || vr.x > col || col > vr.x + vr.width)
7✔
3165
                    ) {
7!
UNCOV
3166
                        return;
×
UNCOV
3167
                    }
×
3168
                    reselect(bounds, true, key);
7✔
3169
                    cancel();
7✔
3170
                }
7✔
3171

45✔
3172
                const moved = updateSelectedCell(col, row, false, freeMove);
45✔
3173
                if (moved) {
61✔
3174
                    cancel();
18✔
3175
                }
18✔
3176
            };
61✔
3177
            void fn();
61✔
3178
        },
61✔
3179
        [
678✔
3180
            onKeyDownIn,
678✔
3181
            deleteRange,
678✔
3182
            overlay,
678✔
3183
            gridSelection,
678✔
3184
            keybindings.selectAll,
678✔
3185
            keybindings.search,
678✔
3186
            keybindings.selectColumn,
678✔
3187
            keybindings.selectRow,
678✔
3188
            keybindings.downFill,
678✔
3189
            keybindings.rightFill,
678✔
3190
            keybindings.pageDown,
678✔
3191
            keybindings.pageUp,
678✔
3192
            keybindings.first,
678✔
3193
            keybindings.last,
678✔
3194
            keybindings.clear,
678✔
3195
            columnSelect,
678✔
3196
            rowSelect,
678✔
3197
            getCellContent,
678✔
3198
            rowMarkerOffset,
678✔
3199
            updateSelectedCell,
678✔
3200
            setGridSelection,
678✔
3201
            onSelectionCleared,
678✔
3202
            columnsIn.length,
678✔
3203
            rows,
678✔
3204
            overlayID,
678✔
3205
            mangledOnCellsEdited,
678✔
3206
            onDelete,
678✔
3207
            mangledCols.length,
678✔
3208
            setSelectedColumns,
678✔
3209
            setSelectedRows,
678✔
3210
            showTrailingBlankRow,
678✔
3211
            getCustomNewRowTargetColumn,
678✔
3212
            appendRow,
678✔
3213
            onCellActivated,
678✔
3214
            reselect,
678✔
3215
            fillDown,
678✔
3216
            getMangledCellContent,
678✔
3217
            adjustSelection,
678✔
3218
            rangeSelect,
678✔
3219
            lastRowSticky,
678✔
3220
        ]
678✔
3221
    );
678✔
3222

678✔
3223
    const onContextMenu = React.useCallback(
678✔
3224
        (args: GridMouseEventArgs, preventDefault: () => void) => {
678✔
3225
            const adjustedCol = args.location[0] - rowMarkerOffset;
7✔
3226
            if (args.kind === "header") {
7!
3227
                onHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
3228
            }
×
3229

7✔
3230
            if (args.kind === groupHeaderKind) {
7!
3231
                if (adjustedCol < 0) {
×
UNCOV
3232
                    return;
×
UNCOV
3233
                }
×
UNCOV
3234
                onGroupHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
UNCOV
3235
            }
×
3236

7✔
3237
            if (args.kind === "cell") {
7✔
3238
                const [col, row] = args.location;
7✔
3239
                onCellContextMenu?.([adjustedCol, row], {
7✔
3240
                    ...args,
7✔
3241
                    preventDefault,
7✔
3242
                });
7✔
3243

7✔
3244
                if (!gridSelectionHasItem(gridSelection, args.location)) {
7✔
3245
                    updateSelectedCell(col, row, false, false);
3✔
3246
                }
3✔
3247
            }
7✔
3248
        },
7✔
3249
        [
678✔
3250
            gridSelection,
678✔
3251
            onCellContextMenu,
678✔
3252
            onGroupHeaderContextMenu,
678✔
3253
            onHeaderContextMenu,
678✔
3254
            rowMarkerOffset,
678✔
3255
            updateSelectedCell,
678✔
3256
        ]
678✔
3257
    );
678✔
3258

678✔
3259
    const onPasteInternal = React.useCallback(
678✔
3260
        async (e?: ClipboardEvent) => {
678✔
3261
            if (!keybindings.paste) return;
6!
3262
            function pasteToCell(
6✔
3263
                inner: InnerGridCell,
51✔
3264
                target: Item,
51✔
3265
                rawValue: string | boolean | string[] | number | boolean | BooleanEmpty | BooleanIndeterminate,
51✔
3266
                formatted?: string | string[]
51✔
3267
            ): EditListItem | undefined {
51✔
3268
                const stringifiedRawValue =
51✔
3269
                    typeof rawValue === "object" ? rawValue?.join("\n") ?? "" : rawValue?.toString() ?? "";
51!
3270

51✔
3271
                if (!isInnerOnlyCell(inner) && isReadWriteCell(inner) && inner.readonly !== true) {
51✔
3272
                    const coerced = coercePasteValue?.(stringifiedRawValue, inner);
51!
3273
                    if (coerced !== undefined && isEditableGridCell(coerced)) {
51!
3274
                        if (process.env.NODE_ENV !== "production" && coerced.kind !== inner.kind) {
×
3275
                            // eslint-disable-next-line no-console
×
3276
                            console.warn("Coercion should not change cell kind.");
×
3277
                        }
×
3278
                        return {
×
UNCOV
3279
                            location: target,
×
UNCOV
3280
                            value: coerced,
×
UNCOV
3281
                        };
×
UNCOV
3282
                    }
×
3283
                    const r = getCellRenderer(inner);
51✔
3284
                    if (r === undefined) return undefined;
51!
3285
                    if (r.kind === GridCellKind.Custom) {
51✔
3286
                        assert(inner.kind === GridCellKind.Custom);
1✔
3287
                        const newVal = (r as unknown as CustomRenderer<CustomCell<any>>).onPaste?.(
1✔
3288
                            stringifiedRawValue,
1✔
3289
                            inner.data
1✔
3290
                        );
1✔
3291
                        if (newVal === undefined) return undefined;
1!
3292
                        return {
×
3293
                            location: target,
×
3294
                            value: {
×
UNCOV
3295
                                ...inner,
×
UNCOV
3296
                                data: newVal,
×
UNCOV
3297
                            },
×
UNCOV
3298
                        };
×
3299
                    } else {
51✔
3300
                        const newVal = r.onPaste?.(stringifiedRawValue, inner, {
50✔
3301
                            formatted,
50✔
3302
                            formattedString: typeof formatted === "string" ? formatted : formatted?.join("\n"),
50!
3303
                            rawValue,
50✔
3304
                        });
50✔
3305
                        if (newVal === undefined) return undefined;
50✔
3306
                        assert(newVal.kind === inner.kind);
36✔
3307
                        return {
36✔
3308
                            location: target,
36✔
3309
                            value: newVal,
36✔
3310
                        };
36✔
3311
                    }
36✔
3312
                }
51!
UNCOV
3313
                return undefined;
×
3314
            }
51✔
3315

6✔
3316
            const selectedColumns = gridSelection.columns;
6✔
3317
            const selectedRows = gridSelection.rows;
6✔
3318
            const focused =
6✔
3319
                scrollRef.current?.contains(document.activeElement) === true ||
6✔
3320
                canvasRef.current?.contains(document.activeElement) === true;
6✔
3321

6✔
3322
            let target: Item | undefined;
6✔
3323

6✔
3324
            if (gridSelection.current !== undefined) {
6✔
3325
                target = [gridSelection.current.range.x, gridSelection.current.range.y];
5✔
3326
            } else if (selectedColumns.length === 1) {
6!
UNCOV
3327
                target = [selectedColumns.first() ?? 0, 0];
×
3328
            } else if (selectedRows.length === 1) {
1!
UNCOV
3329
                target = [rowMarkerOffset, selectedRows.first() ?? 0];
×
UNCOV
3330
            }
×
3331

6✔
3332
            if (focused && target !== undefined) {
6✔
3333
                let data: CopyBuffer | undefined;
5✔
3334
                let text: string | undefined;
5✔
3335

5✔
3336
                const textPlain = "text/plain";
5✔
3337
                const textHtml = "text/html";
5✔
3338

5✔
3339
                if (navigator.clipboard.read !== undefined) {
5!
3340
                    const clipboardContent = await navigator.clipboard.read();
×
3341

×
3342
                    for (const item of clipboardContent) {
×
3343
                        if (item.types.includes(textHtml)) {
×
3344
                            const htmlBlob = await item.getType(textHtml);
×
3345
                            const html = await htmlBlob.text();
×
3346
                            const decoded = decodeHTML(html);
×
3347
                            if (decoded !== undefined) {
×
3348
                                data = decoded;
×
3349
                                break;
×
3350
                            }
×
3351
                        }
×
3352
                        if (item.types.includes(textPlain)) {
×
UNCOV
3353
                            // eslint-disable-next-line unicorn/no-await-expression-member
×
UNCOV
3354
                            text = await (await item.getType(textPlain)).text();
×
UNCOV
3355
                        }
×
3356
                    }
×
3357
                } else if (navigator.clipboard.readText !== undefined) {
5✔
3358
                    text = await navigator.clipboard.readText();
5✔
3359
                } else if (e !== undefined && e?.clipboardData !== null) {
5!
3360
                    if (e.clipboardData.types.includes(textHtml)) {
×
3361
                        const html = e.clipboardData.getData(textHtml);
×
3362
                        data = decodeHTML(html);
×
3363
                    }
×
3364
                    if (data === undefined && e.clipboardData.types.includes(textPlain)) {
×
3365
                        text = e.clipboardData.getData(textPlain);
×
UNCOV
3366
                    }
×
UNCOV
3367
                } else {
×
UNCOV
3368
                    return; // I didn't want to read that paste value anyway
×
UNCOV
3369
                }
×
3370

5✔
3371
                const [targetCol, targetRow] = target;
5✔
3372

5✔
3373
                const editList: EditListItem[] = [];
5✔
3374
                do {
5✔
3375
                    if (onPaste === undefined) {
5✔
3376
                        const cellData = getMangledCellContent(target);
2✔
3377
                        const rawValue = text ?? data?.map(r => r.map(cb => cb.rawValue).join("\t")).join("\t") ?? "";
2!
3378
                        const newVal = pasteToCell(cellData, target, rawValue, undefined);
2✔
3379
                        if (newVal !== undefined) {
2✔
3380
                            editList.push(newVal);
1✔
3381
                        }
1✔
3382
                        break;
2✔
3383
                    }
2✔
3384

3✔
3385
                    if (data === undefined) {
3✔
3386
                        if (text === undefined) return;
3!
3387
                        data = unquote(text);
3✔
3388
                    }
3✔
3389

3✔
3390
                    if (
3✔
3391
                        onPaste === false ||
3✔
3392
                        (typeof onPaste === "function" &&
3✔
3393
                            onPaste?.(
2✔
3394
                                [target[0] - rowMarkerOffset, target[1]],
2✔
3395
                                data.map(r => r.map(cb => cb.rawValue?.toString() ?? ""))
2!
3396
                            ) !== true)
2✔
3397
                    ) {
5!
UNCOV
3398
                        return;
×
UNCOV
3399
                    }
✔
3400

3✔
3401
                    for (const [row, dataRow] of data.entries()) {
5✔
3402
                        if (row + targetRow >= rows) break;
21!
3403
                        for (const [col, dataItem] of dataRow.entries()) {
21✔
3404
                            const index = [col + targetCol, row + targetRow] as const;
63✔
3405
                            const [writeCol, writeRow] = index;
63✔
3406
                            if (writeCol >= mangledCols.length) continue;
63✔
3407
                            if (writeRow >= mangledRows) continue;
49!
3408
                            const cellData = getMangledCellContent(index);
49✔
3409
                            const newVal = pasteToCell(cellData, index, dataItem.rawValue, dataItem.formatted);
49✔
3410
                            if (newVal !== undefined) {
63✔
3411
                                editList.push(newVal);
35✔
3412
                            }
35✔
3413
                        }
63✔
3414
                    }
21✔
3415
                    // eslint-disable-next-line no-constant-condition
3✔
3416
                } while (false);
5✔
3417

5✔
3418
                mangledOnCellsEdited(editList);
5✔
3419

5✔
3420
                gridRef.current?.damage(
5✔
3421
                    editList.map(c => ({
5✔
3422
                        cell: c.location,
36✔
3423
                    }))
5✔
3424
                );
5✔
3425
            }
5✔
3426
        },
6✔
3427
        [
678✔
3428
            coercePasteValue,
678✔
3429
            getCellRenderer,
678✔
3430
            getMangledCellContent,
678✔
3431
            gridSelection,
678✔
3432
            keybindings.paste,
678✔
3433
            mangledCols.length,
678✔
3434
            mangledOnCellsEdited,
678✔
3435
            mangledRows,
678✔
3436
            onPaste,
678✔
3437
            rowMarkerOffset,
678✔
3438
            rows,
678✔
3439
        ]
678✔
3440
    );
678✔
3441

678✔
3442
    useEventListener("paste", onPasteInternal, safeWindow, false, true);
678✔
3443

678✔
3444
    // While this function is async, we deeply prefer not to await if we don't have to. This will lead to unpacking
678✔
3445
    // promises in rather awkward ways when possible to avoid awaiting. We have to use fallback copy mechanisms when
678✔
3446
    // an await has happened.
678✔
3447
    const onCopy = React.useCallback(
678✔
3448
        async (e?: ClipboardEvent, ignoreFocus?: boolean) => {
678✔
3449
            if (!keybindings.copy) return;
6!
3450
            const focused =
6✔
3451
                ignoreFocus === true ||
6✔
3452
                scrollRef.current?.contains(document.activeElement) === true ||
5✔
3453
                canvasRef.current?.contains(document.activeElement) === true;
5✔
3454

6✔
3455
            const selectedColumns = gridSelection.columns;
6✔
3456
            const selectedRows = gridSelection.rows;
6✔
3457

6✔
3458
            const copyToClipboardWithHeaders = (
6✔
3459
                cells: readonly (readonly GridCell[])[],
5✔
3460
                columnIndexes: readonly number[]
5✔
3461
            ) => {
5✔
3462
                if (!copyHeaders) {
5✔
3463
                    copyToClipboard(cells, columnIndexes, e);
5✔
3464
                } else {
5!
3465
                    const headers = columnIndexes.map(index => ({
×
3466
                        kind: GridCellKind.Text,
×
3467
                        data: columnsIn[index].title,
×
3468
                        displayData: columnsIn[index].title,
×
UNCOV
3469
                        allowOverlay: false,
×
UNCOV
3470
                    })) as GridCell[];
×
UNCOV
3471
                    copyToClipboard([headers, ...cells], columnIndexes, e);
×
UNCOV
3472
                }
×
3473
            };
5✔
3474

6✔
3475
            if (focused && getCellsForSelection !== undefined) {
6✔
3476
                if (gridSelection.current !== undefined) {
6✔
3477
                    let thunk = getCellsForSelection(gridSelection.current.range, abortControllerRef.current.signal);
3✔
3478
                    if (typeof thunk !== "object") {
3!
UNCOV
3479
                        thunk = await thunk();
×
UNCOV
3480
                    }
×
3481
                    copyToClipboardWithHeaders(
3✔
3482
                        thunk,
3✔
3483
                        range(
3✔
3484
                            gridSelection.current.range.x - rowMarkerOffset,
3✔
3485
                            gridSelection.current.range.x + gridSelection.current.range.width - rowMarkerOffset
3✔
3486
                        )
3✔
3487
                    );
3✔
3488
                } else if (selectedRows !== undefined && selectedRows.length > 0) {
3✔
3489
                    const toCopy = [...selectedRows];
1✔
3490
                    const cells = toCopy.map(rowIndex => {
1✔
3491
                        const thunk = getCellsForSelection(
1✔
3492
                            {
1✔
3493
                                x: rowMarkerOffset,
1✔
3494
                                y: rowIndex,
1✔
3495
                                width: columnsIn.length,
1✔
3496
                                height: 1,
1✔
3497
                            },
1✔
3498
                            abortControllerRef.current.signal
1✔
3499
                        );
1✔
3500
                        if (typeof thunk === "object") {
1✔
3501
                            return thunk[0];
1✔
3502
                        }
1!
3503
                        return thunk().then(v => v[0]);
×
3504
                    });
1✔
3505
                    if (cells.some(x => x instanceof Promise)) {
1!
UNCOV
3506
                        const settled = await Promise.all(cells);
×
UNCOV
3507
                        copyToClipboardWithHeaders(settled, range(columnsIn.length));
×
3508
                    } else {
1✔
3509
                        copyToClipboardWithHeaders(cells as (readonly GridCell[])[], range(columnsIn.length));
1✔
3510
                    }
1✔
3511
                } else if (selectedColumns.length > 0) {
3✔
3512
                    const results: (readonly (readonly GridCell[])[])[] = [];
1✔
3513
                    const cols: number[] = [];
1✔
3514
                    for (const col of selectedColumns) {
1✔
3515
                        let thunk = getCellsForSelection(
3✔
3516
                            {
3✔
3517
                                x: col,
3✔
3518
                                y: 0,
3✔
3519
                                width: 1,
3✔
3520
                                height: rows,
3✔
3521
                            },
3✔
3522
                            abortControllerRef.current.signal
3✔
3523
                        );
3✔
3524
                        if (typeof thunk !== "object") {
3!
UNCOV
3525
                            thunk = await thunk();
×
UNCOV
3526
                        }
×
3527
                        results.push(thunk);
3✔
3528
                        cols.push(col - rowMarkerOffset);
3✔
3529
                    }
3✔
3530
                    if (results.length === 1) {
1!
UNCOV
3531
                        copyToClipboardWithHeaders(results[0], cols);
×
3532
                    } else {
1✔
3533
                        // FIXME: this is dumb
1✔
3534
                        const toCopy = results.reduce((pv, cv) => pv.map((row, index) => [...row, ...cv[index]]));
1✔
3535
                        copyToClipboardWithHeaders(toCopy, cols);
1✔
3536
                    }
1✔
3537
                }
1✔
3538
            }
6✔
3539
        },
6✔
3540
        [columnsIn, getCellsForSelection, gridSelection, keybindings.copy, rowMarkerOffset, rows, copyHeaders]
678✔
3541
    );
678✔
3542

678✔
3543
    useEventListener("copy", onCopy, safeWindow, false, false);
678✔
3544

678✔
3545
    const onCut = React.useCallback(
678✔
3546
        async (e?: ClipboardEvent) => {
678✔
3547
            if (!keybindings.cut) return;
1!
3548
            const focused =
1✔
3549
                scrollRef.current?.contains(document.activeElement) === true ||
1✔
3550
                canvasRef.current?.contains(document.activeElement) === true;
1✔
3551

1✔
3552
            if (!focused) return;
1!
3553
            await onCopy(e);
1✔
3554
            if (gridSelection.current !== undefined) {
1✔
3555
                let effectiveSelection: GridSelection = {
1✔
3556
                    current: {
1✔
3557
                        cell: gridSelection.current.cell,
1✔
3558
                        range: gridSelection.current.range,
1✔
3559
                        rangeStack: [],
1✔
3560
                    },
1✔
3561
                    rows: CompactSelection.empty(),
1✔
3562
                    columns: CompactSelection.empty(),
1✔
3563
                };
1✔
3564
                const onDeleteResult = onDelete?.(effectiveSelection);
1✔
3565
                if (onDeleteResult === false) return;
1!
3566
                effectiveSelection = onDeleteResult === true ? effectiveSelection : onDeleteResult;
1!
3567
                if (effectiveSelection.current === undefined) return;
1!
3568
                deleteRange(effectiveSelection.current.range);
1✔
3569
            }
1✔
3570
        },
1✔
3571
        [deleteRange, gridSelection, keybindings.cut, onCopy, onDelete]
678✔
3572
    );
678✔
3573

678✔
3574
    useEventListener("cut", onCut, safeWindow, false, false);
678✔
3575

678✔
3576
    const onSearchResultsChanged = React.useCallback(
678✔
3577
        (results: readonly Item[], navIndex: number) => {
678✔
3578
            if (onSearchResultsChangedIn !== undefined) {
7!
3579
                if (rowMarkerOffset !== 0) {
×
3580
                    results = results.map(item => [item[0] - rowMarkerOffset, item[1]]);
×
UNCOV
3581
                }
×
UNCOV
3582
                onSearchResultsChangedIn(results, navIndex);
×
UNCOV
3583
                return;
×
UNCOV
3584
            }
×
3585
            if (results.length === 0 || navIndex === -1) return;
7✔
3586

2✔
3587
            const [col, row] = results[navIndex];
2✔
3588
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
7!
UNCOV
3589
                return;
×
UNCOV
3590
            }
✔
3591
            lastSent.current = [col, row];
2✔
3592
            updateSelectedCell(col, row, false, false);
2✔
3593
        },
7✔
3594
        [onSearchResultsChangedIn, rowMarkerOffset, updateSelectedCell]
678✔
3595
    );
678✔
3596

678✔
3597
    // this effects purpose in life is to scroll the newly selected cell into view when and ONLY when that cell
678✔
3598
    // is from an external gridSelection change. Also note we want the unmangled out selection because scrollTo
678✔
3599
    // expects unmangled indexes
678✔
3600
    const [outCol, outRow] = gridSelectionOuter?.current?.cell ?? [];
678✔
3601
    const scrollToRef = React.useRef(scrollTo);
678✔
3602
    scrollToRef.current = scrollTo;
678✔
3603
    React.useLayoutEffect(() => {
678✔
3604
        if (
211✔
3605
            !hasJustScrolled.current &&
211✔
3606
            outCol !== undefined &&
211✔
3607
            outRow !== undefined &&
77✔
3608
            (outCol !== expectedExternalGridSelection.current?.current?.cell[0] ||
77✔
3609
                outRow !== expectedExternalGridSelection.current?.current?.cell[1])
77✔
3610
        ) {
211!
UNCOV
3611
            scrollToRef.current(outCol, outRow);
×
UNCOV
3612
        }
×
3613
        hasJustScrolled.current = false; //only allow skipping a single scroll
211✔
3614
    }, [outCol, outRow]);
678✔
3615

678✔
3616
    const selectionOutOfBounds =
678✔
3617
        gridSelection.current !== undefined &&
678✔
3618
        (gridSelection.current.cell[0] >= mangledCols.length || gridSelection.current.cell[1] >= mangledRows);
321✔
3619
    React.useLayoutEffect(() => {
678✔
3620
        if (selectionOutOfBounds) {
140✔
3621
            setGridSelection(emptyGridSelection, false);
1✔
3622
        }
1✔
3623
    }, [selectionOutOfBounds, setGridSelection]);
678✔
3624

678✔
3625
    const disabledRows = React.useMemo(() => {
678✔
3626
        if (showTrailingBlankRow === true && trailingRowOptions?.tint === true) {
139✔
3627
            return CompactSelection.fromSingleSelection(mangledRows - 1);
136✔
3628
        }
136✔
3629
        return CompactSelection.empty();
3✔
3630
    }, [mangledRows, showTrailingBlankRow, trailingRowOptions?.tint]);
678✔
3631

678✔
3632
    const mangledVerticalBorder = React.useCallback(
678✔
3633
        (col: number) => {
678✔
3634
            return typeof verticalBorder === "boolean"
7,578!
UNCOV
3635
                ? verticalBorder
×
3636
                : verticalBorder?.(col - rowMarkerOffset) ?? true;
7,578!
3637
        },
7,578✔
3638
        [rowMarkerOffset, verticalBorder]
678✔
3639
    );
678✔
3640

678✔
3641
    const renameGroupNode = React.useMemo(() => {
678✔
3642
        if (renameGroup === undefined || canvasRef.current === null) return null;
140✔
3643
        const { bounds, group } = renameGroup;
2✔
3644
        const canvasBounds = canvasRef.current.getBoundingClientRect();
2✔
3645
        return (
2✔
3646
            <GroupRename
2✔
3647
                bounds={bounds}
2✔
3648
                group={group}
2✔
3649
                canvasBounds={canvasBounds}
2✔
3650
                onClose={() => setRenameGroup(undefined)}
2✔
3651
                onFinish={newVal => {
2✔
3652
                    setRenameGroup(undefined);
1✔
3653
                    onGroupHeaderRenamed?.(group, newVal);
1✔
3654
                }}
1✔
3655
            />
2✔
3656
        );
140✔
3657
    }, [onGroupHeaderRenamed, renameGroup]);
678✔
3658

678✔
3659
    const mangledFreezeColumns = Math.min(mangledCols.length, freezeColumns + (hasRowMarkers ? 1 : 0));
678✔
3660

678✔
3661
    React.useImperativeHandle(
678✔
3662
        forwardedRef,
678✔
3663
        () => ({
678✔
3664
            appendRow: (col: number, openOverlay?: boolean) => appendRow(col + rowMarkerOffset, openOverlay),
27✔
3665
            updateCells: damageList => {
27✔
3666
                if (rowMarkerOffset !== 0) {
2✔
3667
                    damageList = damageList.map(x => ({ cell: [x.cell[0] + rowMarkerOffset, x.cell[1]] }));
1✔
3668
                }
1✔
3669
                return gridRef.current?.damage(damageList);
2✔
3670
            },
2✔
3671
            getBounds: (col, row) => {
27✔
3672
                if (canvasRef?.current === null || scrollRef?.current === null) {
1!
3673
                    return undefined;
×
3674
                }
×
3675

1✔
3676
                if (col === undefined && row === undefined) {
1!
3677
                    // Return the bounds of the entire scroll area:
×
3678
                    const rect = canvasRef.current.getBoundingClientRect();
×
3679
                    const scale = rect.width / scrollRef.current.clientWidth;
×
3680
                    return {
×
3681
                        x: rect.x - scrollRef.current.scrollLeft * scale,
×
3682
                        y: rect.y - scrollRef.current.scrollTop * scale,
×
UNCOV
3683
                        width: scrollRef.current.scrollWidth * scale,
×
UNCOV
3684
                        height: scrollRef.current.scrollHeight * scale,
×
UNCOV
3685
                    };
×
UNCOV
3686
                }
×
3687
                return gridRef.current?.getBounds((col ?? 0) + rowMarkerOffset, row);
1!
3688
            },
1✔
3689
            focus: () => gridRef.current?.focus(),
27✔
3690
            emit: async e => {
27✔
3691
                switch (e) {
5✔
3692
                    case "delete":
5✔
3693
                        onKeyDown({
1✔
3694
                            bounds: undefined,
1✔
3695
                            cancel: () => undefined,
1✔
3696
                            stopPropagation: () => undefined,
1✔
3697
                            preventDefault: () => undefined,
1✔
3698
                            ctrlKey: false,
1✔
3699
                            key: "Delete",
1✔
3700
                            keyCode: 46,
1✔
3701
                            metaKey: false,
1✔
3702
                            shiftKey: false,
1✔
3703
                            altKey: false,
1✔
3704
                            rawEvent: undefined,
1✔
3705
                            location: undefined,
1✔
3706
                        });
1✔
3707
                        break;
1✔
3708
                    case "fill-right":
5✔
3709
                        onKeyDown({
1✔
3710
                            bounds: undefined,
1✔
3711
                            cancel: () => undefined,
1✔
3712
                            stopPropagation: () => undefined,
1✔
3713
                            preventDefault: () => undefined,
1✔
3714
                            ctrlKey: true,
1✔
3715
                            key: "r",
1✔
3716
                            keyCode: 82,
1✔
3717
                            metaKey: false,
1✔
3718
                            shiftKey: false,
1✔
3719
                            altKey: false,
1✔
3720
                            rawEvent: undefined,
1✔
3721
                            location: undefined,
1✔
3722
                        });
1✔
3723
                        break;
1✔
3724
                    case "fill-down":
5✔
3725
                        onKeyDown({
1✔
3726
                            bounds: undefined,
1✔
3727
                            cancel: () => undefined,
1✔
3728
                            stopPropagation: () => undefined,
1✔
3729
                            preventDefault: () => undefined,
1✔
3730
                            ctrlKey: true,
1✔
3731
                            key: "d",
1✔
3732
                            keyCode: 68,
1✔
3733
                            metaKey: false,
1✔
3734
                            shiftKey: false,
1✔
3735
                            altKey: false,
1✔
3736
                            rawEvent: undefined,
1✔
3737
                            location: undefined,
1✔
3738
                        });
1✔
3739
                        break;
1✔
3740
                    case "copy":
5✔
3741
                        await onCopy(undefined, true);
1✔
3742
                        break;
1✔
3743
                    case "paste":
5✔
3744
                        await onPasteInternal();
1✔
3745
                        break;
1✔
3746
                }
5✔
3747
            },
5✔
3748
            scrollTo,
27✔
3749
            remeasureColumns: cols => {
27✔
3750
                for (const col of cols) {
1✔
3751
                    void normalSizeColumn(col + rowMarkerOffset, true);
1✔
3752
                }
1✔
3753
            },
1✔
3754
        }),
27✔
3755
        [appendRow, normalSizeColumn, onCopy, onKeyDown, onPasteInternal, rowMarkerOffset, scrollTo]
678✔
3756
    );
678✔
3757

678✔
3758
    const [selCol, selRow] = currentCell ?? [];
678✔
3759
    const onCellFocused = React.useCallback(
678✔
3760
        (cell: Item) => {
678✔
3761
            const [col, row] = cell;
28✔
3762

28✔
3763
            if (row === -1) {
28!
3764
                if (columnSelect !== "none") {
×
3765
                    setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, false);
×
UNCOV
3766
                    focus();
×
UNCOV
3767
                }
×
UNCOV
3768
                return;
×
UNCOV
3769
            }
×
3770

28✔
3771
            if (selCol === col && selRow === row) return;
28✔
3772
            setCurrent(
1✔
3773
                {
1✔
3774
                    cell,
1✔
3775
                    range: { x: col, y: row, width: 1, height: 1 },
1✔
3776
                },
1✔
3777
                true,
1✔
3778
                false,
1✔
3779
                "keyboard-nav"
1✔
3780
            );
1✔
3781
            scrollTo(col, row);
1✔
3782
        },
28✔
3783
        [columnSelect, focus, scrollTo, selCol, selRow, setCurrent, setSelectedColumns]
678✔
3784
    );
678✔
3785

678✔
3786
    const [isFocused, setIsFocused] = React.useState(false);
678✔
3787
    const setIsFocusedDebounced = React.useRef(
678✔
3788
        debounce((val: boolean) => {
678✔
3789
            setIsFocused(val);
56✔
3790
        }, 5)
678✔
3791
    );
678✔
3792

678✔
3793
    const onCanvasFocused = React.useCallback(() => {
678✔
3794
        setIsFocusedDebounced.current(true);
66✔
3795

66✔
3796
        // check for mouse state, don't do anything if the user is clicked to focus.
66✔
3797
        if (
66✔
3798
            gridSelection.current === undefined &&
66✔
3799
            gridSelection.columns.length === 0 &&
6✔
3800
            gridSelection.rows.length === 0 &&
5✔
3801
            mouseState === undefined
5✔
3802
        ) {
66✔
3803
            setCurrent(
5✔
3804
                {
5✔
3805
                    cell: [rowMarkerOffset, cellYOffset],
5✔
3806
                    range: {
5✔
3807
                        x: rowMarkerOffset,
5✔
3808
                        y: cellYOffset,
5✔
3809
                        width: 1,
5✔
3810
                        height: 1,
5✔
3811
                    },
5✔
3812
                },
5✔
3813
                true,
5✔
3814
                false,
5✔
3815
                "keyboard-select"
5✔
3816
            );
5✔
3817
        }
5✔
3818
    }, [cellYOffset, gridSelection, mouseState, rowMarkerOffset, setCurrent]);
678✔
3819

678✔
3820
    const onFocusOut = React.useCallback(() => {
678✔
3821
        setIsFocusedDebounced.current(false);
32✔
3822
    }, []);
678✔
3823

678✔
3824
    const [idealWidth, idealHeight] = React.useMemo(() => {
678✔
3825
        let h: number;
152✔
3826
        const scrollbarWidth = experimental?.scrollbarWidthOverride ?? getScrollBarWidth();
152✔
3827
        const rowsCountWithTrailingRow = rows + (showTrailingBlankRow ? 1 : 0);
152!
3828
        if (typeof rowHeight === "number") {
152✔
3829
            h = totalHeaderHeight + rowsCountWithTrailingRow * rowHeight;
151✔
3830
        } else {
152✔
3831
            let avg = 0;
1✔
3832
            const toAverage = Math.min(rowsCountWithTrailingRow, 10);
1✔
3833
            for (let i = 0; i < toAverage; i++) {
1✔
3834
                avg += rowHeight(i);
10✔
3835
            }
10✔
3836
            avg = Math.floor(avg / toAverage);
1✔
3837

1✔
3838
            h = totalHeaderHeight + rowsCountWithTrailingRow * avg;
1✔
3839
        }
1✔
3840
        h += scrollbarWidth;
152✔
3841

152✔
3842
        const w = mangledCols.reduce((acc, x) => x.width + acc, 0) + scrollbarWidth;
152✔
3843

152✔
3844
        // We need to set a reasonable cap here as some browsers will just ignore huge values
152✔
3845
        // rather than treat them as huge values.
152✔
3846
        return [`${Math.min(100_000, w)}px`, `${Math.min(100_000, h)}px`];
152✔
3847
    }, [mangledCols, experimental?.scrollbarWidthOverride, rowHeight, rows, showTrailingBlankRow, totalHeaderHeight]);
678✔
3848

678✔
3849
    return (
678✔
3850
        <ThemeContext.Provider value={mergedTheme}>
678✔
3851
            <DataEditorContainer
678✔
3852
                style={makeCSSStyle(mergedTheme)}
678✔
3853
                className={className}
678✔
3854
                inWidth={width ?? idealWidth}
678✔
3855
                inHeight={height ?? idealHeight}>
678✔
3856
                <DataGridSearch
678✔
3857
                    fillHandle={fillHandle}
678✔
3858
                    drawFocusRing={drawFocusRing}
678✔
3859
                    experimental={experimental}
678✔
3860
                    fixedShadowX={fixedShadowX}
678✔
3861
                    fixedShadowY={fixedShadowY}
678✔
3862
                    getRowThemeOverride={getRowThemeOverride}
678✔
3863
                    headerIcons={headerIcons}
678✔
3864
                    imageWindowLoader={imageWindowLoader}
678✔
3865
                    initialSize={initialSize}
678✔
3866
                    isDraggable={isDraggable}
678✔
3867
                    onDragLeave={onDragLeave}
678✔
3868
                    onRowMoved={onRowMoved}
678✔
3869
                    overscrollX={overscrollX}
678✔
3870
                    overscrollY={overscrollY}
678✔
3871
                    preventDiagonalScrolling={preventDiagonalScrolling}
678✔
3872
                    rightElement={rightElement}
678✔
3873
                    rightElementProps={rightElementProps}
678✔
3874
                    smoothScrollX={smoothScrollX}
678✔
3875
                    smoothScrollY={smoothScrollY}
678✔
3876
                    className={className}
678✔
3877
                    enableGroups={enableGroups}
678✔
3878
                    onCanvasFocused={onCanvasFocused}
678✔
3879
                    onCanvasBlur={onFocusOut}
678✔
3880
                    canvasRef={canvasRef}
678✔
3881
                    onContextMenu={onContextMenu}
678✔
3882
                    theme={mergedTheme}
678✔
3883
                    cellXOffset={cellXOffset}
678✔
3884
                    cellYOffset={cellYOffset}
678✔
3885
                    accessibilityHeight={visibleRegion.height}
678✔
3886
                    onDragEnd={onDragEnd}
678✔
3887
                    columns={mangledCols}
678✔
3888
                    nonGrowWidth={nonGrowWidth}
678✔
3889
                    drawHeader={drawHeader}
678✔
3890
                    onColumnProposeMove={onColumnProposeMove}
678✔
3891
                    drawCell={drawCell}
678✔
3892
                    disabledRows={disabledRows}
678✔
3893
                    freezeColumns={mangledFreezeColumns}
678✔
3894
                    lockColumns={rowMarkerOffset}
678✔
3895
                    firstColAccessible={rowMarkerOffset === 0}
678✔
3896
                    getCellContent={getMangledCellContent}
678✔
3897
                    minColumnWidth={minColumnWidth}
678✔
3898
                    maxColumnWidth={maxColumnWidth}
678✔
3899
                    searchInputRef={searchInputRef}
678✔
3900
                    showSearch={showSearch}
678✔
3901
                    onSearchClose={onSearchClose}
678✔
3902
                    highlightRegions={highlightRegions}
678✔
3903
                    getCellsForSelection={getCellsForSelection}
678✔
3904
                    getGroupDetails={mangledGetGroupDetails}
678✔
3905
                    headerHeight={headerHeight}
678✔
3906
                    isFocused={isFocused}
678✔
3907
                    groupHeaderHeight={enableGroups ? groupHeaderHeight : 0}
678✔
3908
                    trailingRowType={
678✔
3909
                        !showTrailingBlankRow ? "none" : trailingRowOptions?.sticky === true ? "sticky" : "appended"
678!
3910
                    }
678✔
3911
                    onColumnResize={onColumnResize}
678✔
3912
                    onColumnResizeEnd={onColumnResizeEnd}
678✔
3913
                    onColumnResizeStart={onColumnResizeStart}
678✔
3914
                    onCellFocused={onCellFocused}
678✔
3915
                    onColumnMoved={onColumnMovedImpl}
678✔
3916
                    onDragStart={onDragStartImpl}
678✔
3917
                    onHeaderMenuClick={onHeaderMenuClickInner}
678✔
3918
                    onItemHovered={onItemHoveredImpl}
678✔
3919
                    isFilling={mouseState?.fillHandle === true}
678✔
3920
                    onMouseMove={onMouseMoveImpl}
678✔
3921
                    onKeyDown={onKeyDown}
678✔
3922
                    onKeyUp={onKeyUpIn}
678✔
3923
                    onMouseDown={onMouseDown}
678✔
3924
                    onMouseUp={onMouseUp}
678✔
3925
                    onDragOverCell={onDragOverCell}
678✔
3926
                    onDrop={onDrop}
678✔
3927
                    onSearchResultsChanged={onSearchResultsChanged}
678✔
3928
                    onVisibleRegionChanged={onVisibleRegionChangedImpl}
678✔
3929
                    clientSize={clientSize}
678✔
3930
                    rowHeight={rowHeight}
678✔
3931
                    searchResults={searchResults}
678✔
3932
                    searchValue={searchValue}
678✔
3933
                    onSearchValueChange={onSearchValueChange}
678✔
3934
                    rows={mangledRows}
678✔
3935
                    scrollRef={scrollRef}
678✔
3936
                    selection={gridSelection}
678✔
3937
                    translateX={visibleRegion.tx}
678✔
3938
                    translateY={visibleRegion.ty}
678✔
3939
                    verticalBorder={mangledVerticalBorder}
678✔
3940
                    gridRef={gridRef}
678✔
3941
                    getCellRenderer={getCellRenderer}
678✔
3942
                />
678✔
3943
                {renameGroupNode}
678✔
3944
                {overlay !== undefined && (
678✔
3945
                    <React.Suspense fallback={null}>
30✔
3946
                        <DataGridOverlayEditor
30✔
3947
                            {...overlay}
30✔
3948
                            validateCell={validateCell}
30✔
3949
                            id={overlayID}
30✔
3950
                            getCellRenderer={getCellRenderer}
30✔
3951
                            className={experimental?.isSubGrid === true ? "click-outside-ignore" : undefined}
30!
3952
                            provideEditor={provideEditor}
30✔
3953
                            imageEditorOverride={imageEditorOverride}
30✔
3954
                            onFinishEditing={onFinishEditing}
30✔
3955
                            markdownDivCreateNode={markdownDivCreateNode}
30✔
3956
                            isOutsideClick={isOutsideClick}
30✔
3957
                        />
30✔
3958
                    </React.Suspense>
30✔
3959
                )}
678✔
3960
            </DataEditorContainer>
678✔
3961
        </ThemeContext.Provider>
678✔
3962
    );
678✔
3963
};
678✔
3964

1✔
3965
/**
1✔
3966
 * The primary component of Glide Data Grid.
1✔
3967
 * @category DataEditor
1✔
3968
 * @param {DataEditorProps} props
1✔
3969
 */
1✔
3970
export const DataEditor = React.forwardRef(DataEditorImpl);
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc