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

glideapps / glide-data-grid / 7204133551

14 Dec 2023 03:31AM UTC coverage: 90.673% (+4.3%) from 86.42%
7204133551

Pull #810

github

jassmith
5.99.9-beta4
Pull Request #810: 6.0.0

2552 of 3183 branches covered (0.0%)

2915 of 3325 new or added lines in 61 files covered. (87.67%)

268 existing lines in 12 files now uncovered.

15544 of 17143 relevant lines covered (90.67%)

3109.36 hits per line

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

89.51
/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 GridDragEventArgs,
1✔
14
    type GridKeyEventArgs,
1✔
15
    type GridMouseEventArgs,
1✔
16
    type GridSelection,
1✔
17
    isEditableGridCell,
1✔
18
    type Rectangle,
1✔
19
    isReadWriteCell,
1✔
20
    type InnerGridCell,
1✔
21
    InnerGridCellKind,
1✔
22
    CompactSelection,
1✔
23
    type Slice,
1✔
24
    isInnerOnlyCell,
1✔
25
    type ProvideEditorCallback,
1✔
26
    type GridMouseCellEventArgs,
1✔
27
    type GridColumn,
1✔
28
    isObjectEditorCallbackResult,
1✔
29
    type GroupHeaderClickedEventArgs,
1✔
30
    type HeaderClickedEventArgs,
1✔
31
    type CellClickedEventArgs,
1✔
32
    type Item,
1✔
33
    type MarkerCell,
1✔
34
    headerCellUnheckedMarker,
1✔
35
    headerCellCheckedMarker,
1✔
36
    headerCellIndeterminateMarker,
1✔
37
    groupHeaderKind,
1✔
38
    outOfBoundsKind,
1✔
39
    type ValidatedGridCell,
1✔
40
    type ImageEditorType,
1✔
41
    type CustomCell,
1✔
42
    headerKind,
1✔
43
    BooleanEmpty,
1✔
44
    BooleanIndeterminate,
1✔
45
    type FillPatternEventArgs,
1✔
46
} from "../internal/data-grid/data-grid-types.js";
1✔
47
import DataGridSearch, { type DataGridSearchProps } from "../internal/data-grid-search/data-grid-search.js";
1✔
48
import { browserIsOSX } from "../common/browser-detect.js";
1✔
49
import {
1✔
50
    getDataEditorTheme,
1✔
51
    makeCSSStyle,
1✔
52
    type FullTheme,
1✔
53
    type Theme,
1✔
54
    ThemeContext,
1✔
55
    mergeAndRealizeTheme,
1✔
56
} from "../common/styles.js";
1✔
57
import type { DataGridRef } from "../internal/data-grid/data-grid.js";
1✔
58
import { getScrollBarWidth, useEventListener, useStateWithReactiveInput, whenDefined } from "../common/utils.js";
1✔
59
import {
1✔
60
    isGroupEqual,
1✔
61
    itemsAreEqual,
1✔
62
    itemIsInRect,
1✔
63
    gridSelectionHasItem,
1✔
64
} from "../internal/data-grid/data-grid-lib.js";
1✔
65
import { GroupRename } from "./group-rename.js";
1✔
66
import { measureColumn, useColumnSizer } from "./use-column-sizer.js";
1✔
67
import { isHotkey } from "../common/is-hotkey.js";
1✔
68
import { type SelectionBlending, useSelectionBehavior } from "../internal/data-grid/use-selection-behavior.js";
1✔
69
import { useCellsForSelection } from "./use-cells-for-selection.js";
1✔
70
import { unquote, expandSelection, copyToClipboard, toggleBoolean } from "./data-editor-fns.js";
1✔
71
import { DataEditorContainer } from "../internal/data-editor-container/data-grid-container.js";
1✔
72
import { useAutoscroll } from "./use-autoscroll.js";
1✔
73
import type { CustomRenderer, CellRenderer, InternalCellRenderer } from "../cells/cell-types.js";
1✔
74
import { decodeHTML, type CopyBuffer } from "./copy-paste.js";
1✔
75
import { useRemAdjuster } from "./use-rem-adjuster.js";
1✔
76
import { type Highlight } from "../internal/data-grid/data-grid-render.js";
1✔
77
import { withAlpha } from "../internal/data-grid/color-parser.js";
1✔
78
import { combineRects, getClosestRect } from "../common/math.js";
1✔
79

1✔
80
const DataGridOverlayEditor = React.lazy(
1✔
81
    async () => await import("../internal/data-grid-overlay-editor/data-grid-overlay-editor.js")
1✔
82
);
1✔
83

1✔
84
let idCounter = 0;
1✔
85

1✔
86
interface MouseState {
1✔
87
    readonly previousSelection?: GridSelection;
1✔
88
    readonly fillHandle?: boolean;
1✔
89
}
1✔
90

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

1✔
141
type EditListItem = { location: Item; value: EditableGridCell };
1✔
142

1✔
143
type EmitEvents = "copy" | "paste" | "delete" | "fill-right" | "fill-down";
1✔
144

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

1✔
155
function shiftSelection(input: GridSelection, offset: number): GridSelection {
283✔
156
    if (input === undefined || offset === 0 || (input.columns.length === 0 && input.current === undefined))
283✔
157
        return input;
283✔
158

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

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

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

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

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

1✔
290
    /** The columns to display in the data grid.
1✔
291
     * @group Data
1✔
292
     */
1✔
293
    readonly columns: readonly GridColumn[];
1✔
294

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

1✔
321
    /**
1✔
322
     * The number of rows in the grid.
1✔
323
     * @group Data
1✔
324
     */
1✔
325
    readonly rows: number;
1✔
326

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

1✔
350
    /** Changes the theme of the row marker column
1✔
351
     * @group Style
1✔
352
     */
1✔
353
    readonly rowMarkerTheme?: Partial<Theme>;
1✔
354

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

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

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

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

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

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

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

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

1✔
477
    /**
1✔
478
     * Emitted when the grid selection is cleared.
1✔
479
     * @group Selection
1✔
480
     */
1✔
481
    readonly onSelectionCleared?: () => void;
1✔
482

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

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

1✔
537
    /**
1✔
538
     * Add table headers to copied data.
1✔
539
     * @group Editing
1✔
540
     * @defaultValue `false`
1✔
541
     */
1✔
542
    readonly copyHeaders?: boolean;
1✔
543

1✔
544
    /**
1✔
545
     * Determins which keybindings are enabled.
1✔
546
     * @group Editing
1✔
547
     * @defaultValue is
1✔
548

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

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

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

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

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

1✔
618
    /**
1✔
619
     * The theme used by the data grid to get all color and font information
1✔
620
     * @group Style
1✔
621
     */
1✔
622
    readonly theme?: Partial<Theme>;
1✔
623

1✔
624
    readonly renderers?: readonly InternalCellRenderer<InnerGridCell>[];
1✔
625

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

1✔
632
    readonly scaleToRem?: boolean;
1✔
633

1✔
634
    /**
1✔
635
     * Custom predicate function to decide whether the click event occurred outside the grid
1✔
636
     * Especially used when custom editor is opened with the portal and is outside the grid, but there is no possibility
1✔
637
     * to add a class "click-outside-ignore"
1✔
638
     * If this function is supplied and returns false, the click event is ignored
1✔
639
     */
1✔
640
    readonly isOutsideClick?: (e: MouseEvent | TouchEvent) => boolean;
1✔
641
}
1✔
642

1✔
643
type ScrollToFn = (
1✔
644
    col: number | { amount: number; unit: "cell" | "px" },
1✔
645
    row: number | { amount: number; unit: "cell" | "px" },
1✔
646
    dir?: "horizontal" | "vertical" | "both",
1✔
647
    paddingX?: number,
1✔
648
    paddingY?: number,
1✔
649
    options?: {
1✔
650
        hAlign?: "start" | "center" | "end";
1✔
651
        vAlign?: "start" | "center" | "end";
1✔
652
    }
1✔
653
) => void;
1✔
654

1✔
655
/** @category DataEditor */
1✔
656
export interface DataEditorRef {
1✔
657
    /**
1✔
658
     * Programatically appends a row.
1✔
659
     * @param col The column index to focus in the new row.
1✔
660
     * @returns A promise which waits for the append to complete.
1✔
661
     */
1✔
662
    appendRow: (col: number, openOverlay?: boolean) => Promise<void>;
1✔
663
    /**
1✔
664
     * Triggers cells to redraw.
1✔
665
     */
1✔
666
    updateCells: DataGridRef["damage"];
1✔
667
    /**
1✔
668
     * Gets the screen space bounds of the requested item.
1✔
669
     */
1✔
670
    getBounds: DataGridRef["getBounds"];
1✔
671
    /**
1✔
672
     * Triggers the data grid to focus itself or the correct accessibility element.
1✔
673
     */
1✔
674
    focus: DataGridRef["focus"];
1✔
675
    /**
1✔
676
     * Generic API for emitting events as if they had been triggered via user interaction.
1✔
677
     */
1✔
678
    emit: (eventName: EmitEvents) => Promise<void>;
1✔
679
    /**
1✔
680
     * Scrolls to the desired cell or location in the grid.
1✔
681
     */
1✔
682
    scrollTo: ScrollToFn;
1✔
683
    /**
1✔
684
     * Causes the columns in the selection to have their natural size recomputed and re-emitted as a resize event.
1✔
685
     */
1✔
686
    remeasureColumns: (cols: CompactSelection) => void;
1✔
687
}
1✔
688

1✔
689
const loadingCell: GridCell = {
1✔
690
    kind: GridCellKind.Loading,
1✔
691
    allowOverlay: false,
1✔
692
};
1✔
693

1✔
694
const emptyGridSelection: GridSelection = {
1✔
695
    columns: CompactSelection.empty(),
1✔
696
    rows: CompactSelection.empty(),
1✔
697
    current: undefined,
1✔
698
};
1✔
699

1✔
700
const DataEditorImpl: React.ForwardRefRenderFunction<DataEditorRef, DataEditorProps> = (p, forwardedRef) => {
1✔
701
    const [gridSelectionInner, setGridSelectionInner] = React.useState<GridSelection>(emptyGridSelection);
650✔
702
    const [overlay, setOverlay] = React.useState<{
650✔
703
        target: Rectangle;
650✔
704
        content: GridCell;
650✔
705
        theme: FullTheme;
650✔
706
        initialValue: string | undefined;
650✔
707
        cell: Item;
650✔
708
        highlight: boolean;
650✔
709
        forceEditMode: boolean;
650✔
710
    }>();
650✔
711
    const searchInputRef = React.useRef<HTMLInputElement | null>(null);
650✔
712
    const canvasRef = React.useRef<HTMLCanvasElement | null>(null);
650✔
713
    const [mouseState, setMouseState] = React.useState<MouseState>();
650✔
714
    const scrollRef = React.useRef<HTMLDivElement | null>(null);
650✔
715
    const lastSent = React.useRef<[number, number]>();
650✔
716

650✔
717
    const safeWindow = typeof window === "undefined" ? null : window;
650!
718

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

650✔
824
    const minColumnWidth = Math.max(minColumnWidthIn, 20);
650✔
825
    const maxColumnWidth = Math.max(maxColumnWidthIn, minColumnWidth);
650✔
826
    const maxColumnAutoWidth = Math.max(maxColumnAutoWidthIn ?? maxColumnWidth, minColumnWidth);
650✔
827

650✔
828
    const docStyle = React.useMemo(() => {
650✔
829
        if (typeof window === "undefined") return { fontSize: "16px" };
132!
830
        return window.getComputedStyle(document.documentElement);
132✔
831
    }, []);
650✔
832

650✔
833
    const fontSizeStr = docStyle.fontSize;
650✔
834

650✔
835
    const remSize = React.useMemo(() => Number.parseFloat(fontSizeStr), [fontSizeStr]);
650✔
836

650✔
837
    const { rowHeight, headerHeight, groupHeaderHeight, theme, overscrollX, overscrollY } = useRemAdjuster({
650✔
838
        groupHeaderHeight: groupHeaderHeightIn,
650✔
839
        headerHeight: headerHeightIn,
650✔
840
        overscrollX: overscrollXIn,
650✔
841
        overscrollY: overscrollYIn,
650✔
842
        remSize,
650✔
843
        rowHeight: rowHeightIn,
650✔
844
        scaleToRem,
650✔
845
        theme: themeIn,
650✔
846
    });
650✔
847

650✔
848
    const keybindings = React.useMemo(() => {
650✔
849
        return keybindingsIn === undefined
132✔
850
            ? keybindingDefaults
129✔
851
            : {
3✔
852
                  ...keybindingDefaults,
3✔
853
                  ...keybindingsIn,
3✔
854
              };
3✔
855
    }, [keybindingsIn]);
650✔
856

650✔
857
    const rowMarkerWidth = rowMarkerWidthRaw ?? (rows > 10_000 ? 48 : rows > 1000 ? 44 : rows > 100 ? 36 : 32);
650!
858
    const hasRowMarkers = rowMarkers !== "none";
650✔
859
    const rowMarkerOffset = hasRowMarkers ? 1 : 0;
650✔
860
    const showTrailingBlankRow = onRowAppended !== undefined;
650✔
861
    const lastRowSticky = trailingRowOptions?.sticky === true;
650✔
862

650✔
863
    const [showSearchInner, setShowSearchInner] = React.useState(false);
650✔
864
    const showSearch = showSearchIn ?? showSearchInner;
650✔
865

650✔
866
    const onSearchClose = React.useCallback(() => {
650✔
867
        if (onSearchCloseIn !== undefined) {
2✔
868
            onSearchCloseIn();
2✔
869
        } else {
2!
870
            setShowSearchInner(false);
×
UNCOV
871
        }
×
872
    }, [onSearchCloseIn]);
650✔
873

650✔
874
    const gridSelectionOuterMangled: GridSelection | undefined = React.useMemo((): GridSelection | undefined => {
650✔
875
        return gridSelectionOuter === undefined ? undefined : shiftSelection(gridSelectionOuter, rowMarkerOffset);
257✔
876
    }, [gridSelectionOuter, rowMarkerOffset]);
650✔
877
    const gridSelection = gridSelectionOuterMangled ?? gridSelectionInner;
650✔
878

650✔
879
    const abortControllerRef = React.useRef(new AbortController());
650✔
880
    React.useEffect(() => {
650✔
881
        return () => {
132✔
882
            // eslint-disable-next-line react-hooks/exhaustive-deps
132✔
883
            abortControllerRef?.current.abort();
132✔
884
        };
132✔
885
    }, []);
650✔
886

650✔
887
    const [getCellsForSelection, getCellsForSeletionDirect] = useCellsForSelection(
650✔
888
        getCellsForSelectionIn,
650✔
889
        getCellContent,
650✔
890
        rowMarkerOffset,
650✔
891
        abortControllerRef.current,
650✔
892
        rows
650✔
893
    );
650✔
894

650✔
895
    const validateCell = React.useCallback<NonNullable<typeof validateCellIn>>(
650✔
896
        (cell, newValue, prevValue) => {
650✔
897
            if (validateCellIn === undefined) return true;
12✔
898
            const item: Item = [cell[0] - rowMarkerOffset, cell[1]];
1✔
899
            return validateCellIn?.(item, newValue, prevValue);
1✔
900
        },
12✔
901
        [rowMarkerOffset, validateCellIn]
650✔
902
    );
650✔
903

650✔
904
    const expectedExternalGridSelection = React.useRef<GridSelection | undefined>(gridSelectionOuter);
650✔
905
    const setGridSelection = React.useCallback(
650✔
906
        (newVal: GridSelection, expand: boolean): void => {
650✔
907
            if (expand) {
168✔
908
                newVal = expandSelection(
126✔
909
                    newVal,
126✔
910
                    getCellsForSelection,
126✔
911
                    rowMarkerOffset,
126✔
912
                    spanRangeBehavior,
126✔
913
                    abortControllerRef.current
126✔
914
                );
126✔
915
            }
126✔
916
            if (onGridSelectionChange !== undefined) {
168✔
917
                expectedExternalGridSelection.current = shiftSelection(newVal, -rowMarkerOffset);
129✔
918
                onGridSelectionChange(expectedExternalGridSelection.current);
129✔
919
            } else {
168✔
920
                setGridSelectionInner(newVal);
39✔
921
            }
39✔
922
        },
168✔
923
        [onGridSelectionChange, getCellsForSelection, rowMarkerOffset, spanRangeBehavior]
650✔
924
    );
650✔
925

650✔
926
    const onColumnResize = whenDefined(
650✔
927
        onColumnResizeIn,
650✔
928
        React.useCallback<NonNullable<typeof onColumnResizeIn>>(
650✔
929
            (_, w, ind, wg) => {
650✔
930
                onColumnResizeIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
11✔
931
            },
11✔
932
            [onColumnResizeIn, rowMarkerOffset, columnsIn]
650✔
933
        )
650✔
934
    );
650✔
935

650✔
936
    const onColumnResizeEnd = whenDefined(
650✔
937
        onColumnResizeEndIn,
650✔
938
        React.useCallback<NonNullable<typeof onColumnResizeEndIn>>(
650✔
939
            (_, w, ind, wg) => {
650✔
940
                onColumnResizeEndIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
2✔
941
            },
2✔
942
            [onColumnResizeEndIn, rowMarkerOffset, columnsIn]
650✔
943
        )
650✔
944
    );
650✔
945

650✔
946
    const onColumnResizeStart = whenDefined(
650✔
947
        onColumnResizeStartIn,
650✔
948
        React.useCallback<NonNullable<typeof onColumnResizeStartIn>>(
650✔
949
            (_, w, ind, wg) => {
650✔
950
                onColumnResizeStartIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
×
UNCOV
951
            },
×
952
            [onColumnResizeStartIn, rowMarkerOffset, columnsIn]
650✔
953
        )
650✔
954
    );
650✔
955

650✔
956
    const drawHeader = whenDefined(
650✔
957
        drawHeaderIn,
650✔
958
        React.useCallback<NonNullable<typeof drawHeaderIn>>(
650✔
959
            (args, draw) => {
650✔
NEW
960
                return drawHeaderIn?.({ ...args, columnIndex: args.columnIndex - rowMarkerOffset }, draw) ?? false;
×
UNCOV
961
            },
×
962
            [drawHeaderIn, rowMarkerOffset]
650✔
963
        )
650✔
964
    );
650✔
965

650✔
966
    const drawCell = whenDefined(
650✔
967
        drawCellIn,
650✔
968
        React.useCallback<NonNullable<typeof drawCellIn>>(
650✔
969
            (args, draw) => {
650✔
NEW
970
                return drawCellIn?.({ ...args, col: args.col - rowMarkerOffset }, draw) ?? false;
×
NEW
971
            },
×
972
            [drawCellIn, rowMarkerOffset]
650✔
973
        )
650✔
974
    );
650✔
975

650✔
976
    const onDelete = React.useCallback<NonNullable<DataEditorProps["onDelete"]>>(
650✔
977
        sel => {
650✔
978
            if (onDeleteIn !== undefined) {
9✔
979
                const result = onDeleteIn(shiftSelection(sel, -rowMarkerOffset));
5✔
980
                if (typeof result === "boolean") {
5!
981
                    return result;
×
UNCOV
982
                }
×
983
                return shiftSelection(result, rowMarkerOffset);
5✔
984
            }
5✔
985
            return true;
4✔
986
        },
9✔
987
        [onDeleteIn, rowMarkerOffset]
650✔
988
    );
650✔
989

650✔
990
    const [setCurrent, setSelectedRows, setSelectedColumns] = useSelectionBehavior(
650✔
991
        gridSelection,
650✔
992
        setGridSelection,
650✔
993
        rangeSelectionBlending,
650✔
994
        columnSelectionBlending,
650✔
995
        rowSelectionBlending,
650✔
996
        rangeSelect
650✔
997
    );
650✔
998

650✔
999
    const mergedTheme = React.useMemo(() => {
650✔
1000
        return mergeAndRealizeTheme(getDataEditorTheme(), theme);
132✔
1001
    }, [theme]);
650✔
1002

650✔
1003
    const [clientSize, setClientSize] = React.useState<readonly [number, number, number]>([10, 10, 0]);
650✔
1004

650✔
1005
    const rendererMap = React.useMemo(() => {
650✔
1006
        if (renderers === undefined) return {};
132!
1007
        const result: Partial<Record<InnerGridCellKind | GridCellKind, InternalCellRenderer<InnerGridCell>>> = {};
132✔
1008
        for (const r of renderers) {
132✔
1009
            result[r.kind] = r;
1,716✔
1010
        }
1,716✔
1011
        return result;
132✔
1012
    }, [renderers]);
650✔
1013

650✔
1014
    const getCellRenderer: <T extends InnerGridCell>(cell: T) => CellRenderer<T> | undefined = React.useCallback(
650✔
1015
        <T extends InnerGridCell>(cell: T) => {
650✔
1016
            if (cell.kind !== GridCellKind.Custom) {
136,449✔
1017
                return rendererMap[cell.kind] as unknown as CellRenderer<T>;
132,719✔
1018
            }
132,719✔
1019
            return additionalRenderers?.find(x => x.isMatch(cell)) as CellRenderer<T>;
136,449✔
1020
        },
136,449✔
1021
        [additionalRenderers, rendererMap]
650✔
1022
    );
650✔
1023

650✔
1024
    const columns = useColumnSizer(
650✔
1025
        columnsIn,
650✔
1026
        rows,
650✔
1027
        getCellsForSeletionDirect,
650✔
1028
        clientSize[0] - (rowMarkerOffset === 0 ? 0 : rowMarkerWidth) - clientSize[2],
650✔
1029
        minColumnWidth,
650✔
1030
        maxColumnAutoWidth,
650✔
1031
        mergedTheme,
650✔
1032
        getCellRenderer,
650✔
1033
        abortControllerRef.current
650✔
1034
    );
650✔
1035

650✔
1036
    const enableGroups = React.useMemo(() => {
650✔
1037
        return columns.some(c => c.group !== undefined);
132✔
1038
    }, [columns]);
650✔
1039

650✔
1040
    const totalHeaderHeight = enableGroups ? headerHeight + groupHeaderHeight : headerHeight;
650✔
1041

650✔
1042
    const numSelectedRows = gridSelection.rows.length;
650✔
1043
    const rowMarkerHeader =
650✔
1044
        rowMarkers === "none"
650✔
1045
            ? ""
521✔
1046
            : numSelectedRows === 0
128✔
1047
            ? headerCellUnheckedMarker
84✔
1048
            : numSelectedRows === rows
44✔
1049
            ? headerCellCheckedMarker
6✔
1050
            : headerCellIndeterminateMarker;
38✔
1051

650✔
1052
    const mangledCols = React.useMemo(() => {
650✔
1053
        if (rowMarkers === "none") return columns;
146✔
1054
        return [
44✔
1055
            {
44✔
1056
                title: rowMarkerHeader,
44✔
1057
                width: rowMarkerWidth,
44✔
1058
                icon: undefined,
44✔
1059
                hasMenu: false,
44✔
1060
                style: "normal" as const,
44✔
1061
                themeOverride: rowMarkerTheme,
44✔
1062
            },
44✔
1063
            ...columns,
44✔
1064
        ];
44✔
1065
    }, [columns, rowMarkerWidth, rowMarkers, rowMarkerHeader, rowMarkerTheme]);
650✔
1066

650✔
1067
    const [visibleRegionY, visibleRegionTy] = React.useMemo(() => {
650✔
1068
        return [
132✔
1069
            scrollOffsetY !== undefined && typeof rowHeight === "number" ? Math.floor(scrollOffsetY / rowHeight) : 0,
132!
1070
            scrollOffsetY !== undefined && typeof rowHeight === "number" ? -(scrollOffsetY % rowHeight) : 0,
132!
1071
        ];
132✔
1072
    }, [scrollOffsetY, rowHeight]);
650✔
1073

650✔
1074
    type VisibleRegion = Rectangle & {
650✔
1075
        /** value in px */
650✔
1076
        tx?: number;
650✔
1077
        /** value in px */
650✔
1078
        ty?: number;
650✔
1079
        extras?: {
650✔
1080
            selected?: Item;
650✔
1081
            freezeRegion?: Rectangle;
650✔
1082
        };
650✔
1083
    };
650✔
1084

650✔
1085
    const visibleRegionRef = React.useRef<VisibleRegion>({
650✔
1086
        height: 1,
650✔
1087
        width: 1,
650✔
1088
        x: 0,
650✔
1089
        y: 0,
650✔
1090
    });
650✔
1091
    const visibleRegionInput = React.useMemo<VisibleRegion>(
650✔
1092
        () => ({
650✔
1093
            x: visibleRegionRef.current.x,
132✔
1094
            y: visibleRegionY,
132✔
1095
            width: visibleRegionRef.current.width ?? 1,
132!
1096
            height: visibleRegionRef.current.height ?? 1,
132!
1097
            // tx: 'TODO',
132✔
1098
            ty: visibleRegionTy,
132✔
1099
        }),
132✔
1100
        [visibleRegionTy, visibleRegionY]
650✔
1101
    );
650✔
1102

650✔
1103
    const hasJustScrolled = React.useRef(false);
650✔
1104

650✔
1105
    const [visibleRegion, setVisibleRegion, empty] = useStateWithReactiveInput<VisibleRegion>(visibleRegionInput);
650✔
1106

650✔
1107
    const vScrollReady = (visibleRegion.height ?? 1) > 1;
650!
1108
    React.useLayoutEffect(() => {
650✔
1109
        if (scrollOffsetY !== undefined && scrollRef.current !== null && vScrollReady) {
264!
1110
            if (scrollRef.current.scrollTop === scrollOffsetY) return;
×
1111
            scrollRef.current.scrollTop = scrollOffsetY;
×
UNCOV
1112
            if (scrollRef.current.scrollTop !== scrollOffsetY) {
×
1113
                empty();
×
UNCOV
1114
            }
×
1115
            hasJustScrolled.current = true;
×
UNCOV
1116
        }
×
1117
    }, [scrollOffsetY, vScrollReady, empty]);
650✔
1118

650✔
1119
    const hScrollReady = (visibleRegion.width ?? 1) > 1;
650!
1120
    React.useLayoutEffect(() => {
650✔
1121
        if (scrollOffsetX !== undefined && scrollRef.current !== null && hScrollReady) {
264!
1122
            if (scrollRef.current.scrollLeft === scrollOffsetX) return;
×
1123
            scrollRef.current.scrollLeft = scrollOffsetX;
×
UNCOV
1124
            if (scrollRef.current.scrollLeft !== scrollOffsetX) {
×
1125
                empty();
×
UNCOV
1126
            }
×
1127
            hasJustScrolled.current = true;
×
UNCOV
1128
        }
×
1129
    }, [scrollOffsetX, hScrollReady, empty]);
650✔
1130

650✔
1131
    const cellXOffset = visibleRegion.x + rowMarkerOffset;
650✔
1132
    const cellYOffset = visibleRegion.y;
650✔
1133

650✔
1134
    const gridRef = React.useRef<DataGridRef | null>(null);
650✔
1135

650✔
1136
    const focus = React.useCallback((immediate?: boolean) => {
650✔
1137
        if (immediate === true) {
121✔
1138
            gridRef.current?.focus();
7✔
1139
        } else {
121✔
1140
            window.requestAnimationFrame(() => {
114✔
1141
                gridRef.current?.focus();
113✔
1142
            });
114✔
1143
        }
114✔
1144
    }, []);
650✔
1145

650✔
1146
    const mangledRows = showTrailingBlankRow ? rows + 1 : rows;
650!
1147

650✔
1148
    const mangledOnCellsEdited = React.useCallback<NonNullable<typeof onCellsEdited>>(
650✔
1149
        (items: readonly EditListItem[]) => {
650✔
1150
            const mangledItems =
27✔
1151
                rowMarkerOffset === 0
27✔
1152
                    ? items
22✔
1153
                    : items.map(x => ({
5✔
1154
                          ...x,
29✔
1155
                          location: [x.location[0] - rowMarkerOffset, x.location[1]] as const,
29✔
1156
                      }));
5✔
1157
            const r = onCellsEdited?.(mangledItems);
27✔
1158

27✔
1159
            if (r !== true) {
27✔
1160
                for (const i of mangledItems) onCellEdited?.(i.location, i.value);
26✔
1161
            }
26✔
1162

27✔
1163
            return r;
27✔
1164
        },
27✔
1165
        [onCellEdited, onCellsEdited, rowMarkerOffset]
650✔
1166
    );
650✔
1167

650✔
1168
    const [fillHighlightRegion, setFillHighlightRegion] = React.useState<Rectangle | undefined>();
650✔
1169

650✔
1170
    // this will generally be undefined triggering the memo less often
650✔
1171
    const highlightRange =
650✔
1172
        gridSelection.current !== undefined &&
650✔
1173
        gridSelection.current.range.width * gridSelection.current.range.height > 1
303✔
1174
            ? gridSelection.current.range
41✔
1175
            : undefined;
608✔
1176
    const highlightRegions = React.useMemo(() => {
650✔
1177
        if (
167✔
1178
            (highlightRegionsIn === undefined || highlightRegionsIn.length === 0) &&
167✔
1179
            highlightRange === undefined &&
166✔
1180
            fillHighlightRegion === undefined
139✔
1181
        )
167✔
1182
            return undefined;
167✔
1183

33✔
1184
        const regions: Highlight[] = [];
33✔
1185

33✔
1186
        if (highlightRegionsIn !== undefined) {
161✔
1187
            for (const r of highlightRegionsIn) {
1✔
1188
                const maxWidth = mangledCols.length - r.range.x - rowMarkerOffset;
1✔
1189
                if (maxWidth > 0) {
1✔
1190
                    regions.push({
1✔
1191
                        color: r.color,
1✔
1192
                        range: {
1✔
1193
                            ...r.range,
1✔
1194
                            x: r.range.x + rowMarkerOffset,
1✔
1195
                            width: Math.min(maxWidth, r.range.width),
1✔
1196
                        },
1✔
1197
                        style: r.style,
1✔
1198
                    });
1✔
1199
                }
1✔
1200
            }
1✔
1201
        }
1✔
1202

33✔
1203
        if (fillHighlightRegion !== undefined) {
161✔
1204
            regions.push({
5✔
1205
                color: withAlpha(mergedTheme.accentColor, 0),
5✔
1206
                range: fillHighlightRegion,
5✔
1207
                style: "dashed",
5✔
1208
            });
5✔
1209
        }
5✔
1210

33✔
1211
        if (highlightRange !== undefined) {
161✔
1212
            regions.push({
27✔
1213
                color: withAlpha(mergedTheme.accentColor, 0.5),
27✔
1214
                range: highlightRange,
27✔
1215
                style: "solid-outline",
27✔
1216
            });
27✔
1217
        }
27✔
1218

33✔
1219
        return regions.length > 0 ? regions : undefined;
167!
1220
    }, [
650✔
1221
        fillHighlightRegion,
650✔
1222
        highlightRange,
650✔
1223
        highlightRegionsIn,
650✔
1224
        mangledCols.length,
650✔
1225
        mergedTheme.accentColor,
650✔
1226
        rowMarkerOffset,
650✔
1227
    ]);
650✔
1228

650✔
1229
    const mangledColsRef = React.useRef(mangledCols);
650✔
1230
    mangledColsRef.current = mangledCols;
650✔
1231
    const getMangledCellContent = React.useCallback(
650✔
1232
        ([col, row]: Item, forceStrict: boolean = false): InnerGridCell => {
650✔
1233
            const isTrailing = showTrailingBlankRow && row === mangledRows - 1;
132,821✔
1234
            const isRowMarkerCol = col === 0 && hasRowMarkers;
132,821✔
1235
            if (isRowMarkerCol) {
132,821✔
1236
                if (isTrailing) {
2,153✔
1237
                    return loadingCell;
96✔
1238
                }
96✔
1239
                return {
2,057✔
1240
                    kind: InnerGridCellKind.Marker,
2,057✔
1241
                    allowOverlay: false,
2,057✔
1242
                    checked: gridSelection?.rows.hasIndex(row) === true,
2,153✔
1243
                    markerKind: rowMarkers === "clickable-number" ? "number" : rowMarkers,
2,153!
1244
                    row: rowMarkerStartIndex + row,
2,153✔
1245
                    drawHandle: onRowMoved !== undefined,
2,153✔
1246
                    cursor: rowMarkers === "clickable-number" ? "pointer" : undefined,
2,153!
1247
                };
2,153✔
1248
            } else if (isTrailing) {
132,821✔
1249
                //If the grid is empty, we will return text
3,749✔
1250
                const isFirst = col === rowMarkerOffset;
3,749✔
1251

3,749✔
1252
                const maybeFirstColumnHint = isFirst ? trailingRowOptions?.hint ?? "" : "";
3,749✔
1253
                const c = mangledColsRef.current[col];
3,749✔
1254

3,749✔
1255
                if (c?.trailingRowOptions?.disabled === true) {
3,749!
1256
                    return loadingCell;
×
1257
                } else {
3,749✔
1258
                    const hint = c?.trailingRowOptions?.hint ?? maybeFirstColumnHint;
3,749!
1259
                    const icon = c?.trailingRowOptions?.addIcon ?? trailingRowOptions?.addIcon;
3,749!
1260
                    return {
3,749✔
1261
                        kind: InnerGridCellKind.NewRow,
3,749✔
1262
                        hint,
3,749✔
1263
                        allowOverlay: false,
3,749✔
1264
                        icon,
3,749✔
1265
                    };
3,749✔
1266
                }
3,749✔
1267
            } else {
130,668✔
1268
                const outerCol = col - rowMarkerOffset;
126,919✔
1269
                if (forceStrict || experimental?.strict === true) {
126,919✔
1270
                    const vr = visibleRegionRef.current;
21,689✔
1271
                    const isOutsideMainArea =
21,689✔
1272
                        vr.x > outerCol || outerCol > vr.x + vr.width || vr.y > row || row > vr.y + vr.height;
21,689✔
1273
                    const isSelected = outerCol === vr.extras?.selected?.[0] && row === vr.extras?.selected[1];
21,689!
1274
                    const isOutsideFreezeArea =
21,689✔
1275
                        vr.extras?.freezeRegion === undefined ||
21,689!
UNCOV
1276
                        vr.extras.freezeRegion.x > outerCol ||
×
UNCOV
1277
                        outerCol > vr.extras.freezeRegion.x + vr.extras.freezeRegion.width ||
×
UNCOV
1278
                        vr.extras.freezeRegion.y > row ||
×
UNCOV
1279
                        row > vr.extras.freezeRegion.y + vr.extras.freezeRegion.height;
×
1280
                    if (isOutsideMainArea && !isSelected && isOutsideFreezeArea) {
21,689!
NEW
1281
                        return loadingCell;
×
UNCOV
1282
                    }
×
1283
                }
21,689✔
1284
                let result = getCellContent([outerCol, row]);
126,919✔
1285
                if (rowMarkerOffset !== 0 && result.span !== undefined) {
126,919!
1286
                    result = {
×
UNCOV
1287
                        ...result,
×
UNCOV
1288
                        span: [result.span[0] + rowMarkerOffset, result.span[1] + rowMarkerOffset],
×
UNCOV
1289
                    };
×
UNCOV
1290
                }
×
1291
                return result;
126,919✔
1292
            }
126,919✔
1293
        },
132,821✔
1294
        [
650✔
1295
            showTrailingBlankRow,
650✔
1296
            mangledRows,
650✔
1297
            hasRowMarkers,
650✔
1298
            gridSelection?.rows,
650✔
1299
            onRowMoved,
650✔
1300
            rowMarkers,
650✔
1301
            rowMarkerOffset,
650✔
1302
            trailingRowOptions?.hint,
650✔
1303
            trailingRowOptions?.addIcon,
650✔
1304
            experimental?.strict,
650✔
1305
            getCellContent,
650✔
1306
            rowMarkerStartIndex,
650✔
1307
        ]
650✔
1308
    );
650✔
1309

650✔
1310
    const mangledGetGroupDetails = React.useCallback<NonNullable<DataEditorProps["getGroupDetails"]>>(
650✔
1311
        group => {
650✔
1312
            let result = getGroupDetails?.(group) ?? { name: group };
8,000✔
1313
            if (onGroupHeaderRenamed !== undefined && group !== "") {
8,000✔
1314
                result = {
91✔
1315
                    icon: result.icon,
91✔
1316
                    name: result.name,
91✔
1317
                    overrideTheme: result.overrideTheme,
91✔
1318
                    actions: [
91✔
1319
                        ...(result.actions ?? []),
91✔
1320
                        {
91✔
1321
                            title: "Rename",
91✔
1322
                            icon: "renameIcon",
91✔
1323
                            onClick: e =>
91✔
1324
                                setRenameGroup({
2✔
1325
                                    group: result.name,
2✔
1326
                                    bounds: e.bounds,
2✔
1327
                                }),
2✔
1328
                        },
91✔
1329
                    ],
91✔
1330
                };
91✔
1331
            }
91✔
1332
            return result;
8,000✔
1333
        },
8,000✔
1334
        [getGroupDetails, onGroupHeaderRenamed]
650✔
1335
    );
650✔
1336

650✔
1337
    const setOverlaySimple = React.useCallback(
650✔
1338
        (val: Omit<NonNullable<typeof overlay>, "theme">) => {
650✔
1339
            const [col, row] = val.cell;
16✔
1340
            const column = mangledCols[col];
16✔
1341
            const groupTheme =
16✔
1342
                column?.group !== undefined ? mangledGetGroupDetails(column.group)?.overrideTheme : undefined;
16!
1343
            const colTheme = column?.themeOverride;
16✔
1344
            const rowTheme = getRowThemeOverride?.(row);
16!
1345

16✔
1346
            setOverlay({
16✔
1347
                ...val,
16✔
1348
                theme: mergeAndRealizeTheme(mergedTheme, groupTheme, colTheme, rowTheme, val.content.themeOverride),
16✔
1349
            });
16✔
1350
        },
16✔
1351
        [getRowThemeOverride, mangledCols, mangledGetGroupDetails, mergedTheme]
650✔
1352
    );
650✔
1353

650✔
1354
    const reselect = React.useCallback(
650✔
1355
        (bounds: Rectangle, fromKeyboard: boolean, initialValue?: string) => {
650✔
1356
            if (gridSelection.current === undefined) return;
16!
1357

16✔
1358
            const [col, row] = gridSelection.current.cell;
16✔
1359
            const c = getMangledCellContent([col, row]);
16✔
1360
            if (c.kind !== GridCellKind.Boolean && c.allowOverlay) {
16✔
1361
                let content = c;
15✔
1362
                if (initialValue !== undefined) {
15✔
1363
                    switch (content.kind) {
7✔
1364
                        case GridCellKind.Number: {
7!
1365
                            const d = maybe(() => (initialValue === "-" ? -0 : Number.parseFloat(initialValue)), 0);
×
1366
                            content = {
×
UNCOV
1367
                                ...content,
×
UNCOV
1368
                                data: Number.isNaN(d) ? 0 : d,
×
UNCOV
1369
                            };
×
1370
                            break;
×
UNCOV
1371
                        }
×
1372
                        case GridCellKind.Text:
7✔
1373
                        case GridCellKind.Markdown:
7✔
1374
                        case GridCellKind.Uri:
7✔
1375
                            content = {
7✔
1376
                                ...content,
7✔
1377
                                data: initialValue,
7✔
1378
                            };
7✔
1379
                            break;
7✔
1380
                    }
7✔
1381
                }
7✔
1382

15✔
1383
                setOverlaySimple({
15✔
1384
                    target: bounds,
15✔
1385
                    content,
15✔
1386
                    initialValue,
15✔
1387
                    cell: [col, row],
15✔
1388
                    highlight: initialValue === undefined,
15✔
1389
                    forceEditMode: initialValue !== undefined,
15✔
1390
                });
15✔
1391
            } else if (c.kind === GridCellKind.Boolean && fromKeyboard && c.readonly !== true) {
16!
1392
                mangledOnCellsEdited([
×
UNCOV
1393
                    {
×
UNCOV
1394
                        location: gridSelection.current.cell,
×
UNCOV
1395
                        value: {
×
UNCOV
1396
                            ...c,
×
UNCOV
1397
                            data: toggleBoolean(c.data),
×
UNCOV
1398
                        },
×
UNCOV
1399
                    },
×
UNCOV
1400
                ]);
×
1401
                gridRef.current?.damage([{ cell: gridSelection.current.cell }]);
×
UNCOV
1402
            }
×
1403
        },
16✔
1404
        [getMangledCellContent, gridSelection, mangledOnCellsEdited, setOverlaySimple]
650✔
1405
    );
650✔
1406

650✔
1407
    const focusOnRowFromTrailingBlankRow = React.useCallback(
650✔
1408
        (col: number, row: number) => {
650✔
1409
            const bounds = gridRef.current?.getBounds(col, row);
1✔
1410
            if (bounds === undefined || scrollRef.current === null) {
1!
1411
                return;
×
UNCOV
1412
            }
×
1413

1✔
1414
            const content = getMangledCellContent([col, row]);
1✔
1415
            if (!content.allowOverlay) {
1!
1416
                return;
×
UNCOV
1417
            }
×
1418

1✔
1419
            setOverlaySimple({
1✔
1420
                target: bounds,
1✔
1421
                content,
1✔
1422
                initialValue: undefined,
1✔
1423
                highlight: true,
1✔
1424
                cell: [col, row],
1✔
1425
                forceEditMode: true,
1✔
1426
            });
1✔
1427
        },
1✔
1428
        [getMangledCellContent, setOverlaySimple]
650✔
1429
    );
650✔
1430

650✔
1431
    const scrollTo = React.useCallback<ScrollToFn>(
650✔
1432
        (col, row, dir = "both", paddingX = 0, paddingY = 0, options = undefined): void => {
650✔
1433
            if (scrollRef.current !== null) {
43✔
1434
                const grid = gridRef.current;
43✔
1435
                const canvas = canvasRef.current;
43✔
1436

43✔
1437
                const trueCol = typeof col !== "number" ? (col.unit === "cell" ? col.amount : undefined) : col;
43!
1438
                const trueRow = typeof row !== "number" ? (row.unit === "cell" ? row.amount : undefined) : row;
43!
1439
                const desiredX = typeof col !== "number" && col.unit === "px" ? col.amount : undefined;
43!
1440
                const desiredY = typeof row !== "number" && row.unit === "px" ? row.amount : undefined;
43✔
1441
                if (grid !== null && canvas !== null) {
43✔
1442
                    let targetRect: Rectangle = {
43✔
1443
                        x: 0,
43✔
1444
                        y: 0,
43✔
1445
                        width: 0,
43✔
1446
                        height: 0,
43✔
1447
                    };
43✔
1448

43✔
1449
                    let scrollX = 0;
43✔
1450
                    let scrollY = 0;
43✔
1451

43✔
1452
                    if (trueCol !== undefined || trueRow !== undefined) {
43!
1453
                        targetRect = grid.getBounds((trueCol ?? 0) + rowMarkerOffset, trueRow ?? 0) ?? targetRect;
43!
1454
                        if (targetRect.width === 0 || targetRect.height === 0) return;
43!
1455
                    }
43✔
1456

43✔
1457
                    const scrollBounds = canvas.getBoundingClientRect();
43✔
1458
                    const scale = scrollBounds.width / canvas.offsetWidth;
43✔
1459

43✔
1460
                    if (desiredX !== undefined) {
43!
1461
                        targetRect = {
×
UNCOV
1462
                            ...targetRect,
×
UNCOV
1463
                            x: desiredX - scrollBounds.left - scrollRef.current.scrollLeft,
×
UNCOV
1464
                            width: 1,
×
UNCOV
1465
                        };
×
UNCOV
1466
                    }
×
1467
                    if (desiredY !== undefined) {
43✔
1468
                        targetRect = {
4✔
1469
                            ...targetRect,
4✔
1470
                            y: desiredY + scrollBounds.top - scrollRef.current.scrollTop,
4✔
1471
                            height: 1,
4✔
1472
                        };
4✔
1473
                    }
4✔
1474

43✔
1475
                    if (targetRect !== undefined) {
43✔
1476
                        const bounds = {
43✔
1477
                            x: targetRect.x - paddingX,
43✔
1478
                            y: targetRect.y - paddingY,
43✔
1479
                            width: targetRect.width + 2 * paddingX,
43✔
1480
                            height: targetRect.height + 2 * paddingY,
43✔
1481
                        };
43✔
1482

43✔
1483
                        let frozenWidth = 0;
43✔
1484
                        for (let i = 0; i < freezeColumns; i++) {
43!
1485
                            frozenWidth += columns[i].width;
×
UNCOV
1486
                        }
×
1487
                        let trailingRowHeight = 0;
43✔
1488
                        if (lastRowSticky) {
43✔
1489
                            trailingRowHeight = typeof rowHeight === "number" ? rowHeight : rowHeight(rows);
43!
1490
                        }
43✔
1491

43✔
1492
                        // scrollBounds is already scaled
43✔
1493
                        let sLeft = frozenWidth * scale + scrollBounds.left + rowMarkerOffset * rowMarkerWidth * scale;
43✔
1494
                        let sRight = scrollBounds.right;
43✔
1495
                        let sTop = scrollBounds.top + totalHeaderHeight * scale;
43✔
1496
                        let sBottom = scrollBounds.bottom - trailingRowHeight * scale;
43✔
1497

43✔
1498
                        const minx = targetRect.width + paddingX * 2;
43✔
1499
                        switch (options?.hAlign) {
43✔
1500
                            case "start":
43!
1501
                                sRight = sLeft + minx;
×
1502
                                break;
×
1503
                            case "end":
43!
1504
                                sLeft = sRight - minx;
×
1505
                                break;
×
1506
                            case "center":
43!
1507
                                sLeft = Math.floor((sLeft + sRight) / 2) - minx / 2;
×
1508
                                sRight = sLeft + minx;
×
1509
                                break;
×
1510
                        }
43✔
1511

43✔
1512
                        const miny = targetRect.height + paddingY * 2;
43✔
1513
                        switch (options?.vAlign) {
43✔
1514
                            case "start":
43✔
1515
                                sBottom = sTop + miny;
1✔
1516
                                break;
1✔
1517
                            case "end":
43✔
1518
                                sTop = sBottom - miny;
1✔
1519
                                break;
1✔
1520
                            case "center":
43✔
1521
                                sTop = Math.floor((sTop + sBottom) / 2) - miny / 2;
1✔
1522
                                sBottom = sTop + miny;
1✔
1523
                                break;
1✔
1524
                        }
43✔
1525

43✔
1526
                        if (sLeft > bounds.x) {
43!
1527
                            scrollX = bounds.x - sLeft;
×
1528
                        } else if (sRight < bounds.x + bounds.width) {
43✔
1529
                            scrollX = bounds.x + bounds.width - sRight;
4✔
1530
                        }
4✔
1531

43✔
1532
                        if (sTop > bounds.y) {
43!
1533
                            scrollY = bounds.y - sTop;
×
1534
                        } else if (sBottom < bounds.y + bounds.height) {
43✔
1535
                            scrollY = bounds.y + bounds.height - sBottom;
12✔
1536
                        }
12✔
1537

43✔
1538
                        if (dir === "vertical" || (typeof col === "number" && col < freezeColumns)) {
43✔
1539
                            scrollX = 0;
2✔
1540
                        } else if (dir === "horizontal") {
43✔
1541
                            scrollY = 0;
6✔
1542
                        }
6✔
1543

43✔
1544
                        if (scrollX !== 0 || scrollY !== 0) {
43✔
1545
                            // Remove scaling as scrollTo method is unaffected by transform scale.
15✔
1546
                            if (scale !== 1) {
15!
1547
                                scrollX /= scale;
×
1548
                                scrollY /= scale;
×
UNCOV
1549
                            }
×
1550
                            scrollRef.current.scrollTo(
15✔
1551
                                scrollX + scrollRef.current.scrollLeft,
15✔
1552
                                scrollY + scrollRef.current.scrollTop
15✔
1553
                            );
15✔
1554
                        }
15✔
1555
                    }
43✔
1556
                }
43✔
1557
            }
43✔
1558
        },
43✔
1559
        [rowMarkerOffset, rowMarkerWidth, totalHeaderHeight, lastRowSticky, freezeColumns, columns, rowHeight, rows]
650✔
1560
    );
650✔
1561

650✔
1562
    const focusCallback = React.useRef(focusOnRowFromTrailingBlankRow);
650✔
1563
    const getCellContentRef = React.useRef(getCellContent);
650✔
1564
    const rowsRef = React.useRef(rows);
650✔
1565
    focusCallback.current = focusOnRowFromTrailingBlankRow;
650✔
1566
    getCellContentRef.current = getCellContent;
650✔
1567
    rowsRef.current = rows;
650✔
1568
    const appendRow = React.useCallback(
650✔
1569
        async (col: number, openOverlay: boolean = true): Promise<void> => {
650✔
1570
            const c = mangledCols[col];
1✔
1571
            if (c?.trailingRowOptions?.disabled === true) {
1!
1572
                return;
×
UNCOV
1573
            }
×
1574
            const appendResult = onRowAppended?.();
1✔
1575

1✔
1576
            let r: "top" | "bottom" | number | undefined = undefined;
1✔
1577
            let bottom = true;
1✔
1578
            if (appendResult !== undefined) {
1!
1579
                r = await appendResult;
×
1580
                if (r === "top") bottom = false;
×
1581
                if (typeof r === "number") bottom = false;
×
UNCOV
1582
            }
×
1583

1✔
1584
            let backoff = 0;
1✔
1585
            const doFocus = () => {
1✔
1586
                if (rowsRef.current <= rows) {
2✔
1587
                    if (backoff < 500) {
1✔
1588
                        window.setTimeout(doFocus, backoff);
1✔
1589
                    }
1✔
1590
                    backoff = 50 + backoff * 2;
1✔
1591
                    return;
1✔
1592
                }
1✔
1593

1✔
1594
                const row = typeof r === "number" ? r : bottom ? rows : 0;
2!
1595
                scrollTo(col - rowMarkerOffset, row);
2✔
1596
                setCurrent(
2✔
1597
                    {
2✔
1598
                        cell: [col, row],
2✔
1599
                        range: {
2✔
1600
                            x: col,
2✔
1601
                            y: row,
2✔
1602
                            width: 1,
2✔
1603
                            height: 1,
2✔
1604
                        },
2✔
1605
                    },
2✔
1606
                    false,
2✔
1607
                    false,
2✔
1608
                    "edit"
2✔
1609
                );
2✔
1610

2✔
1611
                const cell = getCellContentRef.current([col - rowMarkerOffset, row]);
2✔
1612
                if (cell.allowOverlay && isReadWriteCell(cell) && cell.readonly !== true && openOverlay) {
2✔
1613
                    // wait for scroll to have a chance to process
1✔
1614
                    window.setTimeout(() => {
1✔
1615
                        focusCallback.current(col, row);
1✔
1616
                    }, 0);
1✔
1617
                }
1✔
1618
            };
2✔
1619
            // Queue up to allow the consumer to react to the event and let us check if they did
1✔
1620
            doFocus();
1✔
1621
        },
1✔
1622
        [mangledCols, onRowAppended, rowMarkerOffset, rows, scrollTo, setCurrent]
650✔
1623
    );
650✔
1624

650✔
1625
    const getCustomNewRowTargetColumn = React.useCallback(
650✔
1626
        (col: number): number | undefined => {
650✔
1627
            const customTargetColumn =
1✔
1628
                columns[col]?.trailingRowOptions?.targetColumn ?? trailingRowOptions?.targetColumn;
1!
1629

1✔
1630
            if (typeof customTargetColumn === "number") {
1!
1631
                const customTargetOffset = hasRowMarkers ? 1 : 0;
×
1632
                return customTargetColumn + customTargetOffset;
×
UNCOV
1633
            }
×
1634

1✔
1635
            if (typeof customTargetColumn === "object") {
1!
1636
                const maybeIndex = columnsIn.indexOf(customTargetColumn);
×
UNCOV
1637
                if (maybeIndex >= 0) {
×
1638
                    const customTargetOffset = hasRowMarkers ? 1 : 0;
×
1639
                    return maybeIndex + customTargetOffset;
×
UNCOV
1640
                }
×
UNCOV
1641
            }
×
1642

1✔
1643
            return undefined;
1✔
1644
        },
1✔
1645
        [columns, columnsIn, hasRowMarkers, trailingRowOptions?.targetColumn]
650✔
1646
    );
650✔
1647

650✔
1648
    const lastSelectedRowRef = React.useRef<number>();
650✔
1649
    const lastSelectedColRef = React.useRef<number>();
650✔
1650

650✔
1651
    const themeForCell = React.useCallback(
650✔
1652
        (cell: InnerGridCell, pos: Item): FullTheme => {
650✔
1653
            const [col, row] = pos;
20✔
1654
            return mergeAndRealizeTheme(
20✔
1655
                mergedTheme,
20✔
1656
                mangledCols[col]?.themeOverride,
20✔
1657
                getRowThemeOverride?.(row),
20!
1658
                cell.themeOverride
20✔
1659
            );
20✔
1660
        },
20✔
1661
        [getRowThemeOverride, mangledCols, mergedTheme]
650✔
1662
    );
650✔
1663

650✔
1664
    const handleSelect = React.useCallback(
650✔
1665
        (args: GridMouseEventArgs) => {
650✔
1666
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
111!
1667
            const isMultiRow = isMultiKey && rowSelect === "multi";
111✔
1668
            const isMultiCol = isMultiKey && columnSelect === "multi";
111✔
1669
            const [col, row] = args.location;
111✔
1670
            const selectedColumns = gridSelection.columns;
111✔
1671
            const selectedRows = gridSelection.rows;
111✔
1672
            const [cellCol, cellRow] = gridSelection.current?.cell ?? [];
111✔
1673
            // eslint-disable-next-line unicorn/prefer-switch
111✔
1674
            if (args.kind === "cell") {
111✔
1675
                lastSelectedColRef.current = undefined;
95✔
1676

95✔
1677
                lastMouseSelectLocation.current = [col, row];
95✔
1678

95✔
1679
                if (col === 0 && hasRowMarkers) {
95✔
1680
                    if (
15✔
1681
                        (showTrailingBlankRow === true && row === rows) ||
15✔
1682
                        rowMarkers === "number" ||
15✔
1683
                        rowSelect === "none"
14✔
1684
                    )
15✔
1685
                        return;
15✔
1686

14✔
1687
                    const markerCell = getMangledCellContent(args.location);
14✔
1688
                    if (markerCell.kind !== InnerGridCellKind.Marker) {
15!
1689
                        return;
×
UNCOV
1690
                    }
✔
1691

14✔
1692
                    if (onRowMoved !== undefined) {
15!
1693
                        const renderer = getCellRenderer(markerCell);
×
1694
                        assert(renderer?.kind === InnerGridCellKind.Marker);
×
1695
                        const postClick = renderer?.onClick?.({
×
UNCOV
1696
                            ...args,
×
UNCOV
1697
                            cell: markerCell,
×
UNCOV
1698
                            posX: args.localEventX,
×
UNCOV
1699
                            posY: args.localEventY,
×
UNCOV
1700
                            bounds: args.bounds,
×
UNCOV
1701
                            theme: themeForCell(markerCell, args.location),
×
1702
                            preventDefault: () => undefined,
×
UNCOV
1703
                        }) as MarkerCell | undefined;
×
1704
                        if (postClick === undefined || postClick.checked === markerCell.checked) return;
×
UNCOV
1705
                    }
✔
1706

14✔
1707
                    setOverlay(undefined);
14✔
1708
                    focus();
14✔
1709
                    const isSelected = selectedRows.hasIndex(row);
14✔
1710

14✔
1711
                    const lastHighlighted = lastSelectedRowRef.current;
14✔
1712
                    if (
14✔
1713
                        rowSelect === "multi" &&
14✔
1714
                        (args.shiftKey || args.isLongTouch === true) &&
8✔
1715
                        lastHighlighted !== undefined &&
1✔
1716
                        selectedRows.hasIndex(lastHighlighted)
1✔
1717
                    ) {
15✔
1718
                        const newSlice: Slice = [Math.min(lastHighlighted, row), Math.max(lastHighlighted, row) + 1];
1✔
1719

1✔
1720
                        if (isMultiRow || rowSelectionMode === "multi") {
1!
1721
                            setSelectedRows(undefined, newSlice, true);
×
1722
                        } else {
1✔
1723
                            setSelectedRows(CompactSelection.fromSingleSelection(newSlice), undefined, isMultiRow);
1✔
1724
                        }
1✔
1725
                    } else if (isMultiRow || args.isTouch || rowSelectionMode === "multi") {
15✔
1726
                        if (isSelected) {
3✔
1727
                            setSelectedRows(selectedRows.remove(row), undefined, true);
1✔
1728
                        } else {
2✔
1729
                            setSelectedRows(undefined, row, true);
2✔
1730
                            lastSelectedRowRef.current = row;
2✔
1731
                        }
2✔
1732
                    } else if (isSelected && selectedRows.length === 1) {
13✔
1733
                        setSelectedRows(CompactSelection.empty(), undefined, isMultiKey);
1✔
1734
                    } else {
10✔
1735
                        setSelectedRows(CompactSelection.fromSingleSelection(row), undefined, isMultiKey);
9✔
1736
                        lastSelectedRowRef.current = row;
9✔
1737
                    }
9✔
1738
                } else if (col >= rowMarkerOffset && showTrailingBlankRow && row === rows) {
95✔
1739
                    const customTargetColumn = getCustomNewRowTargetColumn(col);
1✔
1740
                    void appendRow(customTargetColumn ?? col);
1✔
1741
                } else {
80✔
1742
                    if (cellCol !== col || cellRow !== row) {
79✔
1743
                        const cell = getMangledCellContent(args.location);
76✔
1744
                        const renderer = getCellRenderer(cell);
76✔
1745

76✔
1746
                        if (renderer?.onSelect !== undefined) {
76!
1747
                            let prevented = false;
×
1748
                            renderer.onSelect({
×
UNCOV
1749
                                ...args,
×
UNCOV
1750
                                cell,
×
UNCOV
1751
                                posX: args.localEventX,
×
UNCOV
1752
                                posY: args.localEventY,
×
UNCOV
1753
                                bounds: args.bounds,
×
1754
                                preventDefault: () => (prevented = true),
×
UNCOV
1755
                                theme: themeForCell(cell, args.location),
×
UNCOV
1756
                            });
×
UNCOV
1757
                            if (prevented) {
×
1758
                                return;
×
UNCOV
1759
                            }
×
UNCOV
1760
                        }
×
1761
                        const isLastStickyRow = lastRowSticky && row === rows;
76✔
1762

76✔
1763
                        const startedFromLastSticky =
76✔
1764
                            lastRowSticky && gridSelection !== undefined && gridSelection.current?.cell[1] === rows;
76✔
1765

76✔
1766
                        if (
76✔
1767
                            (args.shiftKey || args.isLongTouch === true) &&
76✔
1768
                            cellCol !== undefined &&
6✔
1769
                            cellRow !== undefined &&
6✔
1770
                            gridSelection.current !== undefined &&
6✔
1771
                            !startedFromLastSticky
6✔
1772
                        ) {
76✔
1773
                            if (isLastStickyRow) {
6!
UNCOV
1774
                                // If we're making a selection and shift click in to the last sticky row,
×
UNCOV
1775
                                // just drop the event. Don't kill the selection.
×
1776
                                return;
×
UNCOV
1777
                            }
×
1778

6✔
1779
                            const left = Math.min(col, cellCol);
6✔
1780
                            const right = Math.max(col, cellCol);
6✔
1781
                            const top = Math.min(row, cellRow);
6✔
1782
                            const bottom = Math.max(row, cellRow);
6✔
1783
                            setCurrent(
6✔
1784
                                {
6✔
1785
                                    ...gridSelection.current,
6✔
1786
                                    range: {
6✔
1787
                                        x: left,
6✔
1788
                                        y: top,
6✔
1789
                                        width: right - left + 1,
6✔
1790
                                        height: bottom - top + 1,
6✔
1791
                                    },
6✔
1792
                                },
6✔
1793
                                true,
6✔
1794
                                isMultiKey,
6✔
1795
                                "click"
6✔
1796
                            );
6✔
1797
                            lastSelectedRowRef.current = undefined;
6✔
1798
                            focus();
6✔
1799
                        } else {
76✔
1800
                            setCurrent(
70✔
1801
                                {
70✔
1802
                                    cell: [col, row],
70✔
1803
                                    range: { x: col, y: row, width: 1, height: 1 },
70✔
1804
                                },
70✔
1805
                                true,
70✔
1806
                                isMultiKey,
70✔
1807
                                "click"
70✔
1808
                            );
70✔
1809
                            lastSelectedRowRef.current = undefined;
70✔
1810
                            setOverlay(undefined);
70✔
1811
                            focus();
70✔
1812
                        }
70✔
1813
                    }
76✔
1814
                }
79✔
1815
            } else if (args.kind === "header") {
111✔
1816
                lastMouseSelectLocation.current = [col, row];
12✔
1817
                setOverlay(undefined);
12✔
1818
                if (hasRowMarkers && col === 0) {
12✔
1819
                    lastSelectedRowRef.current = undefined;
4✔
1820
                    lastSelectedColRef.current = undefined;
4✔
1821
                    if (rowSelect === "multi") {
4✔
1822
                        if (selectedRows.length !== rows) {
4✔
1823
                            setSelectedRows(CompactSelection.fromSingleSelection([0, rows]), undefined, isMultiKey);
3✔
1824
                        } else {
4✔
1825
                            setSelectedRows(CompactSelection.empty(), undefined, isMultiKey);
1✔
1826
                        }
1✔
1827
                        focus();
4✔
1828
                    }
4✔
1829
                } else {
12✔
1830
                    const lastCol = lastSelectedColRef.current;
8✔
1831
                    if (
8✔
1832
                        columnSelect === "multi" &&
8✔
1833
                        (args.shiftKey || args.isLongTouch === true) &&
7!
UNCOV
1834
                        lastCol !== undefined &&
×
UNCOV
1835
                        selectedColumns.hasIndex(lastCol)
×
1836
                    ) {
8!
1837
                        const newSlice: Slice = [Math.min(lastCol, col), Math.max(lastCol, col) + 1];
×
UNCOV
1838

×
UNCOV
1839
                        if (isMultiCol) {
×
1840
                            setSelectedColumns(undefined, newSlice, isMultiKey);
×
UNCOV
1841
                        } else {
×
1842
                            setSelectedColumns(CompactSelection.fromSingleSelection(newSlice), undefined, isMultiKey);
×
UNCOV
1843
                        }
×
1844
                    } else if (isMultiCol) {
8✔
1845
                        if (selectedColumns.hasIndex(col)) {
1!
1846
                            setSelectedColumns(selectedColumns.remove(col), undefined, isMultiKey);
×
1847
                        } else {
1✔
1848
                            setSelectedColumns(undefined, col, isMultiKey);
1✔
1849
                        }
1✔
1850
                        lastSelectedColRef.current = col;
1✔
1851
                    } else if (columnSelect !== "none") {
8✔
1852
                        setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, isMultiKey);
7✔
1853
                        lastSelectedColRef.current = col;
7✔
1854
                    }
7✔
1855
                    lastSelectedRowRef.current = undefined;
8✔
1856
                    focus();
8✔
1857
                }
8✔
1858
            } else if (args.kind === groupHeaderKind) {
16✔
1859
                lastMouseSelectLocation.current = [col, row];
3✔
1860
            } else if (args.kind === outOfBoundsKind && !args.isMaybeScrollbar) {
4✔
1861
                setGridSelection(emptyGridSelection, false);
1✔
1862
                setOverlay(undefined);
1✔
1863
                focus();
1✔
1864
                onSelectionCleared?.();
1!
1865
                lastSelectedRowRef.current = undefined;
1✔
1866
                lastSelectedColRef.current = undefined;
1✔
1867
            }
1✔
1868
        },
111✔
1869
        [
650✔
1870
            appendRow,
650✔
1871
            columnSelect,
650✔
1872
            focus,
650✔
1873
            getCellRenderer,
650✔
1874
            getCustomNewRowTargetColumn,
650✔
1875
            getMangledCellContent,
650✔
1876
            gridSelection,
650✔
1877
            hasRowMarkers,
650✔
1878
            lastRowSticky,
650✔
1879
            onSelectionCleared,
650✔
1880
            onRowMoved,
650✔
1881
            rowMarkerOffset,
650✔
1882
            rowMarkers,
650✔
1883
            rowSelect,
650✔
1884
            rowSelectionMode,
650✔
1885
            rows,
650✔
1886
            setCurrent,
650✔
1887
            setGridSelection,
650✔
1888
            setSelectedColumns,
650✔
1889
            setSelectedRows,
650✔
1890
            showTrailingBlankRow,
650✔
1891
            themeForCell,
650✔
1892
        ]
650✔
1893
    );
650✔
1894
    const isActivelyDraggingHeader = React.useRef(false);
650✔
1895
    const lastMouseSelectLocation = React.useRef<readonly [number, number]>();
650✔
1896
    const touchDownArgs = React.useRef(visibleRegion);
650✔
1897
    const mouseDownData = React.useRef<{
650✔
1898
        wasDoubleClick: boolean;
650✔
1899
        time: number;
650✔
1900
        button: number;
650✔
1901
        location: Item;
650✔
1902
    }>();
650✔
1903
    const onMouseDown = React.useCallback(
650✔
1904
        (args: GridMouseEventArgs) => {
650✔
1905
            isPrevented.current = false;
128✔
1906
            touchDownArgs.current = visibleRegionRef.current;
128✔
1907
            if (args.button !== 0 && args.button !== 1) {
128✔
1908
                mouseDownData.current = undefined;
1✔
1909
                return;
1✔
1910
            }
1✔
1911

127✔
1912
            const time = performance.now();
127✔
1913
            const wasDoubleClick = time - (mouseDownData.current?.time ?? -1000) < 250;
128✔
1914
            mouseDownData.current = {
128✔
1915
                wasDoubleClick,
128✔
1916
                button: args.button,
128✔
1917
                time,
128✔
1918
                location: args.location,
128✔
1919
            };
128✔
1920

128✔
1921
            if (args?.kind === "header") {
128✔
1922
                isActivelyDraggingHeader.current = true;
18✔
1923
            }
18✔
1924

127✔
1925
            const fh = args.kind === "cell" && args.isFillHandle;
128✔
1926

128✔
1927
            if (!fh && args.kind !== "cell" && args.isEdge) return;
128✔
1928

120✔
1929
            setMouseState({
120✔
1930
                previousSelection: gridSelection,
120✔
1931
                fillHandle: fh,
120✔
1932
            });
120✔
1933
            lastMouseSelectLocation.current = undefined;
120✔
1934

120✔
1935
            if (!args.isTouch && args.button === 0 && !fh) {
128✔
1936
                handleSelect(args);
108✔
1937
            } else if (!args.isTouch && args.button === 1) {
128✔
1938
                lastMouseSelectLocation.current = args.location;
4✔
1939
            }
4✔
1940
        },
128✔
1941
        [gridSelection, handleSelect]
650✔
1942
    );
650✔
1943

650✔
1944
    const [renameGroup, setRenameGroup] = React.useState<{
650✔
1945
        group: string;
650✔
1946
        bounds: Rectangle;
650✔
1947
    }>();
650✔
1948

650✔
1949
    const handleGroupHeaderSelection = React.useCallback(
650✔
1950
        (args: GridMouseEventArgs) => {
650✔
1951
            if (args.kind !== groupHeaderKind || columnSelect !== "multi") {
3!
1952
                return;
×
UNCOV
1953
            }
×
1954
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
3!
1955
            const [col] = args.location;
3✔
1956
            const selectedColumns = gridSelection.columns;
3✔
1957

3✔
1958
            if (col < rowMarkerOffset) return;
3!
1959

3✔
1960
            const needle = mangledCols[col];
3✔
1961
            let start = col;
3✔
1962
            let end = col;
3✔
1963
            for (let i = col - 1; i >= rowMarkerOffset; i--) {
3✔
1964
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
3!
1965
                start--;
3✔
1966
            }
3✔
1967

3✔
1968
            for (let i = col + 1; i < mangledCols.length; i++) {
3✔
1969
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
27!
1970
                end++;
27✔
1971
            }
27✔
1972

3✔
1973
            focus();
3✔
1974

3✔
1975
            if (isMultiKey) {
3✔
1976
                if (selectedColumns.hasAll([start, end + 1])) {
2✔
1977
                    let newVal = selectedColumns;
1✔
1978
                    for (let index = start; index <= end; index++) {
1✔
1979
                        newVal = newVal.remove(index);
11✔
1980
                    }
11✔
1981
                    setSelectedColumns(newVal, undefined, isMultiKey);
1✔
1982
                } else {
1✔
1983
                    setSelectedColumns(undefined, [start, end + 1], isMultiKey);
1✔
1984
                }
1✔
1985
            } else {
3✔
1986
                setSelectedColumns(CompactSelection.fromSingleSelection([start, end + 1]), undefined, isMultiKey);
1✔
1987
            }
1✔
1988
        },
3✔
1989
        [columnSelect, focus, gridSelection.columns, mangledCols, rowMarkerOffset, setSelectedColumns]
650✔
1990
    );
650✔
1991

650✔
1992
    const fillDown = React.useCallback(
650✔
1993
        (reverse: boolean) => {
650✔
1994
            if (gridSelection.current === undefined) return;
1!
1995
            const v: EditListItem[] = [];
1✔
1996
            const r = gridSelection.current.range;
1✔
1997
            for (let x = 0; x < r.width; x++) {
1✔
1998
                const fillCol = x + r.x;
2✔
1999
                const fillVal = getMangledCellContent([fillCol, reverse ? r.y + r.height - 1 : r.y]);
2!
2000
                if (isInnerOnlyCell(fillVal) || !isReadWriteCell(fillVal)) continue;
2!
2001
                for (let y = 1; y < r.height; y++) {
2✔
2002
                    const fillRow = reverse ? r.y + r.height - (y + 1) : y + r.y;
8!
2003
                    const target = [fillCol, fillRow] as const;
8✔
2004
                    v.push({
8✔
2005
                        location: target,
8✔
2006
                        value: { ...fillVal },
8✔
2007
                    });
8✔
2008
                }
8✔
2009
            }
2✔
2010

1✔
2011
            mangledOnCellsEdited(v);
1✔
2012

1✔
2013
            gridRef.current?.damage(
1✔
2014
                v.map(c => ({
1✔
2015
                    cell: c.location,
8✔
2016
                }))
1✔
2017
            );
1✔
2018
        },
1✔
2019
        [getMangledCellContent, gridSelection, mangledOnCellsEdited]
650✔
2020
    );
650✔
2021

650✔
2022
    const isPrevented = React.useRef(false);
650✔
2023

650✔
2024
    const normalSizeColumn = React.useCallback(
650✔
2025
        async (col: number, force: boolean = false): Promise<void> => {
650✔
2026
            if (
3✔
2027
                (mouseDownData.current?.wasDoubleClick === true || force) &&
3✔
2028
                getCellsForSelection !== undefined &&
2✔
2029
                onColumnResize !== undefined
2✔
2030
            ) {
3✔
2031
                const start = visibleRegionRef.current.y;
2✔
2032
                const end = visibleRegionRef.current.height;
2✔
2033
                let cells = getCellsForSelection(
2✔
2034
                    {
2✔
2035
                        x: col,
2✔
2036
                        y: start,
2✔
2037
                        width: 1,
2✔
2038
                        height: Math.min(end, rows - start),
2✔
2039
                    },
2✔
2040
                    abortControllerRef.current.signal
2✔
2041
                );
2✔
2042
                if (typeof cells !== "object") {
2!
2043
                    cells = await cells();
×
UNCOV
2044
                }
×
2045
                const inputCol = columns[col - rowMarkerOffset];
2✔
2046
                const offscreen = document.createElement("canvas");
2✔
2047
                const ctx = offscreen.getContext("2d", { alpha: false });
2✔
2048
                if (ctx !== null) {
2✔
2049
                    ctx.font = mergedTheme.baseFontFull;
2✔
2050
                    const newCol = measureColumn(
2✔
2051
                        ctx,
2✔
2052
                        mergedTheme,
2✔
2053
                        inputCol,
2✔
2054
                        0,
2✔
2055
                        cells,
2✔
2056
                        minColumnWidth,
2✔
2057
                        maxColumnWidth,
2✔
2058
                        false,
2✔
2059
                        getCellRenderer
2✔
2060
                    );
2✔
2061
                    onColumnResize?.(inputCol, newCol.width, col, newCol.width);
2✔
2062
                }
2✔
2063
            }
2✔
2064
        },
3✔
2065
        [
650✔
2066
            columns,
650✔
2067
            getCellsForSelection,
650✔
2068
            maxColumnWidth,
650✔
2069
            mergedTheme,
650✔
2070
            minColumnWidth,
650✔
2071
            onColumnResize,
650✔
2072
            rowMarkerOffset,
650✔
2073
            rows,
650✔
2074
            getCellRenderer,
650✔
2075
        ]
650✔
2076
    );
650✔
2077

650✔
2078
    const [scrollDir, setScrollDir] = React.useState<GridMouseEventArgs["scrollEdge"]>();
650✔
2079

650✔
2080
    const fillPattern = React.useCallback(
650✔
2081
        async (previousSelection: GridSelection, currentSelection: GridSelection) => {
650✔
2082
            const patternRange = previousSelection.current?.range;
4✔
2083

4✔
2084
            if (
4✔
2085
                patternRange === undefined ||
4✔
2086
                getCellsForSelection === undefined ||
4✔
2087
                currentSelection.current === undefined
4✔
2088
            ) {
4!
NEW
2089
                return;
×
NEW
2090
            }
×
2091
            const currentRange = currentSelection.current.range;
4✔
2092

4✔
2093
            if (onFillPattern !== undefined) {
4!
NEW
2094
                let canceled = false;
×
NEW
2095
                onFillPattern({
×
NEW
2096
                    fillDestination: { ...currentRange, x: currentRange.x - rowMarkerOffset },
×
NEW
2097
                    patternSource: { ...patternRange, x: patternRange.x - rowMarkerOffset },
×
NEW
2098
                    preventDefault: () => (canceled = true),
×
NEW
2099
                });
×
NEW
2100
                if (canceled) return;
×
NEW
2101
            }
×
2102

4✔
2103
            let cells = getCellsForSelection(patternRange, abortControllerRef.current.signal);
4✔
2104
            if (typeof cells !== "object") cells = await cells();
4!
2105

4✔
2106
            const pattern = cells;
4✔
2107

4✔
2108
            // loop through all cells in currentSelection.current.range
4✔
2109
            const editItemList: EditListItem[] = [];
4✔
2110
            for (let x = 0; x < currentRange.width; x++) {
4✔
2111
                for (let y = 0; y < currentRange.height; y++) {
4✔
2112
                    const cell: Item = [currentRange.x + x, currentRange.y + y];
15✔
2113
                    if (itemIsInRect(cell, patternRange)) continue;
15✔
2114
                    const patternCell = pattern[y % patternRange.height][x % patternRange.width];
11✔
2115
                    if (isInnerOnlyCell(patternCell) || !isReadWriteCell(patternCell)) continue;
15!
2116
                    editItemList.push({
11✔
2117
                        location: cell,
11✔
2118
                        value: { ...patternCell },
11✔
2119
                    });
11✔
2120
                }
11✔
2121
            }
4✔
2122
            mangledOnCellsEdited(editItemList);
4✔
2123

4✔
2124
            gridRef.current?.damage(
4✔
2125
                editItemList.map(c => ({
4✔
2126
                    cell: c.location,
11✔
2127
                }))
4✔
2128
            );
4✔
2129
        },
4✔
2130
        [getCellsForSelection, mangledOnCellsEdited, onFillPattern, rowMarkerOffset]
650✔
2131
    );
650✔
2132

650✔
2133
    const onMouseUp = React.useCallback(
650✔
2134
        (args: GridMouseEventArgs, isOutside: boolean) => {
650✔
2135
            const mouse = mouseState;
127✔
2136
            setMouseState(undefined);
127✔
2137
            setFillHighlightRegion(undefined);
127✔
2138
            setScrollDir(undefined);
127✔
2139
            isActivelyDraggingHeader.current = false;
127✔
2140

127✔
2141
            if (isOutside) return;
127✔
2142

126✔
2143
            if (
126✔
2144
                mouse?.fillHandle === true &&
127✔
2145
                gridSelection.current !== undefined &&
4✔
2146
                mouse.previousSelection?.current !== undefined
4✔
2147
            ) {
127✔
2148
                if (fillHighlightRegion === undefined) return;
4!
2149
                const newRange = {
4✔
2150
                    ...gridSelection,
4✔
2151
                    current: {
4✔
2152
                        ...gridSelection.current,
4✔
2153
                        range: combineRects(mouse.previousSelection.current.range, fillHighlightRegion),
4✔
2154
                    },
4✔
2155
                };
4✔
2156
                void fillPattern(mouse.previousSelection, newRange);
4✔
2157
                setGridSelection(newRange, true);
4✔
2158
                return;
4✔
2159
            }
4✔
2160

122✔
2161
            const [col, row] = args.location;
122✔
2162
            const [lastMouseDownCol, lastMouseDownRow] = lastMouseSelectLocation.current ?? [];
127✔
2163

127✔
2164
            const preventDefault = () => {
127✔
2165
                isPrevented.current = true;
×
UNCOV
2166
            };
×
2167

127✔
2168
            const handleMaybeClick = (a: GridMouseCellEventArgs): boolean => {
127✔
2169
                const isValidClick = a.isTouch || (lastMouseDownCol === col && lastMouseDownRow === row);
97✔
2170
                if (isValidClick) {
97✔
2171
                    onCellClicked?.([col - rowMarkerOffset, row], {
87✔
2172
                        ...a,
4✔
2173
                        preventDefault,
4✔
2174
                    });
4✔
2175
                }
87✔
2176
                if (a.button === 1) return !isPrevented.current;
97✔
2177
                if (!isPrevented.current) {
94✔
2178
                    const c = getMangledCellContent(args.location);
94✔
2179
                    const r = getCellRenderer(c);
94✔
2180
                    if (r !== undefined && r.onClick !== undefined && isValidClick) {
94✔
2181
                        const newVal = r.onClick({
20✔
2182
                            ...a,
20✔
2183
                            cell: c,
20✔
2184
                            posX: a.localEventX,
20✔
2185
                            posY: a.localEventY,
20✔
2186
                            bounds: a.bounds,
20✔
2187
                            theme: themeForCell(c, args.location),
20✔
2188
                            preventDefault,
20✔
2189
                        });
20✔
2190
                        if (newVal !== undefined && !isInnerOnlyCell(newVal) && isEditableGridCell(newVal)) {
20✔
2191
                            mangledOnCellsEdited([{ location: a.location, value: newVal }]);
4✔
2192
                            gridRef.current?.damage([
4✔
2193
                                {
4✔
2194
                                    cell: a.location,
4✔
2195
                                },
4✔
2196
                            ]);
4✔
2197
                        }
4✔
2198
                    }
20✔
2199
                    if (
94✔
2200
                        !isPrevented.current &&
94✔
2201
                        mouse?.previousSelection?.current?.cell !== undefined &&
94✔
2202
                        gridSelection.current !== undefined
20✔
2203
                    ) {
94✔
2204
                        const [selectedCol, selectedRow] = gridSelection.current.cell;
19✔
2205
                        const [prevCol, prevRow] = mouse.previousSelection.current.cell;
19✔
2206
                        if (col === selectedCol && col === prevCol && row === selectedRow && row === prevRow) {
19✔
2207
                            onCellActivated?.([col - rowMarkerOffset, row]);
3✔
2208
                            reselect(a.bounds, false);
3✔
2209
                            return true;
3✔
2210
                        }
3✔
2211
                    }
19✔
2212
                }
94✔
2213
                return false;
91✔
2214
            };
97✔
2215

127✔
2216
            const clickLocation = args.location[0] - rowMarkerOffset;
127✔
2217
            if (args.isTouch) {
127✔
2218
                const vr = visibleRegionRef.current;
4✔
2219
                const touchVr = touchDownArgs.current;
4✔
2220
                if (vr.x !== touchVr.x || vr.y !== touchVr.y) {
4!
UNCOV
2221
                    // we scrolled, abort
×
2222
                    return;
×
UNCOV
2223
                }
×
2224
                // take care of context menus first if long pressed item is already selected
4✔
2225
                if (args.isLongTouch === true) {
4!
NEW
2226
                    if (args.kind === "cell" && itemsAreEqual(gridSelection.current?.cell, args.location)) {
×
UNCOV
2227
                        onCellContextMenu?.([clickLocation, args.location[1]], {
×
UNCOV
2228
                            ...args,
×
UNCOV
2229
                            preventDefault,
×
UNCOV
2230
                        });
×
2231
                        return;
×
UNCOV
2232
                    } else if (args.kind === "header" && gridSelection.columns.hasIndex(col)) {
×
2233
                        onHeaderContextMenu?.(clickLocation, { ...args, preventDefault });
×
2234
                        return;
×
UNCOV
2235
                    } else if (args.kind === groupHeaderKind) {
×
UNCOV
2236
                        if (clickLocation < 0) {
×
2237
                            return;
×
UNCOV
2238
                        }
×
UNCOV
2239

×
2240
                        onGroupHeaderContextMenu?.(clickLocation, { ...args, preventDefault });
×
2241
                        return;
×
UNCOV
2242
                    }
×
UNCOV
2243
                }
×
2244
                if (args.kind === "cell") {
4✔
2245
                    // click that cell
2✔
2246
                    if (!handleMaybeClick(args)) {
2✔
2247
                        handleSelect(args);
2✔
2248
                    }
2✔
2249
                } else if (args.kind === groupHeaderKind) {
2✔
2250
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
1✔
2251
                } else {
1✔
2252
                    if (args.kind === headerKind) {
1✔
2253
                        onHeaderClicked?.(clickLocation, {
1✔
2254
                            ...args,
1✔
2255
                            preventDefault,
1✔
2256
                        });
1✔
2257
                    }
1✔
2258
                    handleSelect(args);
1✔
2259
                }
1✔
2260
                return;
4✔
2261
            }
4✔
2262

118✔
2263
            if (args.kind === "header") {
127✔
2264
                if (clickLocation < 0) {
16✔
2265
                    return;
3✔
2266
                }
3✔
2267

13✔
2268
                if (args.isEdge) {
16✔
2269
                    void normalSizeColumn(col);
2✔
2270
                } else if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
16✔
2271
                    onHeaderClicked?.(clickLocation, { ...args, preventDefault });
5✔
2272
                }
5✔
2273
            }
16✔
2274

115✔
2275
            if (args.kind === groupHeaderKind) {
127✔
2276
                if (clickLocation < 0) {
3!
2277
                    return;
×
UNCOV
2278
                }
×
2279

3✔
2280
                if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
3✔
2281
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
3!
2282
                    if (!isPrevented.current) {
3✔
2283
                        handleGroupHeaderSelection(args);
3✔
2284
                    }
3✔
2285
                }
3✔
2286
            }
3✔
2287

115✔
2288
            if (args.kind === "cell" && (args.button === 0 || args.button === 1)) {
127✔
2289
                handleMaybeClick(args);
95✔
2290
            }
95✔
2291

115✔
2292
            lastMouseSelectLocation.current = undefined;
115✔
2293
        },
127✔
2294
        [
650✔
2295
            mouseState,
650✔
2296
            gridSelection,
650✔
2297
            rowMarkerOffset,
650✔
2298
            fillHighlightRegion,
650✔
2299
            fillPattern,
650✔
2300
            setGridSelection,
650✔
2301
            onCellClicked,
650✔
2302
            getMangledCellContent,
650✔
2303
            getCellRenderer,
650✔
2304
            themeForCell,
650✔
2305
            mangledOnCellsEdited,
650✔
2306
            onCellActivated,
650✔
2307
            reselect,
650✔
2308
            onCellContextMenu,
650✔
2309
            onHeaderContextMenu,
650✔
2310
            onGroupHeaderContextMenu,
650✔
2311
            handleSelect,
650✔
2312
            onGroupHeaderClicked,
650✔
2313
            onHeaderClicked,
650✔
2314
            normalSizeColumn,
650✔
2315
            handleGroupHeaderSelection,
650✔
2316
        ]
650✔
2317
    );
650✔
2318

650✔
2319
    const onMouseMoveImpl = React.useCallback(
650✔
2320
        (args: GridMouseEventArgs) => {
650✔
2321
            const a: GridMouseEventArgs = {
38✔
2322
                ...args,
38✔
2323
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
38✔
2324
            };
38✔
2325
            onMouseMove?.(a);
38✔
2326
            setScrollDir(cv => {
38✔
2327
                if (isActivelyDraggingHeader.current) return [args.scrollEdge[0], 0];
38✔
2328
                if (args.scrollEdge[0] === cv?.[0] && args.scrollEdge[1] === cv[1]) return cv;
38!
2329
                return mouseState === undefined || (mouseDownData.current?.location[0] ?? 0) < rowMarkerOffset
36!
2330
                    ? undefined
13✔
2331
                    : args.scrollEdge;
14✔
2332
            });
38✔
2333
        },
38✔
2334
        [mouseState, onMouseMove, rowMarkerOffset]
650✔
2335
    );
650✔
2336

650✔
2337
    useAutoscroll(scrollDir, scrollRef);
650✔
2338

650✔
2339
    const onHeaderMenuClickInner = React.useCallback(
650✔
2340
        (col: number, screenPosition: Rectangle) => {
650✔
2341
            onHeaderMenuClick?.(col - rowMarkerOffset, screenPosition);
1✔
2342
        },
1✔
2343
        [onHeaderMenuClick, rowMarkerOffset]
650✔
2344
    );
650✔
2345

650✔
2346
    const currentCell = gridSelection?.current?.cell;
650✔
2347
    const onVisibleRegionChangedImpl = React.useCallback(
650✔
2348
        (
650✔
2349
            region: Rectangle,
136✔
2350
            clientWidth: number,
136✔
2351
            clientHeight: number,
136✔
2352
            rightElWidth: number,
136✔
2353
            tx: number,
136✔
2354
            ty: number
136✔
2355
        ) => {
136✔
2356
            hasJustScrolled.current = false;
136✔
2357
            let selected = currentCell;
136✔
2358
            if (selected !== undefined) {
136✔
2359
                selected = [selected[0] - rowMarkerOffset, selected[1]];
10✔
2360
            }
10✔
2361
            const newRegion = {
136✔
2362
                x: region.x - rowMarkerOffset,
136✔
2363
                y: region.y,
136✔
2364
                width: region.width,
136✔
2365
                height: showTrailingBlankRow && region.y + region.height >= rows ? region.height - 1 : region.height,
136✔
2366
                tx,
136✔
2367
                ty,
136✔
2368
                extras: {
136✔
2369
                    selected,
136✔
2370
                    freezeRegion:
136✔
2371
                        freezeColumns === 0
136✔
2372
                            ? undefined
136!
UNCOV
2373
                            : {
×
UNCOV
2374
                                  x: 0,
×
UNCOV
2375
                                  y: region.y,
×
UNCOV
2376
                                  width: freezeColumns,
×
UNCOV
2377
                                  height: region.height,
×
UNCOV
2378
                              },
×
2379
                },
136✔
2380
            };
136✔
2381
            visibleRegionRef.current = newRegion;
136✔
2382
            setVisibleRegion(newRegion);
136✔
2383
            setClientSize([clientWidth, clientHeight, rightElWidth]);
136✔
2384
            onVisibleRegionChanged?.(newRegion, newRegion.tx, newRegion.ty, newRegion.extras);
136!
2385
        },
136✔
2386
        [
650✔
2387
            currentCell,
650✔
2388
            rowMarkerOffset,
650✔
2389
            showTrailingBlankRow,
650✔
2390
            rows,
650✔
2391
            freezeColumns,
650✔
2392
            setVisibleRegion,
650✔
2393
            onVisibleRegionChanged,
650✔
2394
        ]
650✔
2395
    );
650✔
2396

650✔
2397
    const onColumnMovedImpl = whenDefined(
650✔
2398
        onColumnMoved,
650✔
2399
        React.useCallback(
650✔
2400
            (startIndex: number, endIndex: number) => {
650✔
2401
                onColumnMoved?.(startIndex - rowMarkerOffset, endIndex - rowMarkerOffset);
1✔
2402
                if (columnSelect !== "none") {
1✔
2403
                    setSelectedColumns(CompactSelection.fromSingleSelection(endIndex), undefined, true);
1✔
2404
                }
1✔
2405
            },
1✔
2406
            [columnSelect, onColumnMoved, rowMarkerOffset, setSelectedColumns]
650✔
2407
        )
650✔
2408
    );
650✔
2409

650✔
2410
    const isActivelyDragging = React.useRef(false);
650✔
2411
    const onDragStartImpl = React.useCallback(
650✔
2412
        (args: GridDragEventArgs) => {
650✔
2413
            if (args.location[0] === 0 && rowMarkerOffset > 0) {
1!
2414
                args.preventDefault();
×
2415
                return;
×
UNCOV
2416
            }
×
2417
            onDragStart?.({
1✔
2418
                ...args,
1✔
2419
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
1✔
2420
            });
1✔
2421

1✔
2422
            if (!args.defaultPrevented()) {
1✔
2423
                isActivelyDragging.current = true;
1✔
2424
            }
1✔
2425
            setMouseState(undefined);
1✔
2426
        },
1✔
2427
        [onDragStart, rowMarkerOffset]
650✔
2428
    );
650✔
2429

650✔
2430
    const onDragEnd = React.useCallback(() => {
650✔
2431
        isActivelyDragging.current = false;
×
2432
    }, []);
650✔
2433

650✔
2434
    const onItemHoveredImpl = React.useCallback(
650✔
2435
        (args: GridMouseEventArgs) => {
650✔
2436
            if (mouseDownData?.current?.button !== undefined && mouseDownData.current.button >= 1) return;
33✔
2437
            if (
32✔
2438
                mouseState !== undefined &&
32✔
2439
                mouseDownData.current?.location[0] === 0 &&
19✔
2440
                args.location[0] === 0 &&
3✔
2441
                rowMarkerOffset === 1 &&
3✔
2442
                rowSelect === "multi" &&
3✔
2443
                mouseState.previousSelection &&
2✔
2444
                !mouseState.previousSelection.rows.hasIndex(mouseDownData.current.location[1]) &&
2✔
2445
                gridSelection.rows.hasIndex(mouseDownData.current.location[1])
2✔
2446
            ) {
33✔
2447
                const start = Math.min(mouseDownData.current.location[1], args.location[1]);
2✔
2448
                const end = Math.max(mouseDownData.current.location[1], args.location[1]) + 1;
2✔
2449
                setSelectedRows(CompactSelection.fromSingleSelection([start, end]), undefined, false);
2✔
2450
            }
2✔
2451
            if (
32✔
2452
                mouseState !== undefined &&
32✔
2453
                gridSelection.current !== undefined &&
19✔
2454
                !isActivelyDragging.current &&
17✔
2455
                (rangeSelect === "rect" || rangeSelect === "multi-rect")
17✔
2456
            ) {
33✔
2457
                const [selectedCol, selectedRow] = gridSelection.current.cell;
11✔
2458
                // eslint-disable-next-line prefer-const
11✔
2459
                let [col, row] = args.location;
11✔
2460

11✔
2461
                if (row < 0) {
11✔
2462
                    row = visibleRegionRef.current.y;
1✔
2463
                }
1✔
2464

11✔
2465
                if (mouseState.fillHandle === true && mouseState.previousSelection?.current !== undefined) {
11✔
2466
                    const prevRange = mouseState.previousSelection.current.range;
5✔
2467
                    row = Math.min(row, lastRowSticky ? rows - 1 : rows);
5!
2468
                    const rect = getClosestRect(prevRange, col, row);
5✔
2469
                    setFillHighlightRegion(rect);
5✔
2470
                } else {
11✔
2471
                    const startedFromLastStickyRow = lastRowSticky && selectedRow === rows;
6✔
2472
                    if (startedFromLastStickyRow) return;
6!
2473

6✔
2474
                    const landedOnLastStickyRow = lastRowSticky && row === rows;
6✔
2475
                    if (landedOnLastStickyRow) {
6!
NEW
2476
                        if (args.kind === outOfBoundsKind) row--;
×
NEW
2477
                        else return;
×
NEW
2478
                    }
×
2479

6✔
2480
                    col = Math.max(col, rowMarkerOffset);
6✔
2481

6✔
2482
                    const deltaX = col - selectedCol;
6✔
2483
                    const deltaY = row - selectedRow;
6✔
2484

6✔
2485
                    const newRange: Rectangle = {
6✔
2486
                        x: deltaX >= 0 ? selectedCol : col,
6!
2487
                        y: deltaY >= 0 ? selectedRow : row,
6✔
2488
                        width: Math.abs(deltaX) + 1,
6✔
2489
                        height: Math.abs(deltaY) + 1,
6✔
2490
                    };
6✔
2491

6✔
2492
                    setCurrent(
6✔
2493
                        {
6✔
2494
                            ...gridSelection.current,
6✔
2495
                            range: newRange,
6✔
2496
                        },
6✔
2497
                        true,
6✔
2498
                        false,
6✔
2499
                        "drag"
6✔
2500
                    );
6✔
2501
                }
6✔
2502
            }
11✔
2503

32✔
2504
            onItemHovered?.({ ...args, location: [args.location[0] - rowMarkerOffset, args.location[1]] as any });
33✔
2505
        },
33✔
2506
        [
650✔
2507
            mouseState,
650✔
2508
            rowMarkerOffset,
650✔
2509
            rowSelect,
650✔
2510
            gridSelection,
650✔
2511
            rangeSelect,
650✔
2512
            onItemHovered,
650✔
2513
            setSelectedRows,
650✔
2514
            lastRowSticky,
650✔
2515
            rows,
650✔
2516
            setCurrent,
650✔
2517
        ]
650✔
2518
    );
650✔
2519

650✔
2520
    // 1 === move one
650✔
2521
    // 2 === move to end
650✔
2522
    const adjustSelection = React.useCallback(
650✔
2523
        (direction: [0 | 1 | -1 | 2 | -2, 0 | 1 | -1 | 2 | -2]) => {
650✔
2524
            if (gridSelection.current === undefined) return;
8!
2525

8✔
2526
            const [x, y] = direction;
8✔
2527
            const [col, row] = gridSelection.current.cell;
8✔
2528
            const old = gridSelection.current.range;
8✔
2529
            let left = old.x;
8✔
2530
            let right = old.x + old.width;
8✔
2531
            let top = old.y;
8✔
2532
            let bottom = old.y + old.height;
8✔
2533

8✔
2534
            // take care of vertical first in case new spans come in
8✔
2535
            if (y !== 0) {
8✔
2536
                switch (y) {
2✔
2537
                    case 2: {
2✔
2538
                        // go to end
1✔
2539
                        bottom = rows;
1✔
2540
                        top = row;
1✔
2541
                        scrollTo(0, bottom, "vertical");
1✔
2542

1✔
2543
                        break;
1✔
2544
                    }
1✔
2545
                    case -2: {
2!
UNCOV
2546
                        // go to start
×
2547
                        top = 0;
×
2548
                        bottom = row + 1;
×
2549
                        scrollTo(0, top, "vertical");
×
UNCOV
2550

×
2551
                        break;
×
UNCOV
2552
                    }
×
2553
                    case 1: {
2✔
2554
                        // motion down
1✔
2555
                        if (top < row) {
1!
2556
                            top++;
×
2557
                            scrollTo(0, top, "vertical");
×
2558
                        } else {
1✔
2559
                            bottom = Math.min(rows, bottom + 1);
1✔
2560
                            scrollTo(0, bottom, "vertical");
1✔
2561
                        }
1✔
2562

1✔
2563
                        break;
1✔
2564
                    }
1✔
2565
                    case -1: {
2!
UNCOV
2566
                        // motion up
×
UNCOV
2567
                        if (bottom > row + 1) {
×
2568
                            bottom--;
×
2569
                            scrollTo(0, bottom, "vertical");
×
UNCOV
2570
                        } else {
×
2571
                            top = Math.max(0, top - 1);
×
2572
                            scrollTo(0, top, "vertical");
×
UNCOV
2573
                        }
×
UNCOV
2574

×
2575
                        break;
×
UNCOV
2576
                    }
×
2577
                    default: {
2!
2578
                        assertNever(y);
×
UNCOV
2579
                    }
×
2580
                }
2✔
2581
            }
2✔
2582

8✔
2583
            if (x !== 0) {
8✔
2584
                if (x === 2) {
6✔
2585
                    right = mangledCols.length;
1✔
2586
                    left = col;
1✔
2587
                    scrollTo(right - 1 - rowMarkerOffset, 0, "horizontal");
1✔
2588
                } else if (x === -2) {
6!
2589
                    left = rowMarkerOffset;
×
2590
                    right = col + 1;
×
2591
                    scrollTo(left - rowMarkerOffset, 0, "horizontal");
×
2592
                } else {
5✔
2593
                    let disallowed: number[] = [];
5✔
2594
                    if (getCellsForSelection !== undefined) {
5✔
2595
                        const cells = getCellsForSelection(
5✔
2596
                            {
5✔
2597
                                x: left,
5✔
2598
                                y: top,
5✔
2599
                                width: right - left - rowMarkerOffset,
5✔
2600
                                height: bottom - top,
5✔
2601
                            },
5✔
2602
                            abortControllerRef.current.signal
5✔
2603
                        );
5✔
2604

5✔
2605
                        if (typeof cells === "object") {
5✔
2606
                            disallowed = getSpanStops(cells);
5✔
2607
                        }
5✔
2608
                    }
5✔
2609
                    if (x === 1) {
5✔
2610
                        // motion right
4✔
2611
                        let done = false;
4✔
2612
                        if (left < col) {
4!
UNCOV
2613
                            if (disallowed.length > 0) {
×
2614
                                const target = range(left + 1, col + 1).find(
×
2615
                                    n => !disallowed.includes(n - rowMarkerOffset)
×
UNCOV
2616
                                );
×
UNCOV
2617
                                if (target !== undefined) {
×
2618
                                    left = target;
×
2619
                                    done = true;
×
UNCOV
2620
                                }
×
UNCOV
2621
                            } else {
×
2622
                                left++;
×
2623
                                done = true;
×
UNCOV
2624
                            }
×
2625
                            if (done) scrollTo(left, 0, "horizontal");
×
UNCOV
2626
                        }
×
2627
                        if (!done) {
4✔
2628
                            right = Math.min(mangledCols.length, right + 1);
4✔
2629
                            scrollTo(right - 1 - rowMarkerOffset, 0, "horizontal");
4✔
2630
                        }
4✔
2631
                    } else if (x === -1) {
5✔
2632
                        // motion left
1✔
2633
                        let done = false;
1✔
2634
                        if (right > col + 1) {
1!
UNCOV
2635
                            if (disallowed.length > 0) {
×
2636
                                const target = range(right - 1, col, -1).find(
×
2637
                                    n => !disallowed.includes(n - rowMarkerOffset)
×
UNCOV
2638
                                );
×
UNCOV
2639
                                if (target !== undefined) {
×
2640
                                    right = target;
×
2641
                                    done = true;
×
UNCOV
2642
                                }
×
UNCOV
2643
                            } else {
×
2644
                                right--;
×
2645
                                done = true;
×
UNCOV
2646
                            }
×
2647
                            if (done) scrollTo(right - rowMarkerOffset, 0, "horizontal");
×
UNCOV
2648
                        }
×
2649
                        if (!done) {
1✔
2650
                            left = Math.max(rowMarkerOffset, left - 1);
1✔
2651
                            scrollTo(left - rowMarkerOffset, 0, "horizontal");
1✔
2652
                        }
1✔
2653
                    } else {
1!
2654
                        assertNever(x);
×
UNCOV
2655
                    }
×
2656
                }
5✔
2657
            }
6✔
2658

8✔
2659
            setCurrent(
8✔
2660
                {
8✔
2661
                    cell: gridSelection.current.cell,
8✔
2662
                    range: {
8✔
2663
                        x: left,
8✔
2664
                        y: top,
8✔
2665
                        width: right - left,
8✔
2666
                        height: bottom - top,
8✔
2667
                    },
8✔
2668
                },
8✔
2669
                true,
8✔
2670
                false,
8✔
2671
                "keyboard-select"
8✔
2672
            );
8✔
2673
        },
8✔
2674
        [getCellsForSelection, gridSelection, mangledCols.length, rowMarkerOffset, rows, scrollTo, setCurrent]
650✔
2675
    );
650✔
2676

650✔
2677
    const updateSelectedCell = React.useCallback(
650✔
2678
        (col: number, row: number, fromEditingTrailingRow: boolean, freeMove: boolean): boolean => {
650✔
2679
            const rowMax = mangledRows - (fromEditingTrailingRow ? 0 : 1);
53!
2680
            col = clamp(col, rowMarkerOffset, columns.length - 1 + rowMarkerOffset);
53✔
2681
            row = clamp(row, 0, rowMax);
53✔
2682

53✔
2683
            if (col === currentCell?.[0] && row === currentCell?.[1]) return false;
53✔
2684
            if (freeMove && gridSelection.current !== undefined) {
53✔
2685
                const newStack = [...gridSelection.current.rangeStack];
1✔
2686
                if (gridSelection.current.range.width > 1 || gridSelection.current.range.height > 1) {
1!
2687
                    newStack.push(gridSelection.current.range);
1✔
2688
                }
1✔
2689
                setGridSelection(
1✔
2690
                    {
1✔
2691
                        ...gridSelection,
1✔
2692
                        current: {
1✔
2693
                            cell: [col, row],
1✔
2694
                            range: { x: col, y: row, width: 1, height: 1 },
1✔
2695
                            rangeStack: newStack,
1✔
2696
                        },
1✔
2697
                    },
1✔
2698
                    true
1✔
2699
                );
1✔
2700
            } else {
53✔
2701
                setCurrent(
25✔
2702
                    {
25✔
2703
                        cell: [col, row],
25✔
2704
                        range: { x: col, y: row, width: 1, height: 1 },
25✔
2705
                    },
25✔
2706
                    true,
25✔
2707
                    false,
25✔
2708
                    "keyboard-nav"
25✔
2709
                );
25✔
2710
            }
25✔
2711

26✔
2712
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
53✔
2713
                lastSent.current = undefined;
2✔
2714
            }
2✔
2715

26✔
2716
            scrollTo(col - rowMarkerOffset, row);
26✔
2717

26✔
2718
            return true;
26✔
2719
        },
53✔
2720
        [
650✔
2721
            mangledRows,
650✔
2722
            rowMarkerOffset,
650✔
2723
            columns.length,
650✔
2724
            currentCell,
650✔
2725
            gridSelection,
650✔
2726
            scrollTo,
650✔
2727
            setGridSelection,
650✔
2728
            setCurrent,
650✔
2729
        ]
650✔
2730
    );
650✔
2731

650✔
2732
    const onFinishEditing = React.useCallback(
650✔
2733
        (newValue: GridCell | undefined, movement: readonly [-1 | 0 | 1, -1 | 0 | 1]) => {
650✔
2734
            if (overlay?.cell !== undefined && newValue !== undefined && isEditableGridCell(newValue)) {
7✔
2735
                mangledOnCellsEdited([{ location: overlay.cell, value: newValue }]);
4✔
2736
                window.requestAnimationFrame(() => {
4✔
2737
                    gridRef.current?.damage([
4✔
2738
                        {
4✔
2739
                            cell: overlay.cell,
4✔
2740
                        },
4✔
2741
                    ]);
4✔
2742
                });
4✔
2743
            }
4✔
2744
            focus(true);
7✔
2745
            setOverlay(undefined);
7✔
2746

7✔
2747
            const [movX, movY] = movement;
7✔
2748
            if (gridSelection.current !== undefined && (movX !== 0 || movY !== 0)) {
7✔
2749
                const isEditingTrailingRow =
3✔
2750
                    gridSelection.current.cell[1] === mangledRows - 1 && newValue !== undefined;
3!
2751
                updateSelectedCell(
3✔
2752
                    clamp(gridSelection.current.cell[0] + movX, 0, mangledCols.length - 1),
3✔
2753
                    clamp(gridSelection.current.cell[1] + movY, 0, mangledRows - 1),
3✔
2754
                    isEditingTrailingRow,
3✔
2755
                    false
3✔
2756
                );
3✔
2757
            }
3✔
2758
            onFinishedEditing?.(newValue, movement);
7✔
2759
        },
7✔
2760
        [
650✔
2761
            overlay?.cell,
650✔
2762
            focus,
650✔
2763
            gridSelection,
650✔
2764
            onFinishedEditing,
650✔
2765
            mangledOnCellsEdited,
650✔
2766
            mangledRows,
650✔
2767
            updateSelectedCell,
650✔
2768
            mangledCols.length,
650✔
2769
        ]
650✔
2770
    );
650✔
2771

650✔
2772
    const overlayID = React.useMemo(() => {
650✔
2773
        return `gdg-overlay-${idCounter++}`;
132✔
2774
    }, []);
650✔
2775

650✔
2776
    const deleteRange = React.useCallback(
650✔
2777
        (r: Rectangle) => {
650✔
2778
            focus();
8✔
2779
            const editList: EditListItem[] = [];
8✔
2780
            for (let x = r.x; x < r.x + r.width; x++) {
8✔
2781
                for (let y = r.y; y < r.y + r.height; y++) {
23✔
2782
                    const cellValue = getCellContent([x - rowMarkerOffset, y]);
1,066✔
2783
                    if (!cellValue.allowOverlay && cellValue.kind !== GridCellKind.Boolean) continue;
1,066✔
2784
                    let newVal: InnerGridCell | undefined = undefined;
1,042✔
2785
                    if (cellValue.kind === GridCellKind.Custom) {
1,066✔
2786
                        const toDelete = getCellRenderer(cellValue);
1✔
2787
                        const editor = toDelete?.provideEditor?.(cellValue);
1!
2788
                        if (toDelete?.onDelete !== undefined) {
1✔
2789
                            newVal = toDelete.onDelete(cellValue);
1✔
2790
                        } else if (isObjectEditorCallbackResult(editor)) {
1!
2791
                            newVal = editor?.deletedValue?.(cellValue);
×
UNCOV
2792
                        }
×
2793
                    } else if (
1✔
2794
                        (isEditableGridCell(cellValue) && cellValue.allowOverlay) ||
1,041✔
2795
                        cellValue.kind === GridCellKind.Boolean
1✔
2796
                    ) {
1,041✔
2797
                        const toDelete = getCellRenderer(cellValue);
1,041✔
2798
                        newVal = toDelete?.onDelete?.(cellValue);
1,041✔
2799
                    }
1,041✔
2800
                    if (newVal !== undefined && !isInnerOnlyCell(newVal) && isEditableGridCell(newVal)) {
1,066✔
2801
                        editList.push({ location: [x, y], value: newVal });
1,041✔
2802
                    }
1,041✔
2803
                }
1,066✔
2804
            }
23✔
2805
            mangledOnCellsEdited(editList);
8✔
2806
            gridRef.current?.damage(editList.map(x => ({ cell: x.location })));
8✔
2807
        },
8✔
2808
        [focus, getCellContent, getCellRenderer, mangledOnCellsEdited, rowMarkerOffset]
650✔
2809
    );
650✔
2810

650✔
2811
    const onKeyDown = React.useCallback(
650✔
2812
        (event: GridKeyEventArgs) => {
650✔
2813
            const fn = async () => {
61✔
2814
                let cancelled = false;
61✔
2815
                if (onKeyDownIn !== undefined) {
61✔
2816
                    onKeyDownIn({
1✔
2817
                        ...event,
1✔
2818
                        cancel: () => {
1✔
2819
                            cancelled = true;
×
UNCOV
2820
                        },
×
2821
                    });
1✔
2822
                }
1✔
2823

61✔
2824
                if (cancelled) return;
61!
2825

61✔
2826
                const cancel = () => {
61✔
2827
                    event.stopPropagation();
42✔
2828
                    event.preventDefault();
42✔
2829
                };
42✔
2830

61✔
2831
                const overlayOpen = overlay !== undefined;
61✔
2832
                const { altKey, shiftKey, metaKey, ctrlKey, key, bounds } = event;
61✔
2833
                const isOSX = browserIsOSX.value;
61✔
2834
                const isPrimaryKey = isOSX ? metaKey : ctrlKey;
61!
2835
                const isDeleteKey = key === "Delete" || (isOSX && key === "Backspace");
61!
2836
                const vr = visibleRegionRef.current;
61✔
2837
                const selectedColumns = gridSelection.columns;
61✔
2838
                const selectedRows = gridSelection.rows;
61✔
2839

61✔
2840
                if (key === "Escape") {
61✔
2841
                    if (overlayOpen) {
4✔
2842
                        setOverlay(undefined);
2✔
2843
                    } else if (keybindings.clear) {
2✔
2844
                        setGridSelection(emptyGridSelection, false);
2✔
2845
                        onSelectionCleared?.();
2!
2846
                    }
2✔
2847
                    return;
4✔
2848
                } else if (isHotkey("primary+a", event) && keybindings.selectAll) {
61✔
2849
                    if (!overlayOpen) {
1✔
2850
                        setGridSelection(
1✔
2851
                            {
1✔
2852
                                columns: CompactSelection.empty(),
1✔
2853
                                rows: CompactSelection.empty(),
1✔
2854
                                current: {
1✔
2855
                                    cell: gridSelection.current?.cell ?? [rowMarkerOffset, 0],
1!
2856
                                    range: {
1✔
2857
                                        x: rowMarkerOffset,
1✔
2858
                                        y: 0,
1✔
2859
                                        width: columnsIn.length,
1✔
2860
                                        height: rows,
1✔
2861
                                    },
1✔
2862
                                    rangeStack: [],
1✔
2863
                                },
1✔
2864
                            },
1✔
2865
                            false
1✔
2866
                        );
1✔
2867
                    } else {
1!
2868
                        const el = document.getElementById(overlayID);
×
UNCOV
2869
                        if (el !== null) {
×
2870
                            const s = window.getSelection();
×
2871
                            const r = document.createRange();
×
2872
                            r.selectNodeContents(el);
×
2873
                            s?.removeAllRanges();
×
2874
                            s?.addRange(r);
×
UNCOV
2875
                        }
×
UNCOV
2876
                    }
×
2877
                    cancel();
1✔
2878
                    return;
1✔
2879
                } else if (isHotkey("primary+f", event) && keybindings.search) {
57!
2880
                    cancel();
×
2881
                    searchInputRef?.current?.focus({ preventScroll: true });
×
2882
                    setShowSearchInner(true);
×
UNCOV
2883
                }
✔
2884

56✔
2885
                if (isDeleteKey) {
61✔
2886
                    const callbackResult = onDelete?.(gridSelection) ?? true;
8✔
2887
                    cancel();
8✔
2888
                    if (callbackResult !== false) {
8✔
2889
                        const toDelete = callbackResult === true ? gridSelection : callbackResult;
8✔
2890

8✔
2891
                        // delete order:
8✔
2892
                        // 1) primary range
8✔
2893
                        // 2) secondary ranges
8✔
2894
                        // 3) columns
8✔
2895
                        // 4) rows
8✔
2896

8✔
2897
                        if (toDelete.current !== undefined) {
8✔
2898
                            deleteRange(toDelete.current.range);
5✔
2899
                            for (const r of toDelete.current.rangeStack) {
5!
2900
                                deleteRange(r);
×
UNCOV
2901
                            }
×
2902
                        }
5✔
2903

8✔
2904
                        for (const r of toDelete.rows) {
8✔
2905
                            deleteRange({
1✔
2906
                                x: rowMarkerOffset,
1✔
2907
                                y: r,
1✔
2908
                                width: mangledCols.length - rowMarkerOffset,
1✔
2909
                                height: 1,
1✔
2910
                            });
1✔
2911
                        }
1✔
2912

8✔
2913
                        for (const col of toDelete.columns) {
8✔
2914
                            deleteRange({
1✔
2915
                                x: col,
1✔
2916
                                y: 0,
1✔
2917
                                width: 1,
1✔
2918
                                height: rows,
1✔
2919
                            });
1✔
2920
                        }
1✔
2921
                    }
8✔
2922
                    return;
8✔
2923
                }
8✔
2924

48✔
2925
                if (gridSelection.current === undefined) return;
48✔
2926
                let [col, row] = gridSelection.current.cell;
45✔
2927
                let freeMove = false;
45✔
2928

45✔
2929
                if (keybindings.selectColumn && isHotkey("ctrl+ ", event) && columnSelect !== "none") {
61✔
2930
                    if (selectedColumns.hasIndex(col)) {
2!
2931
                        setSelectedColumns(selectedColumns.remove(col), undefined, true);
×
2932
                    } else {
2✔
2933
                        if (columnSelect === "single") {
2!
2934
                            setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, true);
×
2935
                        } else {
2✔
2936
                            setSelectedColumns(undefined, col, true);
2✔
2937
                        }
2✔
2938
                    }
2✔
2939
                } else if (keybindings.selectRow && isHotkey("shift+ ", event) && rowSelect !== "none") {
61✔
2940
                    if (selectedRows.hasIndex(row)) {
2!
2941
                        setSelectedRows(selectedRows.remove(row), undefined, true);
×
2942
                    } else {
2✔
2943
                        if (rowSelect === "single") {
2!
2944
                            setSelectedRows(CompactSelection.fromSingleSelection(row), undefined, true);
×
2945
                        } else {
2✔
2946
                            setSelectedRows(undefined, row, true);
2✔
2947
                        }
2✔
2948
                    }
2✔
2949
                } else if (
2✔
2950
                    (isHotkey("Enter", event) || isHotkey(" ", event) || isHotkey("shift+Enter", event)) &&
41✔
2951
                    bounds !== undefined
8✔
2952
                ) {
41✔
2953
                    if (overlayOpen) {
8✔
2954
                        setOverlay(undefined);
2✔
2955
                        if (isHotkey("Enter", event)) {
2✔
2956
                            row++;
2✔
2957
                        } else if (isHotkey("shift+Enter", event)) {
2!
2958
                            row--;
×
UNCOV
2959
                        }
×
2960
                    } else if (row === rows && showTrailingBlankRow) {
8!
2961
                        window.setTimeout(() => {
×
2962
                            const customTargetColumn = getCustomNewRowTargetColumn(col);
×
2963
                            void appendRow(customTargetColumn ?? col);
×
UNCOV
2964
                        }, 0);
×
2965
                    } else {
6✔
2966
                        onCellActivated?.([col - rowMarkerOffset, row]);
6✔
2967
                        reselect(bounds, true);
6✔
2968
                        cancel();
6✔
2969
                    }
6✔
2970
                } else if (
8✔
2971
                    keybindings.downFill &&
33✔
2972
                    isHotkey("primary+_68", event) &&
1✔
2973
                    gridSelection.current.range.height > 1
1✔
2974
                ) {
33✔
2975
                    // ctrl/cmd + d
1✔
2976
                    fillDown(false);
1✔
2977
                    cancel();
1✔
2978
                } else if (
1✔
2979
                    keybindings.rightFill &&
32✔
2980
                    isHotkey("primary+_82", event) &&
1✔
2981
                    gridSelection.current.range.width > 1
1✔
2982
                ) {
32✔
2983
                    // ctrl/cmd + r
1✔
2984
                    const editList: EditListItem[] = [];
1✔
2985
                    const r = gridSelection.current.range;
1✔
2986
                    for (let y = 0; y < r.height; y++) {
1✔
2987
                        const fillRow = y + r.y;
5✔
2988
                        const fillVal = getMangledCellContent([r.x, fillRow]);
5✔
2989
                        if (isInnerOnlyCell(fillVal) || !isReadWriteCell(fillVal)) continue;
5!
2990
                        for (let x = 1; x < r.width; x++) {
5✔
2991
                            const fillCol = x + r.x;
5✔
2992
                            const target = [fillCol, fillRow] as const;
5✔
2993
                            editList.push({
5✔
2994
                                location: target,
5✔
2995
                                value: { ...fillVal },
5✔
2996
                            });
5✔
2997
                        }
5✔
2998
                    }
5✔
2999
                    mangledOnCellsEdited(editList);
1✔
3000
                    gridRef.current?.damage(
1✔
3001
                        editList.map(c => ({
1✔
3002
                            cell: c.location,
5✔
3003
                        }))
1✔
3004
                    );
1✔
3005
                    cancel();
1✔
3006
                } else if (keybindings.pageDown && isHotkey("PageDown", event)) {
32!
3007
                    row += Math.max(1, visibleRegionRef.current.height - 4); // partial cell accounting
×
3008
                    cancel();
×
3009
                } else if (keybindings.pageUp && isHotkey("PageUp", event)) {
31!
3010
                    row -= Math.max(1, visibleRegionRef.current.height - 4); // partial cell accounting
×
3011
                    cancel();
×
3012
                } else if (keybindings.first && isHotkey("primary+Home", event)) {
31!
3013
                    setOverlay(undefined);
×
3014
                    row = 0;
×
3015
                    col = 0;
×
3016
                } else if (keybindings.last && isHotkey("primary+End", event)) {
31!
3017
                    setOverlay(undefined);
×
3018
                    row = Number.MAX_SAFE_INTEGER;
×
3019
                    col = Number.MAX_SAFE_INTEGER;
×
3020
                } else if (keybindings.first && isHotkey("primary+shift+Home", event)) {
31!
3021
                    setOverlay(undefined);
×
3022
                    adjustSelection([-2, -2]);
×
3023
                } else if (keybindings.last && isHotkey("primary+shift+End", event)) {
31!
3024
                    setOverlay(undefined);
×
3025
                    adjustSelection([2, 2]);
×
UNCOV
3026
                    // eslint-disable-next-line unicorn/prefer-switch
×
3027
                } else if (key === "ArrowDown") {
31✔
3028
                    if (ctrlKey && altKey) {
8!
3029
                        return;
×
UNCOV
3030
                    }
×
3031
                    setOverlay(undefined);
8✔
3032
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
8!
3033
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
2✔
3034
                        adjustSelection([0, isPrimaryKey && !altKey ? 2 : 1]);
2✔
3035
                    } else {
8✔
3036
                        if (altKey && !isPrimaryKey) {
6!
3037
                            freeMove = true;
×
UNCOV
3038
                        }
×
3039
                        if (isPrimaryKey && !altKey) {
6✔
3040
                            row = rows - 1;
1✔
3041
                        } else {
6✔
3042
                            row += 1;
5✔
3043
                        }
5✔
3044
                    }
6✔
3045
                } else if (key === "ArrowUp" || key === "Home") {
31✔
3046
                    const asPrimary = key === "Home" || isPrimaryKey;
2✔
3047
                    setOverlay(undefined);
2✔
3048
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
2!
UNCOV
3049
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
×
3050
                        adjustSelection([0, asPrimary && !altKey ? -2 : -1]);
×
3051
                    } else {
2✔
3052
                        if (altKey && !asPrimary) {
2!
3053
                            freeMove = true;
×
UNCOV
3054
                        }
×
3055
                        row += asPrimary && !altKey ? Number.MIN_SAFE_INTEGER : -1;
2✔
3056
                    }
2✔
3057
                } else if (key === "ArrowRight" || key === "End") {
23✔
3058
                    const asPrimary = key === "End" || isPrimaryKey;
8✔
3059
                    setOverlay(undefined);
8✔
3060
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
8!
3061
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
5✔
3062
                        adjustSelection([asPrimary && !altKey ? 2 : 1, 0]);
5✔
3063
                    } else {
8✔
3064
                        if (altKey && !asPrimary) {
3!
3065
                            freeMove = true;
×
UNCOV
3066
                        }
×
3067
                        col += asPrimary && !altKey ? Number.MAX_SAFE_INTEGER : 1;
3✔
3068
                    }
3✔
3069
                } else if (key === "ArrowLeft") {
21✔
3070
                    setOverlay(undefined);
4✔
3071
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
4!
3072
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
1✔
3073
                        adjustSelection([isPrimaryKey && !altKey ? -2 : -1, 0]);
1!
3074
                    } else {
4✔
3075
                        if (altKey && !isPrimaryKey) {
3✔
3076
                            freeMove = true;
1✔
3077
                        }
1✔
3078
                        col += isPrimaryKey && !altKey ? Number.MIN_SAFE_INTEGER : -1;
3✔
3079
                    }
3✔
3080
                } else if (key === "Tab") {
13✔
3081
                    setOverlay(undefined);
2✔
3082
                    if (shiftKey) {
2✔
3083
                        col--;
1✔
3084
                    } else {
1✔
3085
                        col++;
1✔
3086
                    }
1✔
3087
                } else if (
2✔
3088
                    !metaKey &&
7✔
3089
                    !ctrlKey &&
7✔
3090
                    gridSelection.current !== undefined &&
7✔
3091
                    key.length === 1 &&
7✔
3092
                    /[ -~]/g.test(key) &&
7✔
3093
                    bounds !== undefined &&
7✔
3094
                    isReadWriteCell(getCellContent([col - rowMarkerOffset, Math.max(0, Math.min(row, rows - 1))]))
7✔
3095
                ) {
7✔
3096
                    if (
7✔
3097
                        (!lastRowSticky || row !== rows) &&
7✔
3098
                        (vr.y > row || row > vr.y + vr.height || vr.x > col || col > vr.x + vr.width)
7✔
3099
                    ) {
7!
3100
                        return;
×
UNCOV
3101
                    }
×
3102
                    reselect(bounds, true, key);
7✔
3103
                    cancel();
7✔
3104
                }
7✔
3105

45✔
3106
                const moved = updateSelectedCell(col, row, false, freeMove);
45✔
3107
                if (moved) {
61✔
3108
                    cancel();
18✔
3109
                }
18✔
3110
            };
61✔
3111
            void fn();
61✔
3112
        },
61✔
3113
        [
650✔
3114
            onKeyDownIn,
650✔
3115
            deleteRange,
650✔
3116
            overlay,
650✔
3117
            gridSelection,
650✔
3118
            keybindings.selectAll,
650✔
3119
            keybindings.search,
650✔
3120
            keybindings.selectColumn,
650✔
3121
            keybindings.selectRow,
650✔
3122
            keybindings.downFill,
650✔
3123
            keybindings.rightFill,
650✔
3124
            keybindings.pageDown,
650✔
3125
            keybindings.pageUp,
650✔
3126
            keybindings.first,
650✔
3127
            keybindings.last,
650✔
3128
            keybindings.clear,
650✔
3129
            columnSelect,
650✔
3130
            rowSelect,
650✔
3131
            getCellContent,
650✔
3132
            rowMarkerOffset,
650✔
3133
            updateSelectedCell,
650✔
3134
            setGridSelection,
650✔
3135
            onSelectionCleared,
650✔
3136
            columnsIn.length,
650✔
3137
            rows,
650✔
3138
            overlayID,
650✔
3139
            mangledOnCellsEdited,
650✔
3140
            onDelete,
650✔
3141
            mangledCols.length,
650✔
3142
            setSelectedColumns,
650✔
3143
            setSelectedRows,
650✔
3144
            showTrailingBlankRow,
650✔
3145
            getCustomNewRowTargetColumn,
650✔
3146
            appendRow,
650✔
3147
            onCellActivated,
650✔
3148
            reselect,
650✔
3149
            fillDown,
650✔
3150
            getMangledCellContent,
650✔
3151
            adjustSelection,
650✔
3152
            rangeSelect,
650✔
3153
            lastRowSticky,
650✔
3154
        ]
650✔
3155
    );
650✔
3156

650✔
3157
    const onContextMenu = React.useCallback(
650✔
3158
        (args: GridMouseEventArgs, preventDefault: () => void) => {
650✔
3159
            const adjustedCol = args.location[0] - rowMarkerOffset;
7✔
3160
            if (args.kind === "header") {
7!
3161
                onHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
UNCOV
3162
            }
×
3163

7✔
3164
            if (args.kind === groupHeaderKind) {
7!
UNCOV
3165
                if (adjustedCol < 0) {
×
3166
                    return;
×
UNCOV
3167
                }
×
3168
                onGroupHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
UNCOV
3169
            }
×
3170

7✔
3171
            if (args.kind === "cell") {
7✔
3172
                const [col, row] = args.location;
7✔
3173
                onCellContextMenu?.([adjustedCol, row], {
7✔
3174
                    ...args,
7✔
3175
                    preventDefault,
7✔
3176
                });
7✔
3177

7✔
3178
                if (!gridSelectionHasItem(gridSelection, args.location)) {
7✔
3179
                    updateSelectedCell(col, row, false, false);
3✔
3180
                }
3✔
3181
            }
7✔
3182
        },
7✔
3183
        [
650✔
3184
            gridSelection,
650✔
3185
            onCellContextMenu,
650✔
3186
            onGroupHeaderContextMenu,
650✔
3187
            onHeaderContextMenu,
650✔
3188
            rowMarkerOffset,
650✔
3189
            updateSelectedCell,
650✔
3190
        ]
650✔
3191
    );
650✔
3192

650✔
3193
    const onPasteInternal = React.useCallback(
650✔
3194
        async (e?: ClipboardEvent) => {
650✔
3195
            if (!keybindings.paste) return;
6!
3196
            function pasteToCell(
6✔
3197
                inner: InnerGridCell,
51✔
3198
                target: Item,
51✔
3199
                rawValue: string | boolean | string[] | number | boolean | BooleanEmpty | BooleanIndeterminate,
51✔
3200
                formatted?: string | string[]
51✔
3201
            ): EditListItem | undefined {
51✔
3202
                const stringifiedRawValue =
51✔
3203
                    typeof rawValue === "object" ? rawValue?.join("\n") ?? "" : rawValue?.toString() ?? "";
51!
3204

51✔
3205
                if (!isInnerOnlyCell(inner) && isReadWriteCell(inner) && inner.readonly !== true) {
51✔
3206
                    const coerced = coercePasteValue?.(stringifiedRawValue, inner);
51!
3207
                    if (coerced !== undefined && isEditableGridCell(coerced)) {
51!
UNCOV
3208
                        if (process.env.NODE_ENV !== "production" && coerced.kind !== inner.kind) {
×
UNCOV
3209
                            // eslint-disable-next-line no-console
×
3210
                            console.warn("Coercion should not change cell kind.");
×
UNCOV
3211
                        }
×
3212
                        return {
×
UNCOV
3213
                            location: target,
×
UNCOV
3214
                            value: coerced,
×
UNCOV
3215
                        };
×
UNCOV
3216
                    }
×
3217
                    const r = getCellRenderer(inner);
51✔
3218
                    if (r === undefined) return undefined;
51!
3219
                    if (r.kind === GridCellKind.Custom) {
51✔
3220
                        assert(inner.kind === GridCellKind.Custom);
1✔
3221
                        const newVal = (r as unknown as CustomRenderer<CustomCell<any>>).onPaste?.(
1✔
3222
                            stringifiedRawValue,
1✔
3223
                            inner.data
1✔
3224
                        );
1✔
3225
                        if (newVal === undefined) return undefined;
1!
3226
                        return {
×
UNCOV
3227
                            location: target,
×
UNCOV
3228
                            value: {
×
UNCOV
3229
                                ...inner,
×
UNCOV
3230
                                data: newVal,
×
UNCOV
3231
                            },
×
UNCOV
3232
                        };
×
3233
                    } else {
51✔
3234
                        const newVal = r.onPaste?.(stringifiedRawValue, inner, {
50✔
3235
                            formatted,
50✔
3236
                            formattedString: typeof formatted === "string" ? formatted : formatted?.join("\n"),
50!
3237
                            rawValue,
50✔
3238
                        });
50✔
3239
                        if (newVal === undefined) return undefined;
50✔
3240
                        assert(newVal.kind === inner.kind);
36✔
3241
                        return {
36✔
3242
                            location: target,
36✔
3243
                            value: newVal,
36✔
3244
                        };
36✔
3245
                    }
36✔
3246
                }
51!
3247
                return undefined;
×
3248
            }
51✔
3249

6✔
3250
            const selectedColumns = gridSelection.columns;
6✔
3251
            const selectedRows = gridSelection.rows;
6✔
3252
            const focused =
6✔
3253
                scrollRef.current?.contains(document.activeElement) === true ||
6✔
3254
                canvasRef.current?.contains(document.activeElement) === true;
6✔
3255

6✔
3256
            let target = gridSelection.current?.cell;
6✔
3257
            if (target === undefined && selectedColumns.length === 1) {
6!
3258
                target = [selectedColumns.first() ?? 0, 0];
×
UNCOV
3259
            }
×
3260
            if (target === undefined && selectedRows.length === 1) {
6!
3261
                target = [rowMarkerOffset, selectedRows.first() ?? 0];
×
UNCOV
3262
            }
×
3263

6✔
3264
            if (focused && target !== undefined) {
6✔
3265
                let data: CopyBuffer | undefined;
5✔
3266
                let text: string | undefined;
5✔
3267

5✔
3268
                const textPlain = "text/plain";
5✔
3269
                const textHtml = "text/html";
5✔
3270

5✔
3271
                if (navigator.clipboard.read !== undefined) {
5!
3272
                    const clipboardContent = await navigator.clipboard.read();
×
UNCOV
3273

×
UNCOV
3274
                    for (const item of clipboardContent) {
×
UNCOV
3275
                        if (item.types.includes(textHtml)) {
×
3276
                            const htmlBlob = await item.getType(textHtml);
×
3277
                            const html = await htmlBlob.text();
×
3278
                            const decoded = decodeHTML(html);
×
UNCOV
3279
                            if (decoded !== undefined) {
×
3280
                                data = decoded;
×
3281
                                break;
×
UNCOV
3282
                            }
×
UNCOV
3283
                        }
×
UNCOV
3284
                        if (item.types.includes(textPlain)) {
×
UNCOV
3285
                            // eslint-disable-next-line unicorn/no-await-expression-member
×
3286
                            text = await (await item.getType(textPlain)).text();
×
UNCOV
3287
                        }
×
UNCOV
3288
                    }
×
3289
                } else if (navigator.clipboard.readText !== undefined) {
5✔
3290
                    text = await navigator.clipboard.readText();
5✔
3291
                } else if (e !== undefined && e?.clipboardData !== null) {
5!
UNCOV
3292
                    if (e.clipboardData.types.includes(textHtml)) {
×
3293
                        const html = e.clipboardData.getData(textHtml);
×
3294
                        data = decodeHTML(html);
×
UNCOV
3295
                    }
×
UNCOV
3296
                    if (data === undefined && e.clipboardData.types.includes(textPlain)) {
×
3297
                        text = e.clipboardData.getData(textPlain);
×
UNCOV
3298
                    }
×
UNCOV
3299
                } else {
×
3300
                    return; // I didn't want to read that paste value anyway
×
UNCOV
3301
                }
×
3302

5✔
3303
                const [gridCol, gridRow] = target;
5✔
3304

5✔
3305
                const editList: EditListItem[] = [];
5✔
3306
                do {
5✔
3307
                    if (onPaste === undefined) {
5✔
3308
                        const cellData = getMangledCellContent(target);
2✔
3309
                        const rawValue = text ?? data?.map(r => r.map(cb => cb.rawValue).join("\t")).join("\t") ?? "";
2!
3310
                        const newVal = pasteToCell(cellData, target, rawValue, undefined);
2✔
3311
                        if (newVal !== undefined) {
2✔
3312
                            editList.push(newVal);
1✔
3313
                        }
1✔
3314
                        break;
2✔
3315
                    }
2✔
3316

3✔
3317
                    if (data === undefined) {
3✔
3318
                        if (text === undefined) return;
3!
3319
                        data = unquote(text);
3✔
3320
                    }
3✔
3321

3✔
3322
                    if (
3✔
3323
                        onPaste === false ||
3✔
3324
                        (typeof onPaste === "function" &&
3✔
3325
                            onPaste?.(
2✔
3326
                                [target[0] - rowMarkerOffset, target[1]],
2✔
3327
                                data.map(r => r.map(cb => cb.rawValue?.toString() ?? ""))
2!
3328
                            ) !== true)
2✔
3329
                    ) {
5!
3330
                        return;
×
UNCOV
3331
                    }
✔
3332

3✔
3333
                    for (const [row, dataRow] of data.entries()) {
5✔
3334
                        if (row + gridRow >= rows) break;
21!
3335
                        for (const [col, dataItem] of dataRow.entries()) {
21✔
3336
                            const index = [col + gridCol, row + gridRow] as const;
63✔
3337
                            const [writeCol, writeRow] = index;
63✔
3338
                            if (writeCol >= mangledCols.length) continue;
63✔
3339
                            if (writeRow >= mangledRows) continue;
49!
3340
                            const cellData = getMangledCellContent(index);
49✔
3341
                            const newVal = pasteToCell(cellData, index, dataItem.rawValue, dataItem.formatted);
49✔
3342
                            if (newVal !== undefined) {
63✔
3343
                                editList.push(newVal);
35✔
3344
                            }
35✔
3345
                        }
63✔
3346
                    }
21✔
3347
                    // eslint-disable-next-line no-constant-condition
3✔
3348
                } while (false);
5✔
3349

5✔
3350
                mangledOnCellsEdited(editList);
5✔
3351

5✔
3352
                gridRef.current?.damage(
5✔
3353
                    editList.map(c => ({
5✔
3354
                        cell: c.location,
36✔
3355
                    }))
5✔
3356
                );
5✔
3357
            }
5✔
3358
        },
6✔
3359
        [
650✔
3360
            coercePasteValue,
650✔
3361
            getCellRenderer,
650✔
3362
            getMangledCellContent,
650✔
3363
            gridSelection,
650✔
3364
            keybindings.paste,
650✔
3365
            mangledCols.length,
650✔
3366
            mangledOnCellsEdited,
650✔
3367
            mangledRows,
650✔
3368
            onPaste,
650✔
3369
            rowMarkerOffset,
650✔
3370
            rows,
650✔
3371
        ]
650✔
3372
    );
650✔
3373

650✔
3374
    useEventListener("paste", onPasteInternal, safeWindow, false, true);
650✔
3375

650✔
3376
    // While this function is async, we deeply prefer not to await if we don't have to. This will lead to unpacking
650✔
3377
    // promises in rather awkward ways when possible to avoid awaiting. We have to use fallback copy mechanisms when
650✔
3378
    // an await has happened.
650✔
3379
    const onCopy = React.useCallback(
650✔
3380
        async (e?: ClipboardEvent, ignoreFocus?: boolean) => {
650✔
3381
            if (!keybindings.copy) return;
6!
3382
            const focused =
6✔
3383
                ignoreFocus === true ||
6✔
3384
                scrollRef.current?.contains(document.activeElement) === true ||
5✔
3385
                canvasRef.current?.contains(document.activeElement) === true;
5✔
3386

6✔
3387
            const selectedColumns = gridSelection.columns;
6✔
3388
            const selectedRows = gridSelection.rows;
6✔
3389

6✔
3390
            const copyToClipboardWithHeaders = (
6✔
3391
                cells: readonly (readonly GridCell[])[],
5✔
3392
                columnIndexes: readonly number[]
5✔
3393
            ) => {
5✔
3394
                if (!copyHeaders) {
5✔
3395
                    copyToClipboard(cells, columnIndexes, e);
5✔
3396
                } else {
5!
3397
                    const headers = columnIndexes.map(index => ({
×
UNCOV
3398
                        kind: GridCellKind.Text,
×
UNCOV
3399
                        data: columnsIn[index].title,
×
UNCOV
3400
                        displayData: columnsIn[index].title,
×
UNCOV
3401
                        allowOverlay: false,
×
UNCOV
3402
                    })) as GridCell[];
×
3403
                    copyToClipboard([headers, ...cells], columnIndexes, e);
×
UNCOV
3404
                }
×
3405
            };
5✔
3406

6✔
3407
            if (focused && getCellsForSelection !== undefined) {
6✔
3408
                if (gridSelection.current !== undefined) {
6✔
3409
                    let thunk = getCellsForSelection(gridSelection.current.range, abortControllerRef.current.signal);
3✔
3410
                    if (typeof thunk !== "object") {
3!
3411
                        thunk = await thunk();
×
UNCOV
3412
                    }
×
3413
                    copyToClipboardWithHeaders(
3✔
3414
                        thunk,
3✔
3415
                        range(
3✔
3416
                            gridSelection.current.range.x - rowMarkerOffset,
3✔
3417
                            gridSelection.current.range.x + gridSelection.current.range.width - rowMarkerOffset
3✔
3418
                        )
3✔
3419
                    );
3✔
3420
                } else if (selectedRows !== undefined && selectedRows.length > 0) {
3✔
3421
                    const toCopy = [...selectedRows];
1✔
3422
                    const cells = toCopy.map(rowIndex => {
1✔
3423
                        const thunk = getCellsForSelection(
1✔
3424
                            {
1✔
3425
                                x: rowMarkerOffset,
1✔
3426
                                y: rowIndex,
1✔
3427
                                width: columnsIn.length,
1✔
3428
                                height: 1,
1✔
3429
                            },
1✔
3430
                            abortControllerRef.current.signal
1✔
3431
                        );
1✔
3432
                        if (typeof thunk === "object") {
1✔
3433
                            return thunk[0];
1✔
3434
                        }
1!
3435
                        return thunk().then(v => v[0]);
×
3436
                    });
1✔
3437
                    if (cells.some(x => x instanceof Promise)) {
1!
3438
                        const settled = await Promise.all(cells);
×
3439
                        copyToClipboardWithHeaders(settled, range(columnsIn.length));
×
3440
                    } else {
1✔
3441
                        copyToClipboardWithHeaders(cells as (readonly GridCell[])[], range(columnsIn.length));
1✔
3442
                    }
1✔
3443
                } else if (selectedColumns.length > 0) {
3✔
3444
                    const results: (readonly (readonly GridCell[])[])[] = [];
1✔
3445
                    const cols: number[] = [];
1✔
3446
                    for (const col of selectedColumns) {
1✔
3447
                        let thunk = getCellsForSelection(
3✔
3448
                            {
3✔
3449
                                x: col,
3✔
3450
                                y: 0,
3✔
3451
                                width: 1,
3✔
3452
                                height: rows,
3✔
3453
                            },
3✔
3454
                            abortControllerRef.current.signal
3✔
3455
                        );
3✔
3456
                        if (typeof thunk !== "object") {
3!
3457
                            thunk = await thunk();
×
UNCOV
3458
                        }
×
3459
                        results.push(thunk);
3✔
3460
                        cols.push(col - rowMarkerOffset);
3✔
3461
                    }
3✔
3462
                    if (results.length === 1) {
1!
3463
                        copyToClipboardWithHeaders(results[0], cols);
×
3464
                    } else {
1✔
3465
                        // FIXME: this is dumb
1✔
3466
                        const toCopy = results.reduce((pv, cv) => pv.map((row, index) => [...row, ...cv[index]]));
1✔
3467
                        copyToClipboardWithHeaders(toCopy, cols);
1✔
3468
                    }
1✔
3469
                }
1✔
3470
            }
6✔
3471
        },
6✔
3472
        [columnsIn, getCellsForSelection, gridSelection, keybindings.copy, rowMarkerOffset, rows, copyHeaders]
650✔
3473
    );
650✔
3474

650✔
3475
    useEventListener("copy", onCopy, safeWindow, false, false);
650✔
3476

650✔
3477
    const onCut = React.useCallback(
650✔
3478
        async (e?: ClipboardEvent) => {
650✔
3479
            if (!keybindings.cut) return;
1!
3480
            const focused =
1✔
3481
                scrollRef.current?.contains(document.activeElement) === true ||
1✔
3482
                canvasRef.current?.contains(document.activeElement) === true;
1✔
3483

1✔
3484
            if (!focused) return;
1!
3485
            await onCopy(e);
1✔
3486
            if (gridSelection.current !== undefined) {
1✔
3487
                let effectiveSelection: GridSelection = {
1✔
3488
                    current: {
1✔
3489
                        cell: gridSelection.current.cell,
1✔
3490
                        range: gridSelection.current.range,
1✔
3491
                        rangeStack: [],
1✔
3492
                    },
1✔
3493
                    rows: CompactSelection.empty(),
1✔
3494
                    columns: CompactSelection.empty(),
1✔
3495
                };
1✔
3496
                const onDeleteResult = onDelete?.(effectiveSelection);
1✔
3497
                if (onDeleteResult === false) return;
1!
3498
                effectiveSelection = onDeleteResult === true ? effectiveSelection : onDeleteResult;
1!
3499
                if (effectiveSelection.current === undefined) return;
1!
3500
                deleteRange(effectiveSelection.current.range);
1✔
3501
            }
1✔
3502
        },
1✔
3503
        [deleteRange, gridSelection, keybindings.cut, onCopy, onDelete]
650✔
3504
    );
650✔
3505

650✔
3506
    useEventListener("cut", onCut, safeWindow, false, false);
650✔
3507

650✔
3508
    const onSearchResultsChanged = React.useCallback(
650✔
3509
        (results: readonly Item[], navIndex: number) => {
650✔
3510
            if (onSearchResultsChangedIn !== undefined) {
7!
UNCOV
3511
                if (rowMarkerOffset !== 0) {
×
3512
                    results = results.map(item => [item[0] - rowMarkerOffset, item[1]]);
×
UNCOV
3513
                }
×
3514
                onSearchResultsChangedIn(results, navIndex);
×
3515
                return;
×
UNCOV
3516
            }
×
3517
            if (results.length === 0 || navIndex === -1) return;
7✔
3518

2✔
3519
            const [col, row] = results[navIndex];
2✔
3520
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
7!
3521
                return;
×
UNCOV
3522
            }
✔
3523
            lastSent.current = [col, row];
2✔
3524
            updateSelectedCell(col, row, false, false);
2✔
3525
        },
7✔
3526
        [onSearchResultsChangedIn, rowMarkerOffset, updateSelectedCell]
650✔
3527
    );
650✔
3528

650✔
3529
    // this effects purpose in life is to scroll the newly selected cell into view when and ONLY when that cell
650✔
3530
    // is from an external gridSelection change. Also note we want the unmangled out selection because scrollTo
650✔
3531
    // expects unmangled indexes
650✔
3532
    const [outCol, outRow] = gridSelectionOuter?.current?.cell ?? [];
650✔
3533
    const scrollToRef = React.useRef(scrollTo);
650✔
3534
    scrollToRef.current = scrollTo;
650✔
3535
    React.useLayoutEffect(() => {
650✔
3536
        if (
206✔
3537
            !hasJustScrolled.current &&
206✔
3538
            outCol !== undefined &&
206✔
3539
            outRow !== undefined &&
77✔
3540
            (outCol !== expectedExternalGridSelection.current?.current?.cell[0] ||
77✔
3541
                outRow !== expectedExternalGridSelection.current?.current?.cell[1])
77✔
3542
        ) {
206!
3543
            scrollToRef.current(outCol, outRow);
×
UNCOV
3544
        }
×
3545
        hasJustScrolled.current = false; //only allow skipping a single scroll
206✔
3546
    }, [outCol, outRow]);
650✔
3547

650✔
3548
    const selectionOutOfBounds =
650✔
3549
        gridSelection.current !== undefined &&
650✔
3550
        (gridSelection.current.cell[0] >= mangledCols.length || gridSelection.current.cell[1] >= mangledRows);
303✔
3551
    React.useLayoutEffect(() => {
650✔
3552
        if (selectionOutOfBounds) {
135✔
3553
            setGridSelection(emptyGridSelection, false);
1✔
3554
        }
1✔
3555
    }, [selectionOutOfBounds, setGridSelection]);
650✔
3556

650✔
3557
    const disabledRows = React.useMemo(() => {
650✔
3558
        if (showTrailingBlankRow === true && trailingRowOptions?.tint === true) {
134✔
3559
            return CompactSelection.fromSingleSelection(mangledRows - 1);
131✔
3560
        }
131✔
3561
        return CompactSelection.empty();
3✔
3562
    }, [mangledRows, showTrailingBlankRow, trailingRowOptions?.tint]);
650✔
3563

650✔
3564
    const mangledVerticalBorder = React.useCallback(
650✔
3565
        (col: number) => {
650✔
3566
            return typeof verticalBorder === "boolean"
7,315!
UNCOV
3567
                ? verticalBorder
×
3568
                : verticalBorder?.(col - rowMarkerOffset) ?? true;
7,315!
3569
        },
7,315✔
3570
        [rowMarkerOffset, verticalBorder]
650✔
3571
    );
650✔
3572

650✔
3573
    const renameGroupNode = React.useMemo(() => {
650✔
3574
        if (renameGroup === undefined || canvasRef.current === null) return null;
135✔
3575
        const { bounds, group } = renameGroup;
2✔
3576
        const canvasBounds = canvasRef.current.getBoundingClientRect();
2✔
3577
        return (
2✔
3578
            <GroupRename
2✔
3579
                bounds={bounds}
2✔
3580
                group={group}
2✔
3581
                canvasBounds={canvasBounds}
2✔
3582
                onClose={() => setRenameGroup(undefined)}
2✔
3583
                onFinish={newVal => {
2✔
3584
                    setRenameGroup(undefined);
1✔
3585
                    onGroupHeaderRenamed?.(group, newVal);
1✔
3586
                }}
1✔
3587
            />
2✔
3588
        );
135✔
3589
    }, [onGroupHeaderRenamed, renameGroup]);
650✔
3590

650✔
3591
    const mangledFreezeColumns = Math.min(mangledCols.length, freezeColumns + (hasRowMarkers ? 1 : 0));
650✔
3592

650✔
3593
    React.useImperativeHandle(
650✔
3594
        forwardedRef,
650✔
3595
        () => ({
650✔
3596
            appendRow: (col: number, openOverlay?: boolean) => appendRow(col + rowMarkerOffset, openOverlay),
26✔
3597
            updateCells: damageList => {
26✔
3598
                if (rowMarkerOffset !== 0) {
2✔
3599
                    damageList = damageList.map(x => ({ cell: [x.cell[0] + rowMarkerOffset, x.cell[1]] }));
1✔
3600
                }
1✔
3601
                return gridRef.current?.damage(damageList);
2✔
3602
            },
2✔
3603
            getBounds: (col, row) => {
26✔
UNCOV
3604
                if (canvasRef?.current === null || scrollRef?.current === null) {
×
NEW
3605
                    return undefined;
×
UNCOV
3606
                }
×
UNCOV
3607

×
UNCOV
3608
                if (col === undefined && row === undefined) {
×
UNCOV
3609
                    // Return the bounds of the entire scroll area:
×
NEW
3610
                    const rect = canvasRef.current.getBoundingClientRect();
×
NEW
3611
                    const scale = rect.width / scrollRef.current.clientWidth;
×
NEW
3612
                    return {
×
NEW
3613
                        x: rect.x - scrollRef.current.scrollLeft * scale,
×
NEW
3614
                        y: rect.y - scrollRef.current.scrollTop * scale,
×
NEW
3615
                        width: scrollRef.current.scrollWidth * scale,
×
NEW
3616
                        height: scrollRef.current.scrollHeight * scale,
×
NEW
3617
                    };
×
3618
                }
×
NEW
3619
                return gridRef.current?.getBounds(col ?? 0 + rowMarkerOffset, row);
×
UNCOV
3620
            },
×
3621
            focus: () => gridRef.current?.focus(),
26✔
3622
            emit: async e => {
26✔
3623
                switch (e) {
5✔
3624
                    case "delete":
5✔
3625
                        onKeyDown({
1✔
3626
                            bounds: undefined,
1✔
3627
                            cancel: () => undefined,
1✔
3628
                            stopPropagation: () => undefined,
1✔
3629
                            preventDefault: () => undefined,
1✔
3630
                            ctrlKey: false,
1✔
3631
                            key: "Delete",
1✔
3632
                            keyCode: 46,
1✔
3633
                            metaKey: false,
1✔
3634
                            shiftKey: false,
1✔
3635
                            altKey: false,
1✔
3636
                            rawEvent: undefined,
1✔
3637
                            location: undefined,
1✔
3638
                        });
1✔
3639
                        break;
1✔
3640
                    case "fill-right":
5✔
3641
                        onKeyDown({
1✔
3642
                            bounds: undefined,
1✔
3643
                            cancel: () => undefined,
1✔
3644
                            stopPropagation: () => undefined,
1✔
3645
                            preventDefault: () => undefined,
1✔
3646
                            ctrlKey: true,
1✔
3647
                            key: "r",
1✔
3648
                            keyCode: 82,
1✔
3649
                            metaKey: false,
1✔
3650
                            shiftKey: false,
1✔
3651
                            altKey: false,
1✔
3652
                            rawEvent: undefined,
1✔
3653
                            location: undefined,
1✔
3654
                        });
1✔
3655
                        break;
1✔
3656
                    case "fill-down":
5✔
3657
                        onKeyDown({
1✔
3658
                            bounds: undefined,
1✔
3659
                            cancel: () => undefined,
1✔
3660
                            stopPropagation: () => undefined,
1✔
3661
                            preventDefault: () => undefined,
1✔
3662
                            ctrlKey: true,
1✔
3663
                            key: "d",
1✔
3664
                            keyCode: 68,
1✔
3665
                            metaKey: false,
1✔
3666
                            shiftKey: false,
1✔
3667
                            altKey: false,
1✔
3668
                            rawEvent: undefined,
1✔
3669
                            location: undefined,
1✔
3670
                        });
1✔
3671
                        break;
1✔
3672
                    case "copy":
5✔
3673
                        await onCopy(undefined, true);
1✔
3674
                        break;
1✔
3675
                    case "paste":
5✔
3676
                        await onPasteInternal();
1✔
3677
                        break;
1✔
3678
                }
5✔
3679
            },
5✔
3680
            scrollTo,
26✔
3681
            remeasureColumns: cols => {
26✔
3682
                for (const col of cols) {
1✔
3683
                    void normalSizeColumn(col + rowMarkerOffset, true);
1✔
3684
                }
1✔
3685
            },
1✔
3686
        }),
26✔
3687
        [appendRow, normalSizeColumn, onCopy, onKeyDown, onPasteInternal, rowMarkerOffset, scrollTo]
650✔
3688
    );
650✔
3689

650✔
3690
    const [selCol, selRow] = currentCell ?? [];
650✔
3691
    const onCellFocused = React.useCallback(
650✔
3692
        (cell: Item) => {
650✔
3693
            const [col, row] = cell;
24✔
3694

24✔
3695
            if (row === -1) {
24!
UNCOV
3696
                if (columnSelect !== "none") {
×
3697
                    setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, false);
×
3698
                    focus();
×
UNCOV
3699
                }
×
3700
                return;
×
UNCOV
3701
            }
×
3702

24✔
3703
            if (selCol === col && selRow === row) return;
24✔
3704
            setCurrent(
1✔
3705
                {
1✔
3706
                    cell,
1✔
3707
                    range: { x: col, y: row, width: 1, height: 1 },
1✔
3708
                },
1✔
3709
                true,
1✔
3710
                false,
1✔
3711
                "keyboard-nav"
1✔
3712
            );
1✔
3713
            scrollTo(col, row);
1✔
3714
        },
24✔
3715
        [columnSelect, focus, scrollTo, selCol, selRow, setCurrent, setSelectedColumns]
650✔
3716
    );
650✔
3717

650✔
3718
    const [isFocused, setIsFocused] = React.useState(false);
650✔
3719
    const setIsFocusedDebounced = React.useRef(
650✔
3720
        debounce((val: boolean) => {
650✔
3721
            setIsFocused(val);
48✔
3722
        }, 5)
650✔
3723
    );
650✔
3724

650✔
3725
    const onCanvasFocused = React.useCallback(() => {
650✔
3726
        setIsFocusedDebounced.current(true);
58✔
3727

58✔
3728
        // check for mouse state, don't do anything if the user is clicked to focus.
58✔
3729
        if (
58✔
3730
            gridSelection.current === undefined &&
58✔
3731
            gridSelection.columns.length === 0 &&
6✔
3732
            gridSelection.rows.length === 0 &&
5✔
3733
            mouseState === undefined
5✔
3734
        ) {
58✔
3735
            setCurrent(
5✔
3736
                {
5✔
3737
                    cell: [rowMarkerOffset, cellYOffset],
5✔
3738
                    range: {
5✔
3739
                        x: rowMarkerOffset,
5✔
3740
                        y: cellYOffset,
5✔
3741
                        width: 1,
5✔
3742
                        height: 1,
5✔
3743
                    },
5✔
3744
                },
5✔
3745
                true,
5✔
3746
                false,
5✔
3747
                "keyboard-select"
5✔
3748
            );
5✔
3749
        }
5✔
3750
    }, [cellYOffset, gridSelection, mouseState, rowMarkerOffset, setCurrent]);
650✔
3751

650✔
3752
    const onFocusOut = React.useCallback(() => {
650✔
3753
        setIsFocusedDebounced.current(false);
28✔
3754
    }, []);
650✔
3755

650✔
3756
    const [idealWidth, idealHeight] = React.useMemo(() => {
650✔
3757
        let h: number;
147✔
3758
        const scrollbarWidth = experimental?.scrollbarWidthOverride ?? getScrollBarWidth();
147✔
3759
        const rowsCountWithTrailingRow = rows + (showTrailingBlankRow ? 1 : 0);
147!
3760
        if (typeof rowHeight === "number") {
147✔
3761
            h = totalHeaderHeight + rowsCountWithTrailingRow * rowHeight;
146✔
3762
        } else {
147✔
3763
            let avg = 0;
1✔
3764
            const toAverage = Math.min(rowsCountWithTrailingRow, 10);
1✔
3765
            for (let i = 0; i < toAverage; i++) {
1✔
3766
                avg += rowHeight(i);
10✔
3767
            }
10✔
3768
            avg = Math.floor(avg / toAverage);
1✔
3769

1✔
3770
            h = totalHeaderHeight + rowsCountWithTrailingRow * avg;
1✔
3771
        }
1✔
3772
        h += scrollbarWidth;
147✔
3773

147✔
3774
        const w = mangledCols.reduce((acc, x) => x.width + acc, 0) + scrollbarWidth;
147✔
3775

147✔
3776
        // We need to set a reasonable cap here as some browsers will just ignore huge values
147✔
3777
        // rather than treat them as huge values.
147✔
3778
        return [`${Math.min(100_000, w)}px`, `${Math.min(100_000, h)}px`];
147✔
3779
    }, [mangledCols, experimental?.scrollbarWidthOverride, rowHeight, rows, showTrailingBlankRow, totalHeaderHeight]);
650✔
3780

650✔
3781
    return (
650✔
3782
        <ThemeContext.Provider value={mergedTheme}>
650✔
3783
            <DataEditorContainer
650✔
3784
                style={makeCSSStyle(mergedTheme)}
650✔
3785
                className={className}
650✔
3786
                inWidth={width ?? idealWidth}
650✔
3787
                inHeight={height ?? idealHeight}>
650✔
3788
                <DataGridSearch
650✔
3789
                    fillHandle={fillHandle}
650✔
3790
                    drawFocusRing={drawFocusRing}
650✔
3791
                    experimental={experimental}
650✔
3792
                    fixedShadowX={fixedShadowX}
650✔
3793
                    fixedShadowY={fixedShadowY}
650✔
3794
                    getRowThemeOverride={getRowThemeOverride}
650✔
3795
                    headerIcons={headerIcons}
650✔
3796
                    imageWindowLoader={imageWindowLoader}
650✔
3797
                    initialSize={initialSize}
650✔
3798
                    isDraggable={isDraggable}
650✔
3799
                    onDragLeave={onDragLeave}
650✔
3800
                    onRowMoved={onRowMoved}
650✔
3801
                    overscrollX={overscrollX}
650✔
3802
                    overscrollY={overscrollY}
650✔
3803
                    preventDiagonalScrolling={preventDiagonalScrolling}
650✔
3804
                    rightElement={rightElement}
650✔
3805
                    rightElementProps={rightElementProps}
650✔
3806
                    smoothScrollX={smoothScrollX}
650✔
3807
                    smoothScrollY={smoothScrollY}
650✔
3808
                    className={className}
650✔
3809
                    enableGroups={enableGroups}
650✔
3810
                    onCanvasFocused={onCanvasFocused}
650✔
3811
                    onCanvasBlur={onFocusOut}
650✔
3812
                    canvasRef={canvasRef}
650✔
3813
                    onContextMenu={onContextMenu}
650✔
3814
                    theme={mergedTheme}
650✔
3815
                    cellXOffset={cellXOffset}
650✔
3816
                    cellYOffset={cellYOffset}
650✔
3817
                    accessibilityHeight={visibleRegion.height}
650✔
3818
                    onDragEnd={onDragEnd}
650✔
3819
                    columns={mangledCols}
650✔
3820
                    drawHeader={drawHeader}
650✔
3821
                    drawCell={drawCell}
650✔
3822
                    disabledRows={disabledRows}
650✔
3823
                    freezeColumns={mangledFreezeColumns}
650✔
3824
                    lockColumns={rowMarkerOffset}
650✔
3825
                    firstColAccessible={rowMarkerOffset === 0}
650✔
3826
                    getCellContent={getMangledCellContent}
650✔
3827
                    minColumnWidth={minColumnWidth}
650✔
3828
                    maxColumnWidth={maxColumnWidth}
650✔
3829
                    searchInputRef={searchInputRef}
650✔
3830
                    showSearch={showSearch}
650✔
3831
                    onSearchClose={onSearchClose}
650✔
3832
                    highlightRegions={highlightRegions}
650✔
3833
                    getCellsForSelection={getCellsForSelection}
650✔
3834
                    getGroupDetails={mangledGetGroupDetails}
650✔
3835
                    headerHeight={headerHeight}
650✔
3836
                    isFocused={isFocused}
650✔
3837
                    groupHeaderHeight={enableGroups ? groupHeaderHeight : 0}
650✔
3838
                    trailingRowType={
650✔
3839
                        !showTrailingBlankRow ? "none" : trailingRowOptions?.sticky === true ? "sticky" : "appended"
650!
3840
                    }
650✔
3841
                    onColumnResize={onColumnResize}
650✔
3842
                    onColumnResizeEnd={onColumnResizeEnd}
650✔
3843
                    onColumnResizeStart={onColumnResizeStart}
650✔
3844
                    onCellFocused={onCellFocused}
650✔
3845
                    onColumnMoved={onColumnMovedImpl}
650✔
3846
                    onDragStart={onDragStartImpl}
650✔
3847
                    onHeaderMenuClick={onHeaderMenuClickInner}
650✔
3848
                    onItemHovered={onItemHoveredImpl}
650✔
3849
                    isFilling={mouseState?.fillHandle === true}
650✔
3850
                    onMouseMove={onMouseMoveImpl}
650✔
3851
                    onKeyDown={onKeyDown}
650✔
3852
                    onKeyUp={onKeyUpIn}
650✔
3853
                    onMouseDown={onMouseDown}
650✔
3854
                    onMouseUp={onMouseUp}
650✔
3855
                    onDragOverCell={onDragOverCell}
650✔
3856
                    onDrop={onDrop}
650✔
3857
                    onSearchResultsChanged={onSearchResultsChanged}
650✔
3858
                    onVisibleRegionChanged={onVisibleRegionChangedImpl}
650✔
3859
                    clientSize={clientSize}
650✔
3860
                    rowHeight={rowHeight}
650✔
3861
                    searchResults={searchResults}
650✔
3862
                    searchValue={searchValue}
650✔
3863
                    onSearchValueChange={onSearchValueChange}
650✔
3864
                    rows={mangledRows}
650✔
3865
                    scrollRef={scrollRef}
650✔
3866
                    selection={gridSelection}
650✔
3867
                    translateX={visibleRegion.tx}
650✔
3868
                    translateY={visibleRegion.ty}
650✔
3869
                    verticalBorder={mangledVerticalBorder}
650✔
3870
                    gridRef={gridRef}
650✔
3871
                    getCellRenderer={getCellRenderer}
650✔
3872
                />
650✔
3873
                {renameGroupNode}
650✔
3874
                {overlay !== undefined && (
650✔
3875
                    <React.Suspense fallback={null}>
27✔
3876
                        <DataGridOverlayEditor
27✔
3877
                            {...overlay}
27✔
3878
                            validateCell={validateCell}
27✔
3879
                            id={overlayID}
27✔
3880
                            getCellRenderer={getCellRenderer}
27✔
3881
                            className={experimental?.isSubGrid === true ? "click-outside-ignore" : undefined}
27!
3882
                            provideEditor={provideEditor}
27✔
3883
                            imageEditorOverride={imageEditorOverride}
27✔
3884
                            onFinishEditing={onFinishEditing}
27✔
3885
                            markdownDivCreateNode={markdownDivCreateNode}
27✔
3886
                            isOutsideClick={isOutsideClick}
27✔
3887
                        />
27✔
3888
                    </React.Suspense>
27✔
3889
                )}
650✔
3890
            </DataEditorContainer>
650✔
3891
        </ThemeContext.Provider>
650✔
3892
    );
650✔
3893
};
650✔
3894

1✔
3895
/**
1✔
3896
 * The primary component of Glide Data Grid.
1✔
3897
 * @category DataEditor
1✔
3898
 * @param {DataEditorProps} props
1✔
3899
 */
1✔
3900
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