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

glideapps / glide-data-grid / 16205117828

10 Jul 2025 08:17PM UTC coverage: 90.954% (-0.2%) from 91.171%
16205117828

Pull #1062

github

web-flow
Merge eeb6397de into 6c463f70b
Pull Request #1062: feat: onRowAppended and onColumnAppended

2933 of 3639 branches covered (80.6%)

90 of 112 new or added lines in 2 files covered. (80.36%)

377 existing lines in 6 files now uncovered.

18007 of 19798 relevant lines covered (90.95%)

3087.08 hits per line

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

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

1✔
89
const DataGridOverlayEditor = React.lazy(
1✔
90
    async () => await import("../internal/data-grid-overlay-editor/data-grid-overlay-editor.js")
1✔
91
);
1✔
92

1✔
93
// There must be a better way
1✔
94
let idCounter = 0;
1✔
95

1✔
96
export interface RowMarkerOptions {
1✔
97
    kind: "checkbox" | "number" | "clickable-number" | "checkbox-visible" | "both" | "none";
1✔
98
    checkboxStyle?: "circle" | "square";
1✔
99
    startIndex?: number;
1✔
100
    width?: number;
1✔
101
    theme?: Partial<Theme>;
1✔
102
    headerTheme?: Partial<Theme>;
1✔
103
    headerAlwaysVisible?: boolean;
1✔
104
    headerDisabled?: boolean;
1✔
105
}
1✔
106

1✔
107
interface MouseState {
1✔
108
    readonly previousSelection?: GridSelection;
1✔
109
    readonly fillHandle?: boolean;
1✔
110
}
1✔
111

1✔
112
type Props = Partial<
1✔
113
    Omit<
1✔
114
        DataGridSearchProps,
1✔
115
        | "accessibilityHeight"
1✔
116
        | "canvasRef"
1✔
117
        | "cellXOffset"
1✔
118
        | "cellYOffset"
1✔
119
        | "className"
1✔
120
        | "clientSize"
1✔
121
        | "columns"
1✔
122
        | "disabledRows"
1✔
123
        | "drawFocusRing"
1✔
124
        | "enableGroups"
1✔
125
        | "firstColAccessible"
1✔
126
        | "firstColSticky"
1✔
127
        | "freezeColumns"
1✔
128
        | "hasAppendRow"
1✔
129
        | "getCellContent"
1✔
130
        | "getCellRenderer"
1✔
131
        | "getCellsForSelection"
1✔
132
        | "getRowThemeOverride"
1✔
133
        | "gridRef"
1✔
134
        | "groupHeaderHeight"
1✔
135
        | "headerHeight"
1✔
136
        | "isFilling"
1✔
137
        | "isFocused"
1✔
138
        | "imageWindowLoader"
1✔
139
        | "lockColumns"
1✔
140
        | "maxColumnWidth"
1✔
141
        | "minColumnWidth"
1✔
142
        | "nonGrowWidth"
1✔
143
        | "onCanvasBlur"
1✔
144
        | "onCanvasFocused"
1✔
145
        | "onCellFocused"
1✔
146
        | "onContextMenu"
1✔
147
        | "onDragEnd"
1✔
148
        | "onMouseDown"
1✔
149
        | "onMouseMove"
1✔
150
        | "onMouseUp"
1✔
151
        | "onVisibleRegionChanged"
1✔
152
        | "rowHeight"
1✔
153
        | "rows"
1✔
154
        | "scrollRef"
1✔
155
        | "searchInputRef"
1✔
156
        | "selectedColumns"
1✔
157
        | "selection"
1✔
158
        | "theme"
1✔
159
        | "translateX"
1✔
160
        | "translateY"
1✔
161
        | "verticalBorder"
1✔
162
    >
1✔
163
>;
1✔
164

1✔
165
type EmitEvents = "copy" | "paste" | "delete" | "fill-right" | "fill-down";
1✔
166

1✔
167
function getSpanStops(cells: readonly (readonly GridCell[])[]): number[] {
5✔
168
    return uniq(
5✔
169
        flatten(
5✔
170
            flatten(cells)
5✔
171
                .filter(c => c.span !== undefined)
5✔
172
                .map(c => range((c.span?.[0] ?? 0) + 1, (c.span?.[1] ?? 0) + 1))
5✔
173
        )
5✔
174
    );
5✔
175
}
5✔
176

1✔
177
function shiftSelection(input: GridSelection, offset: number): GridSelection {
311✔
178
    if (input === undefined || offset === 0 || (input.columns.length === 0 && input.current === undefined))
311✔
179
        return input;
311✔
180

35✔
181
    return {
35✔
182
        current:
35✔
183
            input.current === undefined
35✔
184
                ? undefined
1✔
185
                : {
34✔
186
                      cell: [input.current.cell[0] + offset, input.current.cell[1]],
34✔
187
                      range: {
34✔
188
                          ...input.current.range,
34✔
189
                          x: input.current.range.x + offset,
34✔
190
                      },
34✔
191
                      rangeStack: input.current.rangeStack.map(r => ({
34✔
192
                          ...r,
×
193
                          x: r.x + offset,
×
194
                      })),
34✔
195
                  },
34✔
196
        rows: input.rows,
311✔
197
        columns: input.columns.offset(offset),
311✔
198
    };
311✔
199
}
311✔
200

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

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

1✔
282
    /** The columns to display in the data grid.
1✔
283
     * @group Data
1✔
284
     */
1✔
285
    readonly columns: readonly GridColumn[];
1✔
286

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

1✔
313
    /**
1✔
314
     * The number of rows in the grid.
1✔
315
     * @group Data
1✔
316
     */
1✔
317
    readonly rows: number;
1✔
318

1✔
319
    /** Determines if row markers should be automatically added to the grid.
1✔
320
     * Interactive row markers allow the user to select a row.
1✔
321
     *
1✔
322
     * - "clickable-number" renders a number that can be clicked to
1✔
323
     *   select the row
1✔
324
     * - "both" causes the row marker to show up as a number but
1✔
325
     *   reveal a checkbox when the marker is hovered.
1✔
326
     *
1✔
327
     * @defaultValue `none`
1✔
328
     * @group Style
1✔
329
     */
1✔
330
    readonly rowMarkers?: RowMarkerOptions["kind"] | RowMarkerOptions;
1✔
331
    /**
1✔
332
     * Sets the width of row markers in pixels, if unset row markers will automatically size.
1✔
333
     * @group Style
1✔
334
     * @deprecated Use `rowMarkers` instead.
1✔
335
     */
1✔
336
    readonly rowMarkerWidth?: number;
1✔
337
    /** Changes the starting index for row markers.
1✔
338
     * @defaultValue 1
1✔
339
     * @group Style
1✔
340
     * @deprecated Use `rowMarkers` instead.
1✔
341
     */
1✔
342
    readonly rowMarkerStartIndex?: number;
1✔
343

1✔
344
    /** Changes the theme of the row marker column
1✔
345
     * @group Style
1✔
346
     * @deprecated Use `rowMarkers` instead.
1✔
347
     */
1✔
348
    readonly rowMarkerTheme?: Partial<Theme>;
1✔
349

1✔
350
    /** Sets the width of the data grid.
1✔
351
     * @group Style
1✔
352
     */
1✔
353
    readonly width?: number | string;
1✔
354
    /** Sets the height of the data grid.
1✔
355
     * @group Style
1✔
356
     */
1✔
357
    readonly height?: number | string;
1✔
358
    /** Custom classname for data grid wrapper.
1✔
359
     * @group Style
1✔
360
     */
1✔
361
    readonly className?: string;
1✔
362

1✔
363
    /** If set to `default`, `gridSelection` will be coerced to always include full spans.
1✔
364
     * @group Selection
1✔
365
     * @defaultValue `default`
1✔
366
     */
1✔
367
    readonly spanRangeBehavior?: "default" | "allowPartial";
1✔
368

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

1✔
404
    /** Controls if range selection is allowed to span columns.
1✔
405
     * @group Selection
1✔
406
     * @defaultValue `true`
1✔
407
     */
1✔
408
    readonly rangeSelectionColumnSpanning?: boolean;
1✔
409

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

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

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

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

1✔
465
    /**
1✔
466
     * Allows overriding the theme of any row
1✔
467
     * @param row represents the row index of the row, increasing by 1 for every represented row. Collapsed rows are not included.
1✔
468
     * @param groupRow represents the row index of the group row. Only distinct when row grouping enabled.
1✔
469
     * @param contentRow represents the index of the row excluding group headers. Only distinct when row grouping enabled.
1✔
470
     * @returns
1✔
471
     */
1✔
472
    readonly getRowThemeOverride?: (row: number, groupRow: number, contentRow: number) => Partial<Theme> | undefined;
1✔
473

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

1✔
487
    /**
1✔
488
     * Emitted when the grid selection is cleared.
1✔
489
     * @group Selection
1✔
490
     */
1✔
491
    readonly onSelectionCleared?: () => void;
1✔
492

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

1✔
532
            /**
1✔
533
             * All visible freeze regions
1✔
534
             */
1✔
535
            freezeRegions?: readonly Rectangle[];
1✔
536
        }
1✔
537
    ) => void;
1✔
538

1✔
539
    /**
1✔
540
     * The primary callback for getting cell data into the data grid.
1✔
541
     * @group Data
1✔
542
     * @param cell The location of the cell being requested.
1✔
543
     * @returns A valid GridCell to be rendered by the Grid.
1✔
544
     */
1✔
545
    readonly getCellContent: (cell: Item) => GridCell;
1✔
546
    /**
1✔
547
     * Determines if row selection requires a modifier key to enable multi-selection or not. In auto mode it adapts to
1✔
548
     * touch or mouse environments automatically, in multi-mode it always acts as if the multi key (Ctrl) is pressed.
1✔
549
     * @group Editing
1✔
550
     * @defaultValue `auto`
1✔
551
     */
1✔
552
    readonly rowSelectionMode?: "auto" | "multi";
1✔
553

1✔
554
    /**
1✔
555
     * Add table headers to copied data.
1✔
556
     * @group Editing
1✔
557
     * @defaultValue `false`
1✔
558
     */
1✔
559
    readonly copyHeaders?: boolean;
1✔
560

1✔
561
    /**
1✔
562
     * Determins which keybindings are enabled.
1✔
563
     * @group Editing
1✔
564
     */
1✔
565
    readonly keybindings?: Partial<Keybinds>;
1✔
566

1✔
567
    /**
1✔
568
     * Determines if the data editor should immediately begin editing when the user types on a selected cell
1✔
569
     * @group Editing
1✔
570
     */
1✔
571
    readonly editOnType?: boolean;
1✔
572

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

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

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

1✔
611
    /**
1✔
612
     * Controls the grouping of rows to be drawn in the grid.
1✔
613
     */
1✔
614
    readonly rowGrouping?: RowGroupingOptions;
1✔
615

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

1✔
629
    /**
1✔
630
     * The theme used by the data grid to get all color and font information
1✔
631
     * @group Style
1✔
632
     */
1✔
633
    readonly theme?: Partial<Theme>;
1✔
634

1✔
635
    readonly renderers?: readonly InternalCellRenderer<InnerGridCell>[];
1✔
636

1✔
637
    /**
1✔
638
     * An array of custom renderers which can be used to extend the data grid.
1✔
639
     * @group Advanced
1✔
640
     */
1✔
641
    readonly customRenderers?: readonly CustomRenderer<any>[];
1✔
642

1✔
643
    /**
1✔
644
     * Scales most elements in the theme to match rem scaling automatically
1✔
645
     * @defaultValue false
1✔
646
     */
1✔
647
    readonly scaleToRem?: boolean;
1✔
648

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

1✔
657
    /**
1✔
658
     * Controls which directions fill is allowed in.
1✔
659
     */
1✔
660
    readonly allowedFillDirections?: FillHandleDirection;
1✔
661

1✔
662
    /**
1✔
663
     * Determines when a cell is considered activated and will emit the `onCellActivated` event. Generally an activated
1✔
664
     * cell will open to edit mode.
1✔
665
     */
1✔
666
    readonly cellActivationBehavior?: CellActiviationBehavior;
1✔
667

1✔
668
    /**
1✔
669
     * Controls if focus will trap inside the data grid when doing tab and caret navigation.
1✔
670
     */
1✔
671
    readonly trapFocus?: boolean;
1✔
672

1✔
673
    /**
1✔
674
     * Allows overriding the default amount of bloom (the size growth of the overlay editor)
1✔
675
     */
1✔
676
    readonly editorBloom?: readonly [number, number];
1✔
677

1✔
678
    /**
1✔
679
     * If set to true, the data grid will attempt to scroll to keep the selction in view
1✔
680
     */
1✔
681
    readonly scrollToActiveCell?: boolean;
1✔
682

1✔
683
    readonly drawFocusRing?: boolean | "no-editor";
1✔
684

1✔
685
    /**
1✔
686
     * Allows overriding the default portal element.
1✔
687
     */
1✔
688
    readonly portalElementRef?: React.RefObject<HTMLElement>;
1✔
689
}
1✔
690

1✔
691
type ScrollToFn = (
1✔
692
    col: number | { amount: number; unit: "cell" | "px" },
1✔
693
    row: number | { amount: number; unit: "cell" | "px" },
1✔
694
    dir?: "horizontal" | "vertical" | "both",
1✔
695
    paddingX?: number,
1✔
696
    paddingY?: number,
1✔
697
    options?: {
1✔
698
        hAlign?: "start" | "center" | "end";
1✔
699
        vAlign?: "start" | "center" | "end";
1✔
700
        behavior?: ScrollBehavior;
1✔
701
    }
1✔
702
) => void;
1✔
703

1✔
704
/** @category DataEditor */
1✔
705
export interface DataEditorRef {
1✔
706
    /**
1✔
707
     * Programatically appends a row.
1✔
708
     * @param col The column index to focus in the new row.
1✔
709
     * @returns A promise which waits for the append to complete.
1✔
710
     */
1✔
711
    appendRow: (col: number, openOverlay?: boolean, behavior?: ScrollBehavior) => Promise<void>;
1✔
712
    /**
1✔
713
     * Programatically appends a column.
1✔
714
     * @param row The row index to focus in the new column.
1✔
715
     * @returns A promise which waits for the append to complete.
1✔
716
     */
1✔
717
    appendColumn: (row: number, openOverlay?: boolean) => Promise<void>;
1✔
718
    /**
1✔
719
     * Triggers cells to redraw.
1✔
720
     */
1✔
721
    updateCells: DataGridRef["damage"];
1✔
722
    /**
1✔
723
     * Gets the screen space bounds of the requested item.
1✔
724
     */
1✔
725
    getBounds: DataGridRef["getBounds"];
1✔
726
    /**
1✔
727
     * Triggers the data grid to focus itself or the correct accessibility element.
1✔
728
     */
1✔
729
    focus: DataGridRef["focus"];
1✔
730
    /**
1✔
731
     * Generic API for emitting events as if they had been triggered via user interaction.
1✔
732
     */
1✔
733
    emit: (eventName: EmitEvents) => Promise<void>;
1✔
734
    /**
1✔
735
     * Scrolls to the desired cell or location in the grid.
1✔
736
     */
1✔
737
    scrollTo: ScrollToFn;
1✔
738
    /**
1✔
739
     * Causes the columns in the selection to have their natural size recomputed and re-emitted as a resize event.
1✔
740
     */
1✔
741
    remeasureColumns: (cols: CompactSelection) => void;
1✔
742
    /**
1✔
743
     * Gets the mouse args from pointer event position.
1✔
744
     */
1✔
745
    getMouseArgsForPosition: (
1✔
746
        posX: number,
1✔
747
        posY: number,
1✔
748
        ev?: MouseEvent | TouchEvent
1✔
749
    ) => GridMouseEventArgs | undefined;
1✔
750
}
1✔
751

1✔
752
const loadingCell: GridCell = {
1✔
753
    kind: GridCellKind.Loading,
1✔
754
    allowOverlay: false,
1✔
755
};
1✔
756

1✔
757
export const emptyGridSelection: GridSelection = {
1✔
758
    columns: CompactSelection.empty(),
1✔
759
    rows: CompactSelection.empty(),
1✔
760
    current: undefined,
1✔
761
};
1✔
762

1✔
763
const DataEditorImpl: React.ForwardRefRenderFunction<DataEditorRef, DataEditorProps> = (p, forwardedRef) => {
1✔
764
    const [gridSelectionInner, setGridSelectionInner] = React.useState<GridSelection>(emptyGridSelection);
740✔
765

740✔
766
    const [overlay, setOverlay] = React.useState<{
740✔
767
        target: Rectangle;
740✔
768
        content: GridCell;
740✔
769
        theme: FullTheme;
740✔
770
        initialValue: string | undefined;
740✔
771
        cell: Item;
740✔
772
        highlight: boolean;
740✔
773
        forceEditMode: boolean;
740✔
774
    }>();
740✔
775
    const searchInputRef = React.useRef<HTMLInputElement | null>(null);
740✔
776
    const canvasRef = React.useRef<HTMLCanvasElement | null>(null);
740✔
777
    const [mouseState, setMouseState] = React.useState<MouseState>();
740✔
778
    const lastSent = React.useRef<[number, number]>();
740✔
779

740✔
780
    const safeWindow = typeof window === "undefined" ? null : window;
740!
781

740✔
782
    const {
740✔
783
        imageEditorOverride,
740✔
784
        getRowThemeOverride: getRowThemeOverrideIn,
740✔
785
        markdownDivCreateNode,
740✔
786
        width,
740✔
787
        height,
740✔
788
        columns: columnsIn,
740✔
789
        rows: rowsIn,
740✔
790
        getCellContent,
740✔
791
        onCellClicked,
740✔
792
        onCellActivated,
740✔
793
        onFillPattern,
740✔
794
        onFinishedEditing,
740✔
795
        coercePasteValue,
740✔
796
        drawHeader: drawHeaderIn,
740✔
797
        drawCell: drawCellIn,
740✔
798
        editorBloom,
740✔
799
        onHeaderClicked,
740✔
800
        onColumnProposeMove,
740✔
801
        rangeSelectionColumnSpanning = true,
740✔
802
        spanRangeBehavior = "default",
740✔
803
        onGroupHeaderClicked,
740✔
804
        onCellContextMenu,
740✔
805
        className,
740✔
806
        onHeaderContextMenu,
740✔
807
        getCellsForSelection: getCellsForSelectionIn,
740✔
808
        onGroupHeaderContextMenu,
740✔
809
        onGroupHeaderRenamed,
740✔
810
        onCellEdited,
740✔
811
        onCellsEdited,
740✔
812
        onSearchResultsChanged: onSearchResultsChangedIn,
740✔
813
        searchResults,
740✔
814
        onSearchValueChange,
740✔
815
        searchValue,
740✔
816
        onKeyDown: onKeyDownIn,
740✔
817
        onKeyUp: onKeyUpIn,
740✔
818
        keybindings: keybindingsIn,
740✔
819
        editOnType = true,
740✔
820
        onRowAppended,
740✔
821
        onColumnAppended,
740✔
822
        onColumnMoved,
740✔
823
        validateCell: validateCellIn,
740✔
824
        highlightRegions: highlightRegionsIn,
740✔
825
        rangeSelect = "rect",
740✔
826
        columnSelect = "multi",
740✔
827
        rowSelect = "multi",
740✔
828
        rangeSelectionBlending = "exclusive",
740✔
829
        columnSelectionBlending = "exclusive",
740✔
830
        rowSelectionBlending = "exclusive",
740✔
831
        onDelete: onDeleteIn,
740✔
832
        onDragStart,
740✔
833
        onMouseMove,
740✔
834
        onPaste,
740✔
835
        copyHeaders = false,
740✔
836
        freezeColumns = 0,
740✔
837
        cellActivationBehavior = "second-click",
740✔
838
        rowSelectionMode = "auto",
740✔
839
        onHeaderMenuClick,
740✔
840
        onHeaderIndicatorClick,
740✔
841
        getGroupDetails,
740✔
842
        rowGrouping,
740✔
843
        onSearchClose: onSearchCloseIn,
740✔
844
        onItemHovered,
740✔
845
        onSelectionCleared,
740✔
846
        showSearch: showSearchIn,
740✔
847
        onVisibleRegionChanged,
740✔
848
        gridSelection: gridSelectionOuter,
740✔
849
        onGridSelectionChange,
740✔
850
        minColumnWidth: minColumnWidthIn = 50,
740✔
851
        maxColumnWidth: maxColumnWidthIn = 500,
740✔
852
        maxColumnAutoWidth: maxColumnAutoWidthIn,
740✔
853
        provideEditor,
740✔
854
        trailingRowOptions,
740✔
855
        freezeTrailingRows = 0,
740✔
856
        allowedFillDirections = "orthogonal",
740✔
857
        scrollOffsetX,
740✔
858
        scrollOffsetY,
740✔
859
        verticalBorder,
740✔
860
        onDragOverCell,
740✔
861
        onDrop,
740✔
862
        onColumnResize: onColumnResizeIn,
740✔
863
        onColumnResizeEnd: onColumnResizeEndIn,
740✔
864
        onColumnResizeStart: onColumnResizeStartIn,
740✔
865
        customRenderers: additionalRenderers,
740✔
866
        fillHandle,
740✔
867
        experimental,
740✔
868
        fixedShadowX,
740✔
869
        fixedShadowY,
740✔
870
        headerIcons,
740✔
871
        imageWindowLoader,
740✔
872
        initialSize,
740✔
873
        isDraggable,
740✔
874
        onDragLeave,
740✔
875
        onRowMoved,
740✔
876
        overscrollX: overscrollXIn,
740✔
877
        overscrollY: overscrollYIn,
740✔
878
        preventDiagonalScrolling,
740✔
879
        rightElement,
740✔
880
        rightElementProps,
740✔
881
        trapFocus = false,
740✔
882
        smoothScrollX,
740✔
883
        smoothScrollY,
740✔
884
        scaleToRem = false,
740✔
885
        rowHeight: rowHeightIn = 34,
740✔
886
        headerHeight: headerHeightIn = 36,
740✔
887
        groupHeaderHeight: groupHeaderHeightIn = headerHeightIn,
740✔
888
        theme: themeIn,
740✔
889
        isOutsideClick,
740✔
890
        renderers,
740✔
891
        resizeIndicator,
740✔
892
        scrollToActiveCell = true,
740✔
893
        drawFocusRing: drawFocusRingIn = true,
740✔
894
        portalElementRef,
740✔
895
    } = p;
740✔
896

740✔
897
    const drawFocusRing = drawFocusRingIn === "no-editor" ? overlay === undefined : drawFocusRingIn;
740!
898

740✔
899
    const rowMarkersObj = typeof p.rowMarkers === "string" ? undefined : p.rowMarkers;
740✔
900

740✔
901
    const rowMarkers = rowMarkersObj?.kind ?? (p.rowMarkers as RowMarkerOptions["kind"]) ?? "none";
740!
902
    const rowMarkerWidthRaw = rowMarkersObj?.width ?? p.rowMarkerWidth;
740!
903
    const rowMarkerStartIndex = rowMarkersObj?.startIndex ?? p.rowMarkerStartIndex ?? 1;
740!
904
    const rowMarkerTheme = rowMarkersObj?.theme ?? p.rowMarkerTheme;
740!
905
    const headerRowMarkerTheme = rowMarkersObj?.headerTheme;
740!
906
    const headerRowMarkerAlwaysVisible = rowMarkersObj?.headerAlwaysVisible;
740!
907
    const headerRowMarkerDisabled = rowSelect !== "multi" || rowMarkersObj?.headerDisabled === true;
740!
908
    const rowMarkerCheckboxStyle = rowMarkersObj?.checkboxStyle ?? "square";
740!
909

740✔
910
    const minColumnWidth = Math.max(minColumnWidthIn, 20);
740✔
911
    const maxColumnWidth = Math.max(maxColumnWidthIn, minColumnWidth);
740✔
912
    const maxColumnAutoWidth = Math.max(maxColumnAutoWidthIn ?? maxColumnWidth, minColumnWidth);
740✔
913

740✔
914
    const docStyle = React.useMemo(() => {
740✔
915
        if (typeof window === "undefined") return { fontSize: "16px" };
151!
916
        return window.getComputedStyle(document.documentElement);
151✔
917
    }, []);
740✔
918

740✔
919
    const {
740✔
920
        rows,
740✔
921
        rowNumberMapper,
740✔
922
        rowHeight: rowHeightPostGrouping,
740✔
923
        getRowThemeOverride,
740✔
924
    } = useRowGroupingInner(rowGrouping, rowsIn, rowHeightIn, getRowThemeOverrideIn);
740✔
925

740✔
926
    const remSize = React.useMemo(() => Number.parseFloat(docStyle.fontSize), [docStyle]);
740✔
927
    const { rowHeight, headerHeight, groupHeaderHeight, theme, overscrollX, overscrollY } = useRemAdjuster({
740✔
928
        groupHeaderHeight: groupHeaderHeightIn,
740✔
929
        headerHeight: headerHeightIn,
740✔
930
        overscrollX: overscrollXIn,
740✔
931
        overscrollY: overscrollYIn,
740✔
932
        remSize,
740✔
933
        rowHeight: rowHeightPostGrouping,
740✔
934
        scaleToRem,
740✔
935
        theme: themeIn,
740✔
936
    });
740✔
937

740✔
938
    const keybindings = useKeybindingsWithDefaults(keybindingsIn);
740✔
939

740✔
940
    const rowMarkerWidth = rowMarkerWidthRaw ?? (rowsIn > 10_000 ? 48 : rowsIn > 1000 ? 44 : rowsIn > 100 ? 36 : 32);
740!
941
    const hasRowMarkers = rowMarkers !== "none";
740✔
942
    const rowMarkerOffset = hasRowMarkers ? 1 : 0;
740✔
943
    const showTrailingBlankRow = trailingRowOptions !== undefined;
740✔
944
    const lastRowSticky = trailingRowOptions?.sticky === true;
740✔
945

740✔
946
    const [showSearchInner, setShowSearchInner] = React.useState(false);
740✔
947
    const showSearch = showSearchIn ?? showSearchInner;
740✔
948

740✔
949
    const onSearchClose = React.useCallback(() => {
740✔
950
        if (onSearchCloseIn !== undefined) {
2✔
951
            onSearchCloseIn();
2✔
952
        } else {
2!
UNCOV
953
            setShowSearchInner(false);
×
UNCOV
954
        }
×
955
    }, [onSearchCloseIn]);
740✔
956

740✔
957
    const gridSelectionOuterMangled: GridSelection | undefined = React.useMemo((): GridSelection | undefined => {
740✔
958
        return gridSelectionOuter === undefined ? undefined : shiftSelection(gridSelectionOuter, rowMarkerOffset);
290✔
959
    }, [gridSelectionOuter, rowMarkerOffset]);
740✔
960
    const gridSelection = gridSelectionOuterMangled ?? gridSelectionInner;
740✔
961

740✔
962
    const abortControllerRef = React.useRef() as React.MutableRefObject<AbortController>;
740✔
963
    if (abortControllerRef.current === undefined) abortControllerRef.current = new AbortController();
740✔
964

740✔
965
    React.useEffect(() => () => abortControllerRef?.current.abort(), []);
740✔
966

740✔
967
    const [getCellsForSelection, getCellsForSeletionDirect] = useCellsForSelection(
740✔
968
        getCellsForSelectionIn,
740✔
969
        getCellContent,
740✔
970
        rowMarkerOffset,
740✔
971
        abortControllerRef.current,
740✔
972
        rows
740✔
973
    );
740✔
974

740✔
975
    const validateCell = React.useCallback<NonNullable<typeof validateCellIn>>(
740✔
976
        (cell, newValue, prevValue) => {
740✔
977
            if (validateCellIn === undefined) return true;
17✔
978
            const item: Item = [cell[0] - rowMarkerOffset, cell[1]];
1✔
979
            return validateCellIn?.(item, newValue, prevValue);
1✔
980
        },
17✔
981
        [rowMarkerOffset, validateCellIn]
740✔
982
    );
740✔
983

740✔
984
    const expectedExternalGridSelection = React.useRef<GridSelection | undefined>(gridSelectionOuter);
740✔
985
    const setGridSelection = React.useCallback(
740✔
986
        (newVal: GridSelection, expand: boolean): void => {
740✔
987
            if (expand) {
185✔
988
                newVal = expandSelection(
142✔
989
                    newVal,
142✔
990
                    getCellsForSelection,
142✔
991
                    rowMarkerOffset,
142✔
992
                    spanRangeBehavior,
142✔
993
                    abortControllerRef.current
142✔
994
                );
142✔
995
            }
142✔
996
            if (onGridSelectionChange !== undefined) {
185✔
997
                expectedExternalGridSelection.current = shiftSelection(newVal, -rowMarkerOffset);
143✔
998
                onGridSelectionChange(expectedExternalGridSelection.current);
143✔
999
            } else {
185✔
1000
                setGridSelectionInner(newVal);
42✔
1001
            }
42✔
1002
        },
185✔
1003
        [onGridSelectionChange, getCellsForSelection, rowMarkerOffset, spanRangeBehavior]
740✔
1004
    );
740✔
1005

740✔
1006
    const onColumnResize = whenDefined(
740✔
1007
        onColumnResizeIn,
740✔
1008
        React.useCallback<NonNullable<typeof onColumnResizeIn>>(
740✔
1009
            (_, w, ind, wg) => {
740✔
1010
                onColumnResizeIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
11✔
1011
            },
11✔
1012
            [onColumnResizeIn, rowMarkerOffset, columnsIn]
740✔
1013
        )
740✔
1014
    );
740✔
1015

740✔
1016
    const onColumnResizeEnd = whenDefined(
740✔
1017
        onColumnResizeEndIn,
740✔
1018
        React.useCallback<NonNullable<typeof onColumnResizeEndIn>>(
740✔
1019
            (_, w, ind, wg) => {
740✔
1020
                onColumnResizeEndIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
2✔
1021
            },
2✔
1022
            [onColumnResizeEndIn, rowMarkerOffset, columnsIn]
740✔
1023
        )
740✔
1024
    );
740✔
1025

740✔
1026
    const onColumnResizeStart = whenDefined(
740✔
1027
        onColumnResizeStartIn,
740✔
1028
        React.useCallback<NonNullable<typeof onColumnResizeStartIn>>(
740✔
1029
            (_, w, ind, wg) => {
740✔
UNCOV
1030
                onColumnResizeStartIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
×
UNCOV
1031
            },
×
1032
            [onColumnResizeStartIn, rowMarkerOffset, columnsIn]
740✔
1033
        )
740✔
1034
    );
740✔
1035

740✔
1036
    const drawHeader = whenDefined(
740✔
1037
        drawHeaderIn,
740✔
1038
        React.useCallback<NonNullable<typeof drawHeaderIn>>(
740✔
1039
            (args, draw) => {
740✔
UNCOV
1040
                return drawHeaderIn?.({ ...args, columnIndex: args.columnIndex - rowMarkerOffset }, draw) ?? false;
×
UNCOV
1041
            },
×
1042
            [drawHeaderIn, rowMarkerOffset]
740✔
1043
        )
740✔
1044
    );
740✔
1045

740✔
1046
    const drawCell = whenDefined(
740✔
1047
        drawCellIn,
740✔
1048
        React.useCallback<NonNullable<typeof drawCellIn>>(
740✔
1049
            (args, draw) => {
740✔
UNCOV
1050
                return drawCellIn?.({ ...args, col: args.col - rowMarkerOffset }, draw) ?? false;
×
UNCOV
1051
            },
×
1052
            [drawCellIn, rowMarkerOffset]
740✔
1053
        )
740✔
1054
    );
740✔
1055

740✔
1056
    const onDelete = React.useCallback<NonNullable<DataEditorProps["onDelete"]>>(
740✔
1057
        sel => {
740✔
1058
            if (onDeleteIn !== undefined) {
9✔
1059
                const result = onDeleteIn(shiftSelection(sel, -rowMarkerOffset));
5✔
1060
                if (typeof result === "boolean") {
5!
UNCOV
1061
                    return result;
×
UNCOV
1062
                }
×
1063
                return shiftSelection(result, rowMarkerOffset);
5✔
1064
            }
5✔
1065
            return true;
4✔
1066
        },
9✔
1067
        [onDeleteIn, rowMarkerOffset]
740✔
1068
    );
740✔
1069

740✔
1070
    const [setCurrent, setSelectedRows, setSelectedColumns] = useSelectionBehavior(
740✔
1071
        gridSelection,
740✔
1072
        setGridSelection,
740✔
1073
        rangeSelectionBlending,
740✔
1074
        columnSelectionBlending,
740✔
1075
        rowSelectionBlending,
740✔
1076
        rangeSelect,
740✔
1077
        rangeSelectionColumnSpanning
740✔
1078
    );
740✔
1079

740✔
1080
    const mergedTheme = React.useMemo(() => {
740✔
1081
        return mergeAndRealizeTheme(getDataEditorTheme(), theme);
151✔
1082
    }, [theme]);
740✔
1083

740✔
1084
    const [clientSize, setClientSize] = React.useState<readonly [number, number, number]>([0, 0, 0]);
740✔
1085

740✔
1086
    const rendererMap = React.useMemo(() => {
740✔
1087
        if (renderers === undefined) return {};
151!
1088
        const result: Partial<Record<InnerGridCellKind | GridCellKind, InternalCellRenderer<InnerGridCell>>> = {};
151✔
1089
        for (const r of renderers) {
151✔
1090
            result[r.kind] = r;
1,964✔
1091
        }
1,964✔
1092
        return result;
151✔
1093
    }, [renderers]);
740✔
1094

740✔
1095
    const getCellRenderer: <T extends InnerGridCell>(cell: T) => CellRenderer<T> | undefined = React.useCallback(
740✔
1096
        <T extends InnerGridCell>(cell: T) => {
740✔
1097
            if (cell.kind !== GridCellKind.Custom) {
148,221✔
1098
                return rendererMap[cell.kind] as unknown as CellRenderer<T>;
144,491✔
1099
            }
144,491✔
1100
            return additionalRenderers?.find(x => x.isMatch(cell)) as CellRenderer<T>;
148,221✔
1101
        },
148,221✔
1102
        [additionalRenderers, rendererMap]
740✔
1103
    );
740✔
1104

740✔
1105
    // eslint-disable-next-line prefer-const
740✔
1106
    let { sizedColumns: columns, nonGrowWidth } = useColumnSizer(
740✔
1107
        columnsIn,
740✔
1108
        rows,
740✔
1109
        getCellsForSeletionDirect,
740✔
1110
        clientSize[0] - (rowMarkerOffset === 0 ? 0 : rowMarkerWidth) - clientSize[2],
740✔
1111
        minColumnWidth,
740✔
1112
        maxColumnAutoWidth,
740✔
1113
        mergedTheme,
740✔
1114
        getCellRenderer,
740✔
1115
        abortControllerRef.current
740✔
1116
    );
740✔
1117
    if (rowMarkers !== "none") nonGrowWidth += rowMarkerWidth;
740✔
1118

740✔
1119
    const enableGroups = React.useMemo(() => {
740✔
1120
        return columns.some(c => c.group !== undefined);
152✔
1121
    }, [columns]);
740✔
1122

740✔
1123
    const totalHeaderHeight = enableGroups ? headerHeight + groupHeaderHeight : headerHeight;
740✔
1124

740✔
1125
    const numSelectedRows = gridSelection.rows.length;
740✔
1126
    const rowMarkerChecked =
740✔
1127
        rowMarkers === "none" ? undefined : numSelectedRows === 0 ? false : numSelectedRows === rows ? true : undefined;
740✔
1128

740✔
1129
    const mangledCols = React.useMemo(() => {
740✔
1130
        if (rowMarkers === "none") return columns;
166✔
1131
        return [
46✔
1132
            {
46✔
1133
                title: "",
46✔
1134
                width: rowMarkerWidth,
46✔
1135
                icon: undefined,
46✔
1136
                hasMenu: false,
46✔
1137
                style: "normal" as const,
46✔
1138
                themeOverride: rowMarkerTheme,
46✔
1139
                rowMarker: rowMarkerCheckboxStyle,
46✔
1140
                rowMarkerChecked,
46✔
1141
                headerRowMarkerTheme,
46✔
1142
                headerRowMarkerAlwaysVisible,
46✔
1143
                headerRowMarkerDisabled,
46✔
1144
            },
46✔
1145
            ...columns,
46✔
1146
        ];
46✔
1147
    }, [
740✔
1148
        rowMarkers,
740✔
1149
        columns,
740✔
1150
        rowMarkerWidth,
740✔
1151
        rowMarkerTheme,
740✔
1152
        rowMarkerCheckboxStyle,
740✔
1153
        rowMarkerChecked,
740✔
1154
        headerRowMarkerTheme,
740✔
1155
        headerRowMarkerAlwaysVisible,
740✔
1156
        headerRowMarkerDisabled,
740✔
1157
    ]);
740✔
1158

740✔
1159
    const visibleRegionRef = React.useRef<VisibleRegion>({
740✔
1160
        height: 1,
740✔
1161
        width: 1,
740✔
1162
        x: 0,
740✔
1163
        y: 0,
740✔
1164
    });
740✔
1165

740✔
1166
    const hasJustScrolled = React.useRef(false);
740✔
1167

740✔
1168
    const { setVisibleRegion, visibleRegion, scrollRef } = useInitialScrollOffset(
740✔
1169
        scrollOffsetX,
740✔
1170
        scrollOffsetY,
740✔
1171
        rowHeight,
740✔
1172
        visibleRegionRef,
740✔
1173
        () => (hasJustScrolled.current = true)
740✔
1174
    );
740✔
1175

740✔
1176
    visibleRegionRef.current = visibleRegion;
740✔
1177

740✔
1178
    const cellXOffset = visibleRegion.x + rowMarkerOffset;
740✔
1179
    const cellYOffset = visibleRegion.y;
740✔
1180

740✔
1181
    const gridRef = React.useRef<DataGridRef | null>(null);
740✔
1182

740✔
1183
    const focus = React.useCallback((immediate?: boolean) => {
740✔
1184
        if (immediate === true) {
135✔
1185
            gridRef.current?.focus();
12✔
1186
        } else {
135✔
1187
            window.requestAnimationFrame(() => {
123✔
1188
                gridRef.current?.focus();
122✔
1189
            });
123✔
1190
        }
123✔
1191
    }, []);
740✔
1192

740✔
1193
    const mangledRows = showTrailingBlankRow ? rows + 1 : rows;
740✔
1194

740✔
1195
    const mangledOnCellsEdited = React.useCallback<NonNullable<typeof onCellsEdited>>(
740✔
1196
        (items: readonly EditListItem[]) => {
740✔
1197
            const mangledItems =
29✔
1198
                rowMarkerOffset === 0
29✔
1199
                    ? items
24✔
1200
                    : items.map(x => ({
5✔
1201
                          ...x,
29✔
1202
                          location: [x.location[0] - rowMarkerOffset, x.location[1]] as const,
29✔
1203
                      }));
5✔
1204
            const r = onCellsEdited?.(mangledItems);
29✔
1205

29✔
1206
            if (r !== true) {
29✔
1207
                for (const i of mangledItems) onCellEdited?.(i.location, i.value);
28✔
1208
            }
28✔
1209

29✔
1210
            return r;
29✔
1211
        },
29✔
1212
        [onCellEdited, onCellsEdited, rowMarkerOffset]
740✔
1213
    );
740✔
1214

740✔
1215
    const [fillHighlightRegion, setFillHighlightRegion] = React.useState<Rectangle | undefined>();
740✔
1216

740✔
1217
    // this will generally be undefined triggering the memo less often
740✔
1218
    const highlightRange =
740✔
1219
        gridSelection.current !== undefined &&
740✔
1220
        gridSelection.current.range.width * gridSelection.current.range.height > 1
367✔
1221
            ? gridSelection.current.range
44✔
1222
            : undefined;
696✔
1223

740✔
1224
    const highlightFocus = drawFocusRing ? gridSelection.current?.cell : undefined;
740!
1225
    const highlightFocusCol = highlightFocus?.[0];
740✔
1226
    const highlightFocusRow = highlightFocus?.[1];
740✔
1227

740✔
1228
    const highlightRegions = React.useMemo(() => {
740✔
1229
        if (
305✔
1230
            (highlightRegionsIn === undefined || highlightRegionsIn.length === 0) &&
305✔
1231
            (highlightRange ?? highlightFocusCol ?? highlightFocusRow ?? fillHighlightRegion) === undefined
304✔
1232
        )
305✔
1233
            return undefined;
305✔
1234

158✔
1235
        const regions: Highlight[] = [];
158✔
1236

158✔
1237
        if (highlightRegionsIn !== undefined) {
298✔
1238
            for (const r of highlightRegionsIn) {
1✔
1239
                const maxWidth = mangledCols.length - r.range.x - rowMarkerOffset;
1✔
1240
                if (maxWidth > 0) {
1✔
1241
                    regions.push({
1✔
1242
                        color: r.color,
1✔
1243
                        range: {
1✔
1244
                            ...r.range,
1✔
1245
                            x: r.range.x + rowMarkerOffset,
1✔
1246
                            width: Math.min(maxWidth, r.range.width),
1✔
1247
                        },
1✔
1248
                        style: r.style,
1✔
1249
                    });
1✔
1250
                }
1✔
1251
            }
1✔
1252
        }
1✔
1253

158✔
1254
        if (fillHighlightRegion !== undefined) {
298✔
1255
            regions.push({
6✔
1256
                color: withAlpha(mergedTheme.accentColor, 0),
6✔
1257
                range: fillHighlightRegion,
6✔
1258
                style: "dashed",
6✔
1259
            });
6✔
1260
        }
6✔
1261

158✔
1262
        if (highlightRange !== undefined) {
298✔
1263
            regions.push({
30✔
1264
                color: withAlpha(mergedTheme.accentColor, 0.5),
30✔
1265
                range: highlightRange,
30✔
1266
                style: "solid-outline",
30✔
1267
            });
30✔
1268
        }
30✔
1269

158✔
1270
        if (highlightFocusCol !== undefined && highlightFocusRow !== undefined) {
305✔
1271
            regions.push({
157✔
1272
                color: mergedTheme.accentColor,
157✔
1273
                range: {
157✔
1274
                    x: highlightFocusCol,
157✔
1275
                    y: highlightFocusRow,
157✔
1276
                    width: 1,
157✔
1277
                    height: 1,
157✔
1278
                },
157✔
1279
                style: "solid-outline",
157✔
1280
            });
157✔
1281
        }
157✔
1282

158✔
1283
        return regions.length > 0 ? regions : undefined;
305!
1284
    }, [
740✔
1285
        fillHighlightRegion,
740✔
1286
        highlightRange,
740✔
1287
        highlightFocusCol,
740✔
1288
        highlightFocusRow,
740✔
1289
        highlightRegionsIn,
740✔
1290
        mangledCols.length,
740✔
1291
        mergedTheme.accentColor,
740✔
1292
        rowMarkerOffset,
740✔
1293
    ]);
740✔
1294

740✔
1295
    const mangledColsRef = React.useRef(mangledCols);
740✔
1296
    mangledColsRef.current = mangledCols;
740✔
1297
    const getMangledCellContent = React.useCallback(
740✔
1298
        ([col, row]: Item, forceStrict: boolean = false): InnerGridCell => {
740✔
1299
            const isTrailing = showTrailingBlankRow && row === mangledRows - 1;
149,344✔
1300
            const isRowMarkerCol = col === 0 && hasRowMarkers;
149,344✔
1301
            if (isRowMarkerCol) {
149,344✔
1302
                if (isTrailing) {
2,122✔
1303
                    return loadingCell;
65✔
1304
                }
65✔
1305
                const mappedRow = rowNumberMapper(row);
2,057✔
1306
                if (mappedRow === undefined) return loadingCell;
2,122!
1307
                return {
2,057✔
1308
                    kind: InnerGridCellKind.Marker,
2,057✔
1309
                    allowOverlay: false,
2,057✔
1310
                    checkboxStyle: rowMarkerCheckboxStyle,
2,057✔
1311
                    checked: gridSelection?.rows.hasIndex(row) === true,
2,122✔
1312
                    markerKind: rowMarkers === "clickable-number" ? "number" : rowMarkers,
2,122!
1313
                    row: rowMarkerStartIndex + mappedRow,
2,122✔
1314
                    drawHandle: onRowMoved !== undefined,
2,122✔
1315
                    cursor: rowMarkers === "clickable-number" ? "pointer" : undefined,
2,122!
1316
                };
2,122✔
1317
            } else if (isTrailing) {
149,344✔
1318
                //If the grid is empty, we will return text
3,909✔
1319
                const isFirst = col === rowMarkerOffset;
3,909✔
1320

3,909✔
1321
                const maybeFirstColumnHint = isFirst ? trailingRowOptions?.hint ?? "" : "";
3,909✔
1322
                const c = mangledColsRef.current[col];
3,909✔
1323

3,909✔
1324
                if (c?.trailingRowOptions?.disabled === true) {
3,909!
UNCOV
1325
                    return loadingCell;
×
1326
                } else {
3,909✔
1327
                    const hint = c?.trailingRowOptions?.hint ?? maybeFirstColumnHint;
3,909!
1328
                    const icon = c?.trailingRowOptions?.addIcon ?? trailingRowOptions?.addIcon;
3,909!
1329
                    return {
3,909✔
1330
                        kind: InnerGridCellKind.NewRow,
3,909✔
1331
                        hint,
3,909✔
1332
                        allowOverlay: false,
3,909✔
1333
                        icon,
3,909✔
1334
                    };
3,909✔
1335
                }
3,909✔
1336
            } else {
147,222✔
1337
                const outerCol = col - rowMarkerOffset;
143,313✔
1338
                if (forceStrict || experimental?.strict === true) {
143,313✔
1339
                    const vr = visibleRegionRef.current;
26,505✔
1340
                    const isOutsideMainArea =
26,505✔
1341
                        vr.x > outerCol ||
26,505✔
1342
                        outerCol > vr.x + vr.width ||
26,505✔
1343
                        vr.y > row ||
26,505✔
1344
                        row > vr.y + vr.height ||
26,505✔
1345
                        row >= rowsRef.current;
26,505✔
1346
                    const isSelected = outerCol === vr.extras?.selected?.[0] && row === vr.extras?.selected[1];
26,505✔
1347
                    let isInFreezeArea = false;
26,505✔
1348
                    if (vr.extras?.freezeRegions !== undefined) {
26,505✔
1349
                        for (const fr of vr.extras.freezeRegions) {
26,505!
UNCOV
1350
                            if (pointInRect(fr, outerCol, row)) {
×
UNCOV
1351
                                isInFreezeArea = true;
×
1352
                                break;
×
1353
                            }
×
UNCOV
1354
                        }
×
1355
                    }
26,505✔
1356

26,505✔
1357
                    if (isOutsideMainArea && !isSelected && !isInFreezeArea) {
26,505!
1358
                        return loadingCell;
×
1359
                    }
×
1360
                }
26,505✔
1361
                let result = getCellContent([outerCol, row]);
143,313✔
1362
                if (rowMarkerOffset !== 0 && result.span !== undefined) {
143,313!
UNCOV
1363
                    result = {
×
UNCOV
1364
                        ...result,
×
UNCOV
1365
                        span: [result.span[0] + rowMarkerOffset, result.span[1] + rowMarkerOffset],
×
UNCOV
1366
                    };
×
UNCOV
1367
                }
×
1368
                return result;
143,313✔
1369
            }
143,313✔
1370
        },
149,344✔
1371
        [
740✔
1372
            showTrailingBlankRow,
740✔
1373
            mangledRows,
740✔
1374
            hasRowMarkers,
740✔
1375
            rowNumberMapper,
740✔
1376
            rowMarkerCheckboxStyle,
740✔
1377
            gridSelection?.rows,
740✔
1378
            rowMarkers,
740✔
1379
            rowMarkerStartIndex,
740✔
1380
            onRowMoved,
740✔
1381
            rowMarkerOffset,
740✔
1382
            trailingRowOptions?.hint,
740✔
1383
            trailingRowOptions?.addIcon,
740✔
1384
            experimental?.strict,
740✔
1385
            getCellContent,
740✔
1386
        ]
740✔
1387
    );
740✔
1388

740✔
1389
    const mangledGetGroupDetails = React.useCallback<NonNullable<DataEditorProps["getGroupDetails"]>>(
740✔
1390
        group => {
740✔
1391
            let result = getGroupDetails?.(group) ?? { name: group };
8,505✔
1392
            if (onGroupHeaderRenamed !== undefined && group !== "") {
8,505✔
1393
                result = {
88✔
1394
                    icon: result.icon,
88✔
1395
                    name: result.name,
88✔
1396
                    overrideTheme: result.overrideTheme,
88✔
1397
                    actions: [
88✔
1398
                        ...(result.actions ?? []),
88✔
1399
                        {
88✔
1400
                            title: "Rename",
88✔
1401
                            icon: "renameIcon",
88✔
1402
                            onClick: e =>
88✔
1403
                                setRenameGroup({
2✔
1404
                                    group: result.name,
2✔
1405
                                    bounds: e.bounds,
2✔
1406
                                }),
2✔
1407
                        },
88✔
1408
                    ],
88✔
1409
                };
88✔
1410
            }
88✔
1411
            return result;
8,505✔
1412
        },
8,505✔
1413
        [getGroupDetails, onGroupHeaderRenamed]
740✔
1414
    );
740✔
1415

740✔
1416
    const setOverlaySimple = React.useCallback(
740✔
1417
        (val: Omit<NonNullable<typeof overlay>, "theme">) => {
740✔
1418
            const [col, row] = val.cell;
25✔
1419
            const column = mangledCols[col];
25✔
1420
            const groupTheme =
25✔
1421
                column?.group !== undefined ? mangledGetGroupDetails(column.group)?.overrideTheme : undefined;
25!
1422
            const colTheme = column?.themeOverride;
25✔
1423
            const rowTheme = getRowThemeOverride?.(row);
25!
1424

25✔
1425
            setOverlay({
25✔
1426
                ...val,
25✔
1427
                theme: mergeAndRealizeTheme(mergedTheme, groupTheme, colTheme, rowTheme, val.content.themeOverride),
25✔
1428
            });
25✔
1429
        },
25✔
1430
        [getRowThemeOverride, mangledCols, mangledGetGroupDetails, mergedTheme]
740✔
1431
    );
740✔
1432

740✔
1433
    const reselect = React.useCallback(
740✔
1434
        (bounds: Rectangle, fromKeyboard: boolean, initialValue?: string) => {
740✔
1435
            if (gridSelection.current === undefined) return;
26!
1436

26✔
1437
            const [col, row] = gridSelection.current.cell;
26✔
1438
            const c = getMangledCellContent([col, row]);
26✔
1439
            if (c.kind !== GridCellKind.Boolean && c.allowOverlay) {
26✔
1440
                let content = c;
24✔
1441
                if (initialValue !== undefined) {
24✔
1442
                    switch (content.kind) {
13✔
1443
                        case GridCellKind.Number: {
13!
1444
                            const d = maybe(() => (initialValue === "-" ? -0 : Number.parseFloat(initialValue)), 0);
×
UNCOV
1445
                            content = {
×
UNCOV
1446
                                ...content,
×
UNCOV
1447
                                data: Number.isNaN(d) ? 0 : d,
×
UNCOV
1448
                            };
×
UNCOV
1449
                            break;
×
UNCOV
1450
                        }
×
1451
                        case GridCellKind.Text:
13✔
1452
                        case GridCellKind.Markdown:
13✔
1453
                        case GridCellKind.Uri:
13✔
1454
                            content = {
13✔
1455
                                ...content,
13✔
1456
                                data: initialValue,
13✔
1457
                            };
13✔
1458
                            break;
13✔
1459
                    }
13✔
1460
                }
13✔
1461

24✔
1462
                setOverlaySimple({
24✔
1463
                    target: bounds,
24✔
1464
                    content,
24✔
1465
                    initialValue,
24✔
1466
                    cell: [col, row],
24✔
1467
                    highlight: initialValue === undefined,
24✔
1468
                    forceEditMode: initialValue !== undefined,
24✔
1469
                });
24✔
1470
            } else if (c.kind === GridCellKind.Boolean && fromKeyboard && c.readonly !== true) {
26✔
1471
                mangledOnCellsEdited([
1✔
1472
                    {
1✔
1473
                        location: gridSelection.current.cell,
1✔
1474
                        value: {
1✔
1475
                            ...c,
1✔
1476
                            data: toggleBoolean(c.data),
1✔
1477
                        },
1✔
1478
                    },
1✔
1479
                ]);
1✔
1480
                gridRef.current?.damage([{ cell: gridSelection.current.cell }]);
1✔
1481
            }
1✔
1482
        },
26✔
1483
        [getMangledCellContent, gridSelection, mangledOnCellsEdited, setOverlaySimple]
740✔
1484
    );
740✔
1485

740✔
1486
    const focusOnRowFromTrailingBlankRow = React.useCallback(
740✔
1487
        (col: number, row: number) => {
740✔
1488
            const bounds = gridRef.current?.getBounds(col, row);
1✔
1489
            if (bounds === undefined || scrollRef.current === null) {
1!
1490
                return;
×
UNCOV
1491
            }
×
1492

1✔
1493
            const content = getMangledCellContent([col, row]);
1✔
1494
            if (!content.allowOverlay) {
1!
UNCOV
1495
                return;
×
UNCOV
1496
            }
×
1497

1✔
1498
            setOverlaySimple({
1✔
1499
                target: bounds,
1✔
1500
                content,
1✔
1501
                initialValue: undefined,
1✔
1502
                highlight: true,
1✔
1503
                cell: [col, row],
1✔
1504
                forceEditMode: true,
1✔
1505
            });
1✔
1506
        },
1✔
1507
        [getMangledCellContent, scrollRef, setOverlaySimple]
740✔
1508
    );
740✔
1509

740✔
1510
    const scrollTo = React.useCallback<ScrollToFn>(
740✔
1511
        (col, row, dir = "both", paddingX = 0, paddingY = 0, options = undefined): void => {
740✔
1512
            if (scrollRef.current !== null) {
53✔
1513
                const grid = gridRef.current;
53✔
1514
                const canvas = canvasRef.current;
53✔
1515

53✔
1516
                const trueCol = typeof col !== "number" ? (col.unit === "cell" ? col.amount : undefined) : col;
53!
1517
                const trueRow = typeof row !== "number" ? (row.unit === "cell" ? row.amount : undefined) : row;
53!
1518
                const desiredX = typeof col !== "number" && col.unit === "px" ? col.amount : undefined;
53!
1519
                const desiredY = typeof row !== "number" && row.unit === "px" ? row.amount : undefined;
53✔
1520
                if (grid !== null && canvas !== null) {
53✔
1521
                    let targetRect: Rectangle = {
53✔
1522
                        x: 0,
53✔
1523
                        y: 0,
53✔
1524
                        width: 0,
53✔
1525
                        height: 0,
53✔
1526
                    };
53✔
1527

53✔
1528
                    let scrollX = 0;
53✔
1529
                    let scrollY = 0;
53✔
1530

53✔
1531
                    if (trueCol !== undefined || trueRow !== undefined) {
53!
1532
                        targetRect = grid.getBounds((trueCol ?? 0) + rowMarkerOffset, trueRow ?? 0) ?? targetRect;
53!
1533
                        if (targetRect.width === 0 || targetRect.height === 0) return;
53!
1534
                    }
53✔
1535

53✔
1536
                    const scrollBounds = canvas.getBoundingClientRect();
53✔
1537
                    const scale = scrollBounds.width / canvas.offsetWidth;
53✔
1538

53✔
1539
                    if (desiredX !== undefined) {
53!
UNCOV
1540
                        targetRect = {
×
UNCOV
1541
                            ...targetRect,
×
UNCOV
1542
                            x: desiredX - scrollBounds.left - scrollRef.current.scrollLeft,
×
UNCOV
1543
                            width: 1,
×
UNCOV
1544
                        };
×
UNCOV
1545
                    }
×
1546
                    if (desiredY !== undefined) {
53✔
1547
                        targetRect = {
4✔
1548
                            ...targetRect,
4✔
1549
                            y: desiredY + scrollBounds.top - scrollRef.current.scrollTop,
4✔
1550
                            height: 1,
4✔
1551
                        };
4✔
1552
                    }
4✔
1553

53✔
1554
                    if (targetRect !== undefined) {
53✔
1555
                        const bounds = {
53✔
1556
                            x: targetRect.x - paddingX,
53✔
1557
                            y: targetRect.y - paddingY,
53✔
1558
                            width: targetRect.width + 2 * paddingX,
53✔
1559
                            height: targetRect.height + 2 * paddingY,
53✔
1560
                        };
53✔
1561

53✔
1562
                        let frozenWidth = 0;
53✔
1563
                        for (let i = 0; i < freezeColumns; i++) {
53!
UNCOV
1564
                            frozenWidth += columns[i].width;
×
UNCOV
1565
                        }
×
1566
                        let trailingRowHeight = 0;
53✔
1567
                        const freezeTrailingRowsEffective = freezeTrailingRows + (lastRowSticky ? 1 : 0);
53✔
1568
                        if (freezeTrailingRowsEffective > 0) {
53✔
1569
                            trailingRowHeight = getFreezeTrailingHeight(
51✔
1570
                                mangledRows,
51✔
1571
                                freezeTrailingRowsEffective,
51✔
1572
                                rowHeight
51✔
1573
                            );
51✔
1574
                        }
51✔
1575

53✔
1576
                        // scrollBounds is already scaled
53✔
1577
                        let sLeft = frozenWidth * scale + scrollBounds.left + rowMarkerOffset * rowMarkerWidth * scale;
53✔
1578
                        let sRight = scrollBounds.right;
53✔
1579
                        let sTop = scrollBounds.top + totalHeaderHeight * scale;
53✔
1580
                        let sBottom = scrollBounds.bottom - trailingRowHeight * scale;
53✔
1581

53✔
1582
                        const minx = targetRect.width + paddingX * 2;
53✔
1583
                        switch (options?.hAlign) {
53✔
1584
                            case "start":
53!
1585
                                sRight = sLeft + minx;
×
1586
                                break;
×
1587
                            case "end":
53!
UNCOV
1588
                                sLeft = sRight - minx;
×
UNCOV
1589
                                break;
×
1590
                            case "center":
53!
UNCOV
1591
                                sLeft = Math.floor((sLeft + sRight) / 2) - minx / 2;
×
UNCOV
1592
                                sRight = sLeft + minx;
×
UNCOV
1593
                                break;
×
1594
                        }
53✔
1595

53✔
1596
                        const miny = targetRect.height + paddingY * 2;
53✔
1597
                        switch (options?.vAlign) {
53✔
1598
                            case "start":
53✔
1599
                                sBottom = sTop + miny;
1✔
1600
                                break;
1✔
1601
                            case "end":
53✔
1602
                                sTop = sBottom - miny;
1✔
1603
                                break;
1✔
1604
                            case "center":
53✔
1605
                                sTop = Math.floor((sTop + sBottom) / 2) - miny / 2;
1✔
1606
                                sBottom = sTop + miny;
1✔
1607
                                break;
1✔
1608
                        }
53✔
1609

53✔
1610
                        if (sLeft > bounds.x) {
53!
1611
                            scrollX = bounds.x - sLeft;
×
1612
                        } else if (sRight < bounds.x + bounds.width) {
53✔
1613
                            scrollX = bounds.x + bounds.width - sRight;
7✔
1614
                        }
7✔
1615

53✔
1616
                        if (sTop > bounds.y) {
53!
UNCOV
1617
                            scrollY = bounds.y - sTop;
×
1618
                        } else if (sBottom < bounds.y + bounds.height) {
53✔
1619
                            scrollY = bounds.y + bounds.height - sBottom;
16✔
1620
                        }
16✔
1621

53✔
1622
                        if (dir === "vertical" || (typeof col === "number" && col < freezeColumns)) {
53✔
1623
                            scrollX = 0;
4✔
1624
                        } else if (
4✔
1625
                            dir === "horizontal" ||
49✔
1626
                            (typeof row === "number" && row >= mangledRows - freezeTrailingRowsEffective)
41✔
1627
                        ) {
49✔
1628
                            scrollY = 0;
10✔
1629
                        }
10✔
1630

53✔
1631
                        if (scrollX !== 0 || scrollY !== 0) {
53✔
1632
                            // Remove scaling as scrollTo method is unaffected by transform scale.
20✔
1633
                            if (scale !== 1) {
20!
UNCOV
1634
                                scrollX /= scale;
×
UNCOV
1635
                                scrollY /= scale;
×
UNCOV
1636
                            }
×
1637
                            scrollRef.current.scrollTo({
20✔
1638
                                left: scrollX + scrollRef.current.scrollLeft,
20✔
1639
                                top: scrollY + scrollRef.current.scrollTop,
20✔
1640
                                behavior: options?.behavior ?? "auto",
20✔
1641
                            });
20✔
1642
                        }
20✔
1643
                    }
53✔
1644
                }
53✔
1645
            }
53✔
1646
        },
53✔
1647
        [
740✔
1648
            rowMarkerOffset,
740✔
1649
            freezeTrailingRows,
740✔
1650
            rowMarkerWidth,
740✔
1651
            scrollRef,
740✔
1652
            totalHeaderHeight,
740✔
1653
            freezeColumns,
740✔
1654
            columns,
740✔
1655
            mangledRows,
740✔
1656
            lastRowSticky,
740✔
1657
            rowHeight,
740✔
1658
        ]
740✔
1659
    );
740✔
1660

740✔
1661
    const focusCallback = React.useRef(focusOnRowFromTrailingBlankRow);
740✔
1662
    const getCellContentRef = React.useRef(getCellContent);
740✔
1663

740✔
1664
    focusCallback.current = focusOnRowFromTrailingBlankRow;
740✔
1665
    getCellContentRef.current = getCellContent;
740✔
1666

740✔
1667
    const rowsRef = React.useRef(rows);
740✔
1668
    rowsRef.current = rows;
740✔
1669

740✔
1670
    const colsRef = React.useRef(mangledCols.length);
740✔
1671
    colsRef.current = mangledCols.length;
740✔
1672

740✔
1673
    const appendRow = React.useCallback(
740✔
1674
        async (col: number, openOverlay: boolean = true, behavior?: ScrollBehavior): Promise<void> => {
740✔
1675
            const c = mangledCols[col];
2✔
1676
            if (c?.trailingRowOptions?.disabled === true) {
2!
UNCOV
1677
                return;
×
1678
            }
×
1679
            const appendResult = onRowAppended?.();
2✔
1680

2✔
1681
            let r: "top" | "bottom" | number | undefined = undefined;
2✔
1682
            let bottom = true;
2✔
1683
            if (appendResult !== undefined) {
2!
UNCOV
1684
                r = await appendResult;
×
UNCOV
1685
                if (r === "top") bottom = false;
×
UNCOV
1686
                if (typeof r === "number") bottom = false;
×
UNCOV
1687
            }
×
1688

2✔
1689
            let backoff = 0;
2✔
1690
            const doFocus = () => {
2✔
1691
                if (rowsRef.current <= rows) {
4✔
1692
                    if (backoff < 500) {
2✔
1693
                        window.setTimeout(doFocus, backoff);
2✔
1694
                    }
2✔
1695
                    backoff = 50 + backoff * 2;
2✔
1696
                    return;
2✔
1697
                }
2✔
1698

2✔
1699
                const row = typeof r === "number" ? r : bottom ? rows : 0;
4!
1700
                scrollToRef.current(col - rowMarkerOffset, row, "both", 0, 0, behavior ? { behavior } : undefined);
4!
1701
                setCurrent(
4✔
1702
                    {
4✔
1703
                        cell: [col, row],
4✔
1704
                        range: {
4✔
1705
                            x: col,
4✔
1706
                            y: row,
4✔
1707
                            width: 1,
4✔
1708
                            height: 1,
4✔
1709
                        },
4✔
1710
                    },
4✔
1711
                    false,
4✔
1712
                    false,
4✔
1713
                    "edit"
4✔
1714
                );
4✔
1715

4✔
1716
                const cell = getCellContentRef.current([col - rowMarkerOffset, row]);
4✔
1717
                if (cell.allowOverlay && isReadWriteCell(cell) && cell.readonly !== true && openOverlay) {
4✔
1718
                    // wait for scroll to have a chance to process
1✔
1719
                    window.setTimeout(() => {
1✔
1720
                        focusCallback.current(col, row);
1✔
1721
                    }, 0);
1✔
1722
                }
1✔
1723
            };
4✔
1724
            // Queue up to allow the consumer to react to the event and let us check if they did
2✔
1725
            doFocus();
2✔
1726
        },
2✔
1727
        [mangledCols, onRowAppended, rowMarkerOffset, rows, setCurrent]
740✔
1728
    );
740✔
1729

740✔
1730
    const appendColumn = React.useCallback(
740✔
1731
        async (row: number, openOverlay: boolean = true): Promise<void> => {
740✔
1732
            const appendResult = onColumnAppended?.();
1✔
1733

1✔
1734
            let r: "left" | "right" | number | undefined = undefined;
1✔
1735
            let right = true;
1✔
1736
            if (appendResult !== undefined) {
1!
NEW
1737
                r = await appendResult;
×
NEW
1738
                if (r === "left") right = false;
×
NEW
1739
                if (typeof r === "number") right = false;
×
NEW
1740
            }
×
1741

1✔
1742
            let backoff = 0;
1✔
1743
            const doFocus = () => {
1✔
1744
                if (colsRef.current <= mangledCols.length) {
2✔
1745
                    if (backoff < 500) {
1✔
1746
                        window.setTimeout(doFocus, backoff);
1✔
1747
                    }
1✔
1748
                    backoff = 50 + backoff * 2;
1✔
1749
                    return;
1✔
1750
                }
1✔
1751

1✔
1752
                const col = typeof r === "number" ? r : right ? mangledCols.length : 0;
2!
1753
                scrollTo(col - rowMarkerOffset, row);
2✔
1754
                setCurrent(
2✔
1755
                    {
2✔
1756
                        cell: [col, row],
2✔
1757
                        range: {
2✔
1758
                            x: col,
2✔
1759
                            y: row,
2✔
1760
                            width: 1,
2✔
1761
                            height: 1,
2✔
1762
                        },
2✔
1763
                    },
2✔
1764
                    false,
2✔
1765
                    false,
2✔
1766
                    "edit"
2✔
1767
                );
2✔
1768

2✔
1769
                const cell = getCellContentRef.current([col - rowMarkerOffset, row]);
2✔
1770
                if (cell.allowOverlay && isReadWriteCell(cell) && cell.readonly !== true && openOverlay) {
2!
NEW
1771
                    window.setTimeout(() => {
×
NEW
1772
                        focusCallback.current(col, row);
×
NEW
1773
                    }, 0);
×
NEW
1774
                }
×
1775
            };
2✔
1776
            doFocus();
1✔
1777
        },
1✔
1778
        [mangledCols, onColumnAppended, rowMarkerOffset, scrollTo, setCurrent]
740✔
1779
    );
740✔
1780

740✔
1781
    const getCustomNewRowTargetColumn = React.useCallback(
740✔
1782
        (col: number): number | undefined => {
740✔
1783
            const customTargetColumn =
1✔
1784
                columns[col]?.trailingRowOptions?.targetColumn ?? trailingRowOptions?.targetColumn;
1!
1785

1✔
1786
            if (typeof customTargetColumn === "number") {
1!
1787
                const customTargetOffset = hasRowMarkers ? 1 : 0;
×
1788
                return customTargetColumn + customTargetOffset;
×
1789
            }
×
1790

1✔
1791
            if (typeof customTargetColumn === "object") {
1!
UNCOV
1792
                const maybeIndex = columnsIn.indexOf(customTargetColumn);
×
UNCOV
1793
                if (maybeIndex >= 0) {
×
UNCOV
1794
                    const customTargetOffset = hasRowMarkers ? 1 : 0;
×
UNCOV
1795
                    return maybeIndex + customTargetOffset;
×
UNCOV
1796
                }
×
UNCOV
1797
            }
×
1798

1✔
1799
            return undefined;
1✔
1800
        },
1✔
1801
        [columns, columnsIn, hasRowMarkers, trailingRowOptions?.targetColumn]
740✔
1802
    );
740✔
1803

740✔
1804
    const lastSelectedRowRef = React.useRef<number>();
740✔
1805
    const lastSelectedColRef = React.useRef<number>();
740✔
1806

740✔
1807
    const themeForCell = React.useCallback(
740✔
1808
        (cell: InnerGridCell, pos: Item): FullTheme => {
740✔
1809
            const [col, row] = pos;
28✔
1810
            return mergeAndRealizeTheme(
28✔
1811
                mergedTheme,
28✔
1812
                mangledCols[col]?.themeOverride,
28✔
1813
                getRowThemeOverride?.(row),
28!
1814
                cell.themeOverride
28✔
1815
            );
28✔
1816
        },
28✔
1817
        [getRowThemeOverride, mangledCols, mergedTheme]
740✔
1818
    );
740✔
1819

740✔
1820
    const { mapper } = useRowGrouping(rowGrouping, rowsIn);
740✔
1821

740✔
1822
    const rowGroupingNavBehavior = rowGrouping?.navigationBehavior;
740!
1823

740✔
1824
    const handleSelect = React.useCallback(
740✔
1825
        (args: GridMouseEventArgs) => {
740✔
1826
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
127!
1827
            const isMultiRow = isMultiKey && rowSelect === "multi";
127✔
1828
            const isMultiCol = isMultiKey && columnSelect === "multi";
127✔
1829
            const [col, row] = args.location;
127✔
1830
            const selectedColumns = gridSelection.columns;
127✔
1831
            const selectedRows = gridSelection.rows;
127✔
1832
            const [cellCol, cellRow] = gridSelection.current?.cell ?? [];
127✔
1833
            // eslint-disable-next-line unicorn/prefer-switch
127✔
1834
            if (args.kind === "cell") {
127✔
1835
                lastSelectedColRef.current = undefined;
111✔
1836

111✔
1837
                lastMouseSelectLocation.current = [col, row];
111✔
1838

111✔
1839
                if (col === 0 && hasRowMarkers) {
111✔
1840
                    if (
15✔
1841
                        (showTrailingBlankRow === true && row === rows) ||
15✔
1842
                        rowMarkers === "number" ||
15✔
1843
                        rowSelect === "none"
14✔
1844
                    )
15✔
1845
                        return;
15✔
1846

14✔
1847
                    const markerCell = getMangledCellContent(args.location);
14✔
1848
                    if (markerCell.kind !== InnerGridCellKind.Marker) {
15!
1849
                        return;
×
1850
                    }
✔
1851

14✔
1852
                    if (onRowMoved !== undefined) {
15!
1853
                        const renderer = getCellRenderer(markerCell);
×
1854
                        assert(renderer?.kind === InnerGridCellKind.Marker);
×
1855
                        const postClick = renderer?.onClick?.({
×
1856
                            ...args,
×
1857
                            cell: markerCell,
×
1858
                            posX: args.localEventX,
×
1859
                            posY: args.localEventY,
×
UNCOV
1860
                            bounds: args.bounds,
×
UNCOV
1861
                            theme: themeForCell(markerCell, args.location),
×
UNCOV
1862
                            preventDefault: () => undefined,
×
UNCOV
1863
                        }) as MarkerCell | undefined;
×
UNCOV
1864
                        if (postClick === undefined || postClick.checked === markerCell.checked) return;
×
UNCOV
1865
                    }
✔
1866

14✔
1867
                    setOverlay(undefined);
14✔
1868
                    focus();
14✔
1869
                    const isSelected = selectedRows.hasIndex(row);
14✔
1870

14✔
1871
                    const lastHighlighted = lastSelectedRowRef.current;
14✔
1872
                    if (
14✔
1873
                        rowSelect === "multi" &&
14✔
1874
                        (args.shiftKey || args.isLongTouch === true) &&
8✔
1875
                        lastHighlighted !== undefined &&
1✔
1876
                        selectedRows.hasIndex(lastHighlighted)
1✔
1877
                    ) {
15✔
1878
                        const newSlice: Slice = [Math.min(lastHighlighted, row), Math.max(lastHighlighted, row) + 1];
1✔
1879

1✔
1880
                        if (isMultiRow || rowSelectionMode === "multi") {
1!
UNCOV
1881
                            setSelectedRows(undefined, newSlice, true);
×
1882
                        } else {
1✔
1883
                            setSelectedRows(CompactSelection.fromSingleSelection(newSlice), undefined, isMultiRow);
1✔
1884
                        }
1✔
1885
                    } else if (rowSelect === "multi" && (isMultiRow || args.isTouch || rowSelectionMode === "multi")) {
15✔
1886
                        if (isSelected) {
3✔
1887
                            setSelectedRows(selectedRows.remove(row), undefined, true);
1✔
1888
                        } else {
2✔
1889
                            setSelectedRows(undefined, row, true);
2✔
1890
                            lastSelectedRowRef.current = row;
2✔
1891
                        }
2✔
1892
                    } else if (isSelected && selectedRows.length === 1) {
13✔
1893
                        setSelectedRows(CompactSelection.empty(), undefined, isMultiKey);
1✔
1894
                    } else {
10✔
1895
                        setSelectedRows(CompactSelection.fromSingleSelection(row), undefined, isMultiKey);
9✔
1896
                        lastSelectedRowRef.current = row;
9✔
1897
                    }
9✔
1898
                } else if (col >= rowMarkerOffset && showTrailingBlankRow && row === rows) {
111✔
1899
                    const customTargetColumn = getCustomNewRowTargetColumn(col);
1✔
1900
                    void appendRow(customTargetColumn ?? col);
1✔
1901
                } else {
96✔
1902
                    if (cellCol !== col || cellRow !== row) {
95✔
1903
                        const cell = getMangledCellContent(args.location);
89✔
1904
                        const renderer = getCellRenderer(cell);
89✔
1905

89✔
1906
                        if (renderer?.onSelect !== undefined) {
89✔
1907
                            let prevented = false;
7✔
1908
                            renderer.onSelect({
7✔
1909
                                ...args,
7✔
1910
                                cell,
7✔
1911
                                posX: args.localEventX,
7✔
1912
                                posY: args.localEventY,
7✔
1913
                                bounds: args.bounds,
7✔
1914
                                preventDefault: () => (prevented = true),
7✔
1915
                                theme: themeForCell(cell, args.location),
7✔
1916
                            });
7✔
1917
                            if (prevented) {
7✔
1918
                                return;
4✔
1919
                            }
4✔
1920
                        }
7✔
1921

85✔
1922
                        if (rowGroupingNavBehavior === "block" && mapper(row).isGroupHeader) {
89!
UNCOV
1923
                            return;
×
UNCOV
1924
                        }
✔
1925

85✔
1926
                        const isLastStickyRow = lastRowSticky && row === rows;
85✔
1927

89✔
1928
                        const startedFromLastSticky =
89✔
1929
                            lastRowSticky && gridSelection !== undefined && gridSelection.current?.cell[1] === rows;
89✔
1930

89✔
1931
                        if (
89✔
1932
                            (args.shiftKey || args.isLongTouch === true) &&
89✔
1933
                            cellCol !== undefined &&
6✔
1934
                            cellRow !== undefined &&
6✔
1935
                            gridSelection.current !== undefined &&
6✔
1936
                            !startedFromLastSticky
6✔
1937
                        ) {
89✔
1938
                            if (isLastStickyRow) {
6!
UNCOV
1939
                                // If we're making a selection and shift click in to the last sticky row,
×
UNCOV
1940
                                // just drop the event. Don't kill the selection.
×
UNCOV
1941
                                return;
×
UNCOV
1942
                            }
×
1943

6✔
1944
                            const left = Math.min(col, cellCol);
6✔
1945
                            const right = Math.max(col, cellCol);
6✔
1946
                            const top = Math.min(row, cellRow);
6✔
1947
                            const bottom = Math.max(row, cellRow);
6✔
1948
                            setCurrent(
6✔
1949
                                {
6✔
1950
                                    ...gridSelection.current,
6✔
1951
                                    range: {
6✔
1952
                                        x: left,
6✔
1953
                                        y: top,
6✔
1954
                                        width: right - left + 1,
6✔
1955
                                        height: bottom - top + 1,
6✔
1956
                                    },
6✔
1957
                                },
6✔
1958
                                true,
6✔
1959
                                isMultiKey,
6✔
1960
                                "click"
6✔
1961
                            );
6✔
1962
                            lastSelectedRowRef.current = undefined;
6✔
1963
                            focus();
6✔
1964
                        } else {
89✔
1965
                            setCurrent(
79✔
1966
                                {
79✔
1967
                                    cell: [col, row],
79✔
1968
                                    range: { x: col, y: row, width: 1, height: 1 },
79✔
1969
                                },
79✔
1970
                                true,
79✔
1971
                                isMultiKey,
79✔
1972
                                "click"
79✔
1973
                            );
79✔
1974
                            lastSelectedRowRef.current = undefined;
79✔
1975
                            setOverlay(undefined);
79✔
1976
                            focus();
79✔
1977
                        }
79✔
1978
                    }
89✔
1979
                }
95✔
1980
            } else if (args.kind === "header") {
127✔
1981
                lastMouseSelectLocation.current = [col, row];
11✔
1982
                setOverlay(undefined);
11✔
1983
                if (hasRowMarkers && col === 0) {
11✔
1984
                    lastSelectedRowRef.current = undefined;
3✔
1985
                    lastSelectedColRef.current = undefined;
3✔
1986
                    if (!headerRowMarkerDisabled && rowSelect === "multi") {
3✔
1987
                        if (selectedRows.length !== rows) {
3✔
1988
                            setSelectedRows(CompactSelection.fromSingleSelection([0, rows]), undefined, isMultiKey);
2✔
1989
                        } else {
3✔
1990
                            setSelectedRows(CompactSelection.empty(), undefined, isMultiKey);
1✔
1991
                        }
1✔
1992
                        focus();
3✔
1993
                    }
3✔
1994
                } else {
11✔
1995
                    const lastCol = lastSelectedColRef.current;
8✔
1996
                    if (
8✔
1997
                        columnSelect === "multi" &&
8✔
1998
                        (args.shiftKey || args.isLongTouch === true) &&
7!
1999
                        lastCol !== undefined &&
×
2000
                        selectedColumns.hasIndex(lastCol)
×
2001
                    ) {
8!
2002
                        const newSlice: Slice = [Math.min(lastCol, col), Math.max(lastCol, col) + 1];
×
UNCOV
2003

×
UNCOV
2004
                        if (isMultiCol) {
×
2005
                            setSelectedColumns(undefined, newSlice, isMultiKey);
×
2006
                        } else {
×
UNCOV
2007
                            setSelectedColumns(CompactSelection.fromSingleSelection(newSlice), undefined, isMultiKey);
×
UNCOV
2008
                        }
×
2009
                    } else if (isMultiCol) {
8✔
2010
                        if (selectedColumns.hasIndex(col)) {
1!
UNCOV
2011
                            // If the column is already selected, deselect that column:
×
UNCOV
2012
                            setSelectedColumns(selectedColumns.remove(col), undefined, isMultiKey);
×
2013
                        } else {
1✔
2014
                            setSelectedColumns(undefined, col, isMultiKey);
1✔
2015
                        }
1✔
2016
                        lastSelectedColRef.current = col;
1✔
2017
                    } else if (columnSelect !== "none") {
8✔
2018
                        if (selectedColumns.hasIndex(col)) {
7!
UNCOV
2019
                            setSelectedColumns(selectedColumns.remove(col), undefined, isMultiKey);
×
2020
                        } else {
7✔
2021
                            setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, isMultiKey);
7✔
2022
                        }
7✔
2023
                        lastSelectedColRef.current = col;
7✔
2024
                    }
7✔
2025
                    lastSelectedRowRef.current = undefined;
8✔
2026
                    focus();
8✔
2027
                }
8✔
2028
            } else if (args.kind === groupHeaderKind) {
16✔
2029
                lastMouseSelectLocation.current = [col, row];
4✔
2030
            } else if (args.kind === outOfBoundsKind && !args.isMaybeScrollbar) {
5✔
2031
                setGridSelection(emptyGridSelection, false);
1✔
2032
                setOverlay(undefined);
1✔
2033
                focus();
1✔
2034
                onSelectionCleared?.();
1!
2035
                lastSelectedRowRef.current = undefined;
1✔
2036
                lastSelectedColRef.current = undefined;
1✔
2037
            }
1✔
2038
        },
127✔
2039
        [
740✔
2040
            rowSelect,
740✔
2041
            columnSelect,
740✔
2042
            gridSelection,
740✔
2043
            hasRowMarkers,
740✔
2044
            rowMarkerOffset,
740✔
2045
            showTrailingBlankRow,
740✔
2046
            rows,
740✔
2047
            rowMarkers,
740✔
2048
            getMangledCellContent,
740✔
2049
            onRowMoved,
740✔
2050
            focus,
740✔
2051
            rowSelectionMode,
740✔
2052
            getCellRenderer,
740✔
2053
            themeForCell,
740✔
2054
            setSelectedRows,
740✔
2055
            getCustomNewRowTargetColumn,
740✔
2056
            appendRow,
740✔
2057
            rowGroupingNavBehavior,
740✔
2058
            mapper,
740✔
2059
            lastRowSticky,
740✔
2060
            setCurrent,
740✔
2061
            setSelectedColumns,
740✔
2062
            setGridSelection,
740✔
2063
            onSelectionCleared,
740✔
2064
        ]
740✔
2065
    );
740✔
2066
    const isActivelyDraggingHeader = React.useRef(false);
740✔
2067
    const lastMouseSelectLocation = React.useRef<readonly [number, number]>();
740✔
2068
    const touchDownArgs = React.useRef(visibleRegion);
740✔
2069
    const mouseDownData = React.useRef<{
740✔
2070
        time: number;
740✔
2071
        button: number;
740✔
2072
        location: Item;
740✔
2073
    }>();
740✔
2074
    const onMouseDown = React.useCallback(
740✔
2075
        (args: GridMouseEventArgs) => {
740✔
2076
            isPrevented.current = false;
144✔
2077
            touchDownArgs.current = visibleRegionRef.current;
144✔
2078
            if (args.button !== 0 && args.button !== 1) {
144✔
2079
                mouseDownData.current = undefined;
1✔
2080
                return;
1✔
2081
            }
1✔
2082

143✔
2083
            const time = performance.now();
143✔
2084
            mouseDownData.current = {
143✔
2085
                button: args.button,
143✔
2086
                time,
143✔
2087
                location: args.location,
143✔
2088
            };
143✔
2089

143✔
2090
            if (args?.kind === "header") {
144✔
2091
                isActivelyDraggingHeader.current = true;
17✔
2092
            }
17✔
2093

143✔
2094
            const fh = args.kind === "cell" && args.isFillHandle;
144✔
2095

144✔
2096
            if (!fh && args.kind !== "cell" && args.isEdge) return;
144✔
2097

136✔
2098
            setMouseState({
136✔
2099
                previousSelection: gridSelection,
136✔
2100
                fillHandle: fh,
136✔
2101
            });
136✔
2102
            lastMouseSelectLocation.current = undefined;
136✔
2103

136✔
2104
            if (!args.isTouch && args.button === 0 && !fh) {
144✔
2105
                handleSelect(args);
127✔
2106
            } else if (!args.isTouch && args.button === 1) {
137✔
2107
                lastMouseSelectLocation.current = args.location;
4✔
2108
            }
4✔
2109
        },
144✔
2110
        [gridSelection, handleSelect]
740✔
2111
    );
740✔
2112

740✔
2113
    const [renameGroup, setRenameGroup] = React.useState<{
740✔
2114
        group: string;
740✔
2115
        bounds: Rectangle;
740✔
2116
    }>();
740✔
2117

740✔
2118
    const handleGroupHeaderSelection = React.useCallback(
740✔
2119
        (args: GridMouseEventArgs) => {
740✔
2120
            if (args.kind !== groupHeaderKind || columnSelect !== "multi") {
4!
UNCOV
2121
                return;
×
UNCOV
2122
            }
×
2123
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
4!
2124
            const [col] = args.location;
4✔
2125
            const selectedColumns = gridSelection.columns;
4✔
2126

4✔
2127
            if (col < rowMarkerOffset) return;
4!
2128

4✔
2129
            const needle = mangledCols[col];
4✔
2130
            let start = col;
4✔
2131
            let end = col;
4✔
2132
            for (let i = col - 1; i >= rowMarkerOffset; i--) {
4✔
2133
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
4!
2134
                start--;
4✔
2135
            }
4✔
2136

4✔
2137
            for (let i = col + 1; i < mangledCols.length; i++) {
4✔
2138
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
36!
2139
                end++;
36✔
2140
            }
36✔
2141

4✔
2142
            focus();
4✔
2143

4✔
2144
            if (isMultiKey) {
4✔
2145
                if (selectedColumns.hasAll([start, end + 1])) {
2✔
2146
                    let newVal = selectedColumns;
1✔
2147
                    for (let index = start; index <= end; index++) {
1✔
2148
                        newVal = newVal.remove(index);
11✔
2149
                    }
11✔
2150
                    setSelectedColumns(newVal, undefined, isMultiKey);
1✔
2151
                } else {
1✔
2152
                    setSelectedColumns(undefined, [start, end + 1], isMultiKey);
1✔
2153
                }
1✔
2154
            } else {
2✔
2155
                setSelectedColumns(CompactSelection.fromSingleSelection([start, end + 1]), undefined, isMultiKey);
2✔
2156
            }
2✔
2157
        },
4✔
2158
        [columnSelect, focus, gridSelection.columns, mangledCols, rowMarkerOffset, setSelectedColumns]
740✔
2159
    );
740✔
2160

740✔
2161
    const isPrevented = React.useRef(false);
740✔
2162

740✔
2163
    const normalSizeColumn = React.useCallback(
740✔
2164
        async (col: number): Promise<void> => {
740✔
2165
            if (getCellsForSelection !== undefined && onColumnResize !== undefined) {
2✔
2166
                const start = visibleRegionRef.current.y;
2✔
2167
                const end = visibleRegionRef.current.height;
2✔
2168
                let cells = getCellsForSelection(
2✔
2169
                    {
2✔
2170
                        x: col,
2✔
2171
                        y: start,
2✔
2172
                        width: 1,
2✔
2173
                        height: Math.min(end, rows - start),
2✔
2174
                    },
2✔
2175
                    abortControllerRef.current.signal
2✔
2176
                );
2✔
2177
                if (typeof cells !== "object") {
2!
UNCOV
2178
                    cells = await cells();
×
UNCOV
2179
                }
×
2180
                const inputCol = columns[col - rowMarkerOffset];
2✔
2181
                const offscreen = document.createElement("canvas");
2✔
2182
                const ctx = offscreen.getContext("2d", { alpha: false });
2✔
2183
                if (ctx !== null) {
2✔
2184
                    ctx.font = mergedTheme.baseFontFull;
2✔
2185
                    const newCol = measureColumn(
2✔
2186
                        ctx,
2✔
2187
                        mergedTheme,
2✔
2188
                        inputCol,
2✔
2189
                        0,
2✔
2190
                        cells,
2✔
2191
                        minColumnWidth,
2✔
2192
                        maxColumnWidth,
2✔
2193
                        false,
2✔
2194
                        getCellRenderer
2✔
2195
                    );
2✔
2196
                    onColumnResize?.(inputCol, newCol.width, col, newCol.width);
2✔
2197
                }
2✔
2198
            }
2✔
2199
        },
2✔
2200
        [
740✔
2201
            columns,
740✔
2202
            getCellsForSelection,
740✔
2203
            maxColumnWidth,
740✔
2204
            mergedTheme,
740✔
2205
            minColumnWidth,
740✔
2206
            onColumnResize,
740✔
2207
            rowMarkerOffset,
740✔
2208
            rows,
740✔
2209
            getCellRenderer,
740✔
2210
        ]
740✔
2211
    );
740✔
2212

740✔
2213
    const [scrollDir, setScrollDir] = React.useState<GridMouseEventArgs["scrollEdge"]>();
740✔
2214

740✔
2215
    const fillPattern = React.useCallback(
740✔
2216
        async (previousSelection: GridSelection, currentSelection: GridSelection) => {
740✔
2217
            const patternRange = previousSelection.current?.range;
7✔
2218

7✔
2219
            if (
7✔
2220
                patternRange === undefined ||
7✔
2221
                getCellsForSelection === undefined ||
7✔
2222
                currentSelection.current === undefined
7✔
2223
            ) {
7!
UNCOV
2224
                return;
×
UNCOV
2225
            }
×
2226
            const currentRange = currentSelection.current.range;
7✔
2227

7✔
2228
            if (onFillPattern !== undefined) {
7✔
2229
                let canceled = false;
1✔
2230
                onFillPattern({
1✔
2231
                    fillDestination: { ...currentRange, x: currentRange.x - rowMarkerOffset },
1✔
2232
                    patternSource: { ...patternRange, x: patternRange.x - rowMarkerOffset },
1✔
2233
                    preventDefault: () => (canceled = true),
1✔
2234
                });
1✔
2235
                if (canceled) return;
1!
2236
            }
1✔
2237

7✔
2238
            let cells = getCellsForSelection(patternRange, abortControllerRef.current.signal);
7✔
2239
            if (typeof cells !== "object") cells = await cells();
7!
2240

7✔
2241
            const pattern = cells;
7✔
2242

7✔
2243
            // loop through all cells in currentSelection.current.range
7✔
2244
            const editItemList: EditListItem[] = [];
7✔
2245
            for (let x = 0; x < currentRange.width; x++) {
7✔
2246
                for (let y = 0; y < currentRange.height; y++) {
9✔
2247
                    const cell: Item = [currentRange.x + x, currentRange.y + y];
41✔
2248
                    if (itemIsInRect(cell, patternRange)) continue;
41✔
2249
                    const patternCell = pattern[y % patternRange.height][x % patternRange.width];
29✔
2250
                    if (isInnerOnlyCell(patternCell) || !isReadWriteCell(patternCell)) continue;
41!
2251
                    editItemList.push({
29✔
2252
                        location: cell,
29✔
2253
                        value: { ...patternCell },
29✔
2254
                    });
29✔
2255
                }
29✔
2256
            }
9✔
2257
            mangledOnCellsEdited(editItemList);
7✔
2258

7✔
2259
            gridRef.current?.damage(
7✔
2260
                editItemList.map(c => ({
7✔
2261
                    cell: c.location,
29✔
2262
                }))
7✔
2263
            );
7✔
2264
        },
7✔
2265
        [getCellsForSelection, mangledOnCellsEdited, onFillPattern, rowMarkerOffset]
740✔
2266
    );
740✔
2267

740✔
2268
    const fillRight = React.useCallback(() => {
740✔
2269
        if (gridSelection.current === undefined || gridSelection.current.range.width <= 1) return;
1!
2270

1✔
2271
        const firstColSelection = {
1✔
2272
            ...gridSelection,
1✔
2273
            current: {
1✔
2274
                ...gridSelection.current,
1✔
2275
                range: {
1✔
2276
                    ...gridSelection.current.range,
1✔
2277
                    width: 1,
1✔
2278
                },
1✔
2279
            },
1✔
2280
        };
1✔
2281

1✔
2282
        void fillPattern(firstColSelection, gridSelection);
1✔
2283
    }, [fillPattern, gridSelection]);
740✔
2284

740✔
2285
    const fillDown = React.useCallback(() => {
740✔
2286
        if (gridSelection.current === undefined || gridSelection.current.range.height <= 1) return;
1!
2287

1✔
2288
        const firstRowSelection = {
1✔
2289
            ...gridSelection,
1✔
2290
            current: {
1✔
2291
                ...gridSelection.current,
1✔
2292
                range: {
1✔
2293
                    ...gridSelection.current.range,
1✔
2294
                    height: 1,
1✔
2295
                },
1✔
2296
            },
1✔
2297
        };
1✔
2298

1✔
2299
        void fillPattern(firstRowSelection, gridSelection);
1✔
2300
    }, [fillPattern, gridSelection]);
740✔
2301

740✔
2302
    const onMouseUp = React.useCallback(
740✔
2303
        (args: GridMouseEventArgs, isOutside: boolean) => {
740✔
2304
            const mouse = mouseState;
144✔
2305
            setMouseState(undefined);
144✔
2306
            setFillHighlightRegion(undefined);
144✔
2307
            setScrollDir(undefined);
144✔
2308
            isActivelyDraggingHeader.current = false;
144✔
2309

144✔
2310
            if (isOutside) return;
144✔
2311

143✔
2312
            if (
143✔
2313
                mouse?.fillHandle === true &&
144✔
2314
                gridSelection.current !== undefined &&
5✔
2315
                mouse.previousSelection?.current !== undefined
5✔
2316
            ) {
144✔
2317
                if (fillHighlightRegion === undefined) return;
5!
2318
                const newRange = {
5✔
2319
                    ...gridSelection,
5✔
2320
                    current: {
5✔
2321
                        ...gridSelection.current,
5✔
2322
                        range: combineRects(mouse.previousSelection.current.range, fillHighlightRegion),
5✔
2323
                    },
5✔
2324
                };
5✔
2325
                void fillPattern(mouse.previousSelection, newRange);
5✔
2326
                setGridSelection(newRange, true);
5✔
2327
                return;
5✔
2328
            }
5✔
2329

138✔
2330
            const [col, row] = args.location;
138✔
2331
            const [lastMouseDownCol, lastMouseDownRow] = lastMouseSelectLocation.current ?? [];
144✔
2332

144✔
2333
            const preventDefault = () => {
144✔
UNCOV
2334
                isPrevented.current = true;
×
UNCOV
2335
            };
×
2336

144✔
2337
            const handleMaybeClick = (a: GridMouseCellEventArgs): boolean => {
144✔
2338
                const isValidClick = a.isTouch || (lastMouseDownCol === col && lastMouseDownRow === row);
113✔
2339
                if (isValidClick) {
113✔
2340
                    onCellClicked?.([col - rowMarkerOffset, row], {
103✔
2341
                        ...a,
4✔
2342
                        preventDefault,
4✔
2343
                    });
4✔
2344
                }
103✔
2345
                if (a.button === 1) return !isPrevented.current;
113✔
2346
                if (!isPrevented.current) {
110✔
2347
                    const c = getMangledCellContent(args.location);
110✔
2348
                    const r = getCellRenderer(c);
110✔
2349
                    if (r !== undefined && r.onClick !== undefined && isValidClick) {
110✔
2350
                        const newVal = r.onClick({
21✔
2351
                            ...a,
21✔
2352
                            cell: c,
21✔
2353
                            posX: a.localEventX,
21✔
2354
                            posY: a.localEventY,
21✔
2355
                            bounds: a.bounds,
21✔
2356
                            theme: themeForCell(c, args.location),
21✔
2357
                            preventDefault,
21✔
2358
                        });
21✔
2359
                        if (newVal !== undefined && !isInnerOnlyCell(newVal) && isEditableGridCell(newVal)) {
21✔
2360
                            mangledOnCellsEdited([{ location: a.location, value: newVal }]);
4✔
2361
                            gridRef.current?.damage([
4✔
2362
                                {
4✔
2363
                                    cell: a.location,
4✔
2364
                                },
4✔
2365
                            ]);
4✔
2366
                        }
4✔
2367
                    }
21✔
2368
                    if (isPrevented.current || gridSelection.current === undefined) return false;
110✔
2369

96✔
2370
                    let shouldActivate = false;
96✔
2371
                    switch (c.activationBehaviorOverride ?? cellActivationBehavior) {
110✔
2372
                        case "double-click":
110✔
2373
                        case "second-click": {
110✔
2374
                            if (mouse?.previousSelection?.current?.cell === undefined) break;
95✔
2375
                            const [selectedCol, selectedRow] = gridSelection.current.cell;
21✔
2376
                            const [prevCol, prevRow] = mouse.previousSelection.current.cell;
21✔
2377
                            const isClickOnSelected =
21✔
2378
                                col === selectedCol && col === prevCol && row === selectedRow && row === prevRow;
95✔
2379
                            shouldActivate =
95✔
2380
                                isClickOnSelected &&
95✔
2381
                                (a.isDoubleClick === true || cellActivationBehavior === "second-click");
6✔
2382
                            break;
95✔
2383
                        }
95✔
2384
                        case "single-click": {
110✔
2385
                            shouldActivate = true;
1✔
2386
                            break;
1✔
2387
                        }
1✔
2388
                    }
110✔
2389
                    if (shouldActivate) {
110✔
2390
                        onCellActivated?.([col - rowMarkerOffset, row]);
6✔
2391
                        reselect(a.bounds, false);
6✔
2392
                        return true;
6✔
2393
                    }
6✔
2394
                }
110✔
2395
                return false;
90✔
2396
            };
113✔
2397

144✔
2398
            const clickLocation = args.location[0] - rowMarkerOffset;
144✔
2399
            if (args.isTouch) {
144!
UNCOV
2400
                const vr = visibleRegionRef.current;
×
UNCOV
2401
                const touchVr = touchDownArgs.current;
×
2402
                if (vr.x !== touchVr.x || vr.y !== touchVr.y) {
×
2403
                    // we scrolled, abort
×
2404
                    return;
×
2405
                }
×
2406
                // take care of context menus first if long pressed item is already selected
×
2407
                if (args.isLongTouch === true) {
×
2408
                    if (args.kind === "cell" && itemsAreEqual(gridSelection.current?.cell, args.location)) {
×
2409
                        onCellContextMenu?.([clickLocation, args.location[1]], {
×
2410
                            ...args,
×
2411
                            preventDefault,
×
2412
                        });
×
2413
                        return;
×
2414
                    } else if (args.kind === "header" && gridSelection.columns.hasIndex(col)) {
×
2415
                        onHeaderContextMenu?.(clickLocation, { ...args, preventDefault });
×
2416
                        return;
×
2417
                    } else if (args.kind === groupHeaderKind) {
×
2418
                        if (clickLocation < 0) {
×
2419
                            return;
×
UNCOV
2420
                        }
×
UNCOV
2421

×
UNCOV
2422
                        onGroupHeaderContextMenu?.(clickLocation, { ...args, preventDefault });
×
UNCOV
2423
                        return;
×
UNCOV
2424
                    }
×
UNCOV
2425
                }
×
UNCOV
2426
                if (args.kind === "cell") {
×
UNCOV
2427
                    // click that cell
×
UNCOV
2428
                    if (!handleMaybeClick(args)) {
×
UNCOV
2429
                        handleSelect(args);
×
UNCOV
2430
                    }
×
UNCOV
2431
                } else if (args.kind === groupHeaderKind) {
×
UNCOV
2432
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
×
UNCOV
2433
                } else {
×
UNCOV
2434
                    if (args.kind === headerKind) {
×
UNCOV
2435
                        onHeaderClicked?.(clickLocation, {
×
UNCOV
2436
                            ...args,
×
UNCOV
2437
                            preventDefault,
×
UNCOV
2438
                        });
×
UNCOV
2439
                    }
×
UNCOV
2440
                    handleSelect(args);
×
UNCOV
2441
                }
×
UNCOV
2442
                return;
×
UNCOV
2443
            }
✔
2444

138✔
2445
            if (args.kind === "header") {
144✔
2446
                if (clickLocation < 0) {
17✔
2447
                    return;
3✔
2448
                }
3✔
2449

14✔
2450
                if (args.isEdge) {
17✔
2451
                    if (args.isDoubleClick === true) {
2✔
2452
                        void normalSizeColumn(col);
1✔
2453
                    }
1✔
2454
                } else if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
17✔
2455
                    onHeaderClicked?.(clickLocation, { ...args, preventDefault });
6✔
2456
                }
6✔
2457
            }
17✔
2458

135✔
2459
            if (args.kind === groupHeaderKind) {
144✔
2460
                if (clickLocation < 0) {
4!
UNCOV
2461
                    return;
×
UNCOV
2462
                }
×
2463

4✔
2464
                if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
4✔
2465
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
4✔
2466
                    if (!isPrevented.current) {
4✔
2467
                        handleGroupHeaderSelection(args);
4✔
2468
                    }
4✔
2469
                }
4✔
2470
            }
4✔
2471

135✔
2472
            if (args.kind === "cell" && (args.button === 0 || args.button === 1)) {
144✔
2473
                handleMaybeClick(args);
113✔
2474
            }
113✔
2475

135✔
2476
            lastMouseSelectLocation.current = undefined;
135✔
2477
        },
144✔
2478
        [
740✔
2479
            mouseState,
740✔
2480
            gridSelection,
740✔
2481
            rowMarkerOffset,
740✔
2482
            fillHighlightRegion,
740✔
2483
            fillPattern,
740✔
2484
            setGridSelection,
740✔
2485
            onCellClicked,
740✔
2486
            getMangledCellContent,
740✔
2487
            getCellRenderer,
740✔
2488
            cellActivationBehavior,
740✔
2489
            themeForCell,
740✔
2490
            mangledOnCellsEdited,
740✔
2491
            onCellActivated,
740✔
2492
            reselect,
740✔
2493
            onCellContextMenu,
740✔
2494
            onHeaderContextMenu,
740✔
2495
            onGroupHeaderContextMenu,
740✔
2496
            handleSelect,
740✔
2497
            onGroupHeaderClicked,
740✔
2498
            onHeaderClicked,
740✔
2499
            normalSizeColumn,
740✔
2500
            handleGroupHeaderSelection,
740✔
2501
        ]
740✔
2502
    );
740✔
2503

740✔
2504
    const onMouseMoveImpl = React.useCallback(
740✔
2505
        (args: GridMouseEventArgs) => {
740✔
2506
            const a: GridMouseEventArgs = {
39✔
2507
                ...args,
39✔
2508
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
39✔
2509
            };
39✔
2510
            onMouseMove?.(a);
39✔
2511

39✔
2512
            if (mouseState !== undefined && args.buttons === 0) {
39✔
2513
                setMouseState(undefined);
6✔
2514
                setFillHighlightRegion(undefined);
6✔
2515
                setScrollDir(undefined);
6✔
2516
                isActivelyDraggingHeader.current = false;
6✔
2517
            }
6✔
2518

39✔
2519
            setScrollDir(cv => {
39✔
2520
                if (isActivelyDraggingHeader.current) return [args.scrollEdge[0], 0];
39✔
2521
                if (args.scrollEdge[0] === cv?.[0] && args.scrollEdge[1] === cv[1]) return cv;
39✔
2522
                return mouseState === undefined || (mouseDownData.current?.location[0] ?? 0) < rowMarkerOffset
39!
2523
                    ? undefined
13✔
2524
                    : args.scrollEdge;
16✔
2525
            });
39✔
2526
        },
39✔
2527
        [mouseState, onMouseMove, rowMarkerOffset]
740✔
2528
    );
740✔
2529

740✔
2530
    const onHeaderMenuClickInner = React.useCallback(
740✔
2531
        (col: number, screenPosition: Rectangle) => {
740✔
2532
            onHeaderMenuClick?.(col - rowMarkerOffset, screenPosition);
1✔
2533
        },
1✔
2534
        [onHeaderMenuClick, rowMarkerOffset]
740✔
2535
    );
740✔
2536

740✔
2537
    const onHeaderIndicatorClickInner = React.useCallback(
740✔
2538
        (col: number, screenPosition: Rectangle) => {
740✔
UNCOV
2539
            onHeaderIndicatorClick?.(col - rowMarkerOffset, screenPosition);
×
UNCOV
2540
        },
×
2541
        [onHeaderIndicatorClick, rowMarkerOffset]
740✔
2542
    );
740✔
2543

740✔
2544
    const currentCell = gridSelection?.current?.cell;
740✔
2545
    const onVisibleRegionChangedImpl = React.useCallback(
740✔
2546
        (
740✔
2547
            region: Rectangle,
156✔
2548
            clientWidth: number,
156✔
2549
            clientHeight: number,
156✔
2550
            rightElWidth: number,
156✔
2551
            tx: number,
156✔
2552
            ty: number
156✔
2553
        ) => {
156✔
2554
            hasJustScrolled.current = false;
156✔
2555
            let selected = currentCell;
156✔
2556
            if (selected !== undefined) {
156✔
2557
                selected = [selected[0] - rowMarkerOffset, selected[1]];
11✔
2558
            }
11✔
2559

156✔
2560
            const freezeRegion =
156✔
2561
                freezeColumns === 0
156✔
2562
                    ? undefined
155✔
2563
                    : {
1✔
2564
                          x: 0,
1✔
2565
                          y: region.y,
1✔
2566
                          width: freezeColumns,
1✔
2567
                          height: region.height,
1✔
2568
                      };
1✔
2569

156✔
2570
            const freezeRegions: Rectangle[] = [];
156✔
2571
            if (freezeRegion !== undefined) freezeRegions.push(freezeRegion);
156✔
2572
            if (freezeTrailingRows > 0) {
156✔
2573
                freezeRegions.push({
1✔
2574
                    x: region.x - rowMarkerOffset,
1✔
2575
                    y: rows - freezeTrailingRows,
1✔
2576
                    width: region.width,
1✔
2577
                    height: freezeTrailingRows,
1✔
2578
                });
1✔
2579

1✔
2580
                if (freezeColumns > 0) {
1✔
2581
                    freezeRegions.push({
1✔
2582
                        x: 0,
1✔
2583
                        y: rows - freezeTrailingRows,
1✔
2584
                        width: freezeColumns,
1✔
2585
                        height: freezeTrailingRows,
1✔
2586
                    });
1✔
2587
                }
1✔
2588
            }
1✔
2589

156✔
2590
            const newRegion = {
156✔
2591
                x: region.x - rowMarkerOffset,
156✔
2592
                y: region.y,
156✔
2593
                width: region.width,
156✔
2594
                height: showTrailingBlankRow && region.y + region.height >= rows ? region.height - 1 : region.height,
156✔
2595
                tx,
156✔
2596
                ty,
156✔
2597
                extras: {
156✔
2598
                    selected,
156✔
2599
                    freezeRegion,
156✔
2600
                    freezeRegions,
156✔
2601
                },
156✔
2602
            };
156✔
2603
            visibleRegionRef.current = newRegion;
156✔
2604
            setVisibleRegion(newRegion);
156✔
2605
            setClientSize([clientWidth, clientHeight, rightElWidth]);
156✔
2606
            onVisibleRegionChanged?.(newRegion, newRegion.tx, newRegion.ty, newRegion.extras);
156✔
2607
        },
156✔
2608
        [
740✔
2609
            currentCell,
740✔
2610
            rowMarkerOffset,
740✔
2611
            showTrailingBlankRow,
740✔
2612
            rows,
740✔
2613
            freezeColumns,
740✔
2614
            freezeTrailingRows,
740✔
2615
            setVisibleRegion,
740✔
2616
            onVisibleRegionChanged,
740✔
2617
        ]
740✔
2618
    );
740✔
2619

740✔
2620
    const onColumnProposeMoveImpl = whenDefined(
740✔
2621
        onColumnProposeMove,
740✔
2622
        React.useCallback(
740✔
2623
            (startIndex: number, endIndex: number) => {
740✔
UNCOV
2624
                return onColumnProposeMove?.(startIndex - rowMarkerOffset, endIndex - rowMarkerOffset) !== false;
×
UNCOV
2625
            },
×
2626
            [onColumnProposeMove, rowMarkerOffset]
740✔
2627
        )
740✔
2628
    );
740✔
2629

740✔
2630
    const onColumnMovedImpl = whenDefined(
740✔
2631
        onColumnMoved,
740✔
2632
        React.useCallback(
740✔
2633
            (startIndex: number, endIndex: number) => {
740✔
2634
                onColumnMoved?.(startIndex - rowMarkerOffset, endIndex - rowMarkerOffset);
1✔
2635
                if (columnSelect !== "none") {
1✔
2636
                    setSelectedColumns(CompactSelection.fromSingleSelection(endIndex), undefined, true);
1✔
2637
                }
1✔
2638
            },
1✔
2639
            [columnSelect, onColumnMoved, rowMarkerOffset, setSelectedColumns]
740✔
2640
        )
740✔
2641
    );
740✔
2642

740✔
2643
    const isActivelyDragging = React.useRef(false);
740✔
2644
    const onDragStartImpl = React.useCallback(
740✔
2645
        (args: GridDragEventArgs) => {
740✔
2646
            if (args.location[0] === 0 && rowMarkerOffset > 0) {
1!
UNCOV
2647
                args.preventDefault();
×
UNCOV
2648
                return;
×
UNCOV
2649
            }
×
2650
            onDragStart?.({
1✔
2651
                ...args,
1✔
2652
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
1✔
2653
            });
1✔
2654

1✔
2655
            if (!args.defaultPrevented()) {
1✔
2656
                isActivelyDragging.current = true;
1✔
2657
            }
1✔
2658
            setMouseState(undefined);
1✔
2659
        },
1✔
2660
        [onDragStart, rowMarkerOffset]
740✔
2661
    );
740✔
2662

740✔
2663
    const onDragEnd = React.useCallback(() => {
740✔
UNCOV
2664
        isActivelyDragging.current = false;
×
2665
    }, []);
740✔
2666

740✔
2667
    const rowGroupingSelectionBehavior = rowGrouping?.selectionBehavior;
740!
2668

740✔
2669
    const getSelectionRowLimits = React.useCallback(
740✔
2670
        (selectedRow: number): readonly [number, number] | undefined => {
740✔
2671
            if (rowGroupingSelectionBehavior !== "block-spanning") return undefined;
16!
2672

×
2673
            const { isGroupHeader, path, groupRows } = mapper(selectedRow);
×
2674

×
2675
            if (isGroupHeader) {
×
2676
                return [selectedRow, selectedRow];
×
2677
            }
×
UNCOV
2678

×
UNCOV
2679
            const groupRowIndex = path[path.length - 1];
×
UNCOV
2680
            const lowerBounds = selectedRow - groupRowIndex;
×
UNCOV
2681
            const upperBounds = selectedRow + groupRows - groupRowIndex - 1;
×
UNCOV
2682

×
UNCOV
2683
            return [lowerBounds, upperBounds];
×
2684
        },
16✔
2685
        [mapper, rowGroupingSelectionBehavior]
740✔
2686
    );
740✔
2687

740✔
2688
    const hoveredRef = React.useRef<GridMouseEventArgs>();
740✔
2689
    const onItemHoveredImpl = React.useCallback(
740✔
2690
        (args: GridMouseEventArgs) => {
740✔
2691
            // make sure we still have a button down
29✔
2692
            if (mouseEventArgsAreEqual(args, hoveredRef.current)) return;
29!
2693
            hoveredRef.current = args;
29✔
2694
            if (mouseDownData?.current?.button !== undefined && mouseDownData.current.button >= 1) return;
29✔
2695
            if (
28✔
2696
                args.buttons !== 0 &&
28✔
2697
                mouseState !== undefined &&
14✔
2698
                mouseDownData.current?.location[0] === 0 &&
14✔
2699
                args.location[0] === 0 &&
1✔
2700
                rowMarkerOffset === 1 &&
1✔
2701
                rowSelect === "multi" &&
1✔
2702
                mouseState.previousSelection &&
1✔
2703
                !mouseState.previousSelection.rows.hasIndex(mouseDownData.current.location[1]) &&
1✔
2704
                gridSelection.rows.hasIndex(mouseDownData.current.location[1])
1✔
2705
            ) {
29✔
2706
                const start = Math.min(mouseDownData.current.location[1], args.location[1]);
1✔
2707
                const end = Math.max(mouseDownData.current.location[1], args.location[1]) + 1;
1✔
2708
                setSelectedRows(CompactSelection.fromSingleSelection([start, end]), undefined, false);
1✔
2709
            }
1✔
2710
            if (
28✔
2711
                args.buttons !== 0 &&
28✔
2712
                mouseState !== undefined &&
14✔
2713
                gridSelection.current !== undefined &&
14✔
2714
                !isActivelyDragging.current &&
12✔
2715
                !isActivelyDraggingHeader.current &&
12✔
2716
                (rangeSelect === "rect" || rangeSelect === "multi-rect")
12!
2717
            ) {
29✔
2718
                const [selectedCol, selectedRow] = gridSelection.current.cell;
12✔
2719
                // eslint-disable-next-line prefer-const
12✔
2720
                let [col, row] = args.location;
12✔
2721

12✔
2722
                if (row < 0) {
12✔
2723
                    row = visibleRegionRef.current.y;
1✔
2724
                }
1✔
2725

12✔
2726
                if (mouseState.fillHandle === true && mouseState.previousSelection?.current !== undefined) {
12✔
2727
                    const prevRange = mouseState.previousSelection.current.range;
6✔
2728
                    row = Math.min(row, showTrailingBlankRow ? rows - 1 : rows);
6!
2729
                    const rect = getClosestRect(prevRange, col, row, allowedFillDirections);
6✔
2730
                    setFillHighlightRegion(rect);
6✔
2731
                } else {
6✔
2732
                    const startedFromLastStickyRow = showTrailingBlankRow && selectedRow === rows;
6✔
2733
                    if (startedFromLastStickyRow) return;
6!
2734

6✔
2735
                    const landedOnLastStickyRow = showTrailingBlankRow && row === rows;
6✔
2736
                    if (landedOnLastStickyRow) {
6!
UNCOV
2737
                        if (args.kind === outOfBoundsKind) row--;
×
UNCOV
2738
                        else return;
×
UNCOV
2739
                    }
×
2740

6✔
2741
                    col = Math.max(col, rowMarkerOffset);
6✔
2742
                    const clampLimits = getSelectionRowLimits(selectedRow);
6✔
2743
                    row = clampLimits === undefined ? row : clamp(row, clampLimits[0], clampLimits[1]);
6!
2744

6✔
2745
                    // FIXME: Restrict row based on rowGrouping.selectionBehavior here
6✔
2746

6✔
2747
                    const deltaX = col - selectedCol;
6✔
2748
                    const deltaY = row - selectedRow;
6✔
2749

6✔
2750
                    const newRange: Rectangle = {
6✔
2751
                        x: deltaX >= 0 ? selectedCol : col,
6!
2752
                        y: deltaY >= 0 ? selectedRow : row,
6✔
2753
                        width: Math.abs(deltaX) + 1,
6✔
2754
                        height: Math.abs(deltaY) + 1,
6✔
2755
                    };
6✔
2756

6✔
2757
                    setCurrent(
6✔
2758
                        {
6✔
2759
                            ...gridSelection.current,
6✔
2760
                            range: newRange,
6✔
2761
                        },
6✔
2762
                        true,
6✔
2763
                        false,
6✔
2764
                        "drag"
6✔
2765
                    );
6✔
2766
                }
6✔
2767
            }
12✔
2768

28✔
2769
            onItemHovered?.({ ...args, location: [args.location[0] - rowMarkerOffset, args.location[1]] as any });
29✔
2770
        },
29✔
2771
        [
740✔
2772
            mouseState,
740✔
2773
            rowMarkerOffset,
740✔
2774
            rowSelect,
740✔
2775
            gridSelection,
740✔
2776
            rangeSelect,
740✔
2777
            onItemHovered,
740✔
2778
            setSelectedRows,
740✔
2779
            showTrailingBlankRow,
740✔
2780
            rows,
740✔
2781
            allowedFillDirections,
740✔
2782
            getSelectionRowLimits,
740✔
2783
            setCurrent,
740✔
2784
        ]
740✔
2785
    );
740✔
2786

740✔
2787
    const adjustSelectionOnScroll = React.useCallback(() => {
740✔
2788
        const args = hoveredRef.current;
×
2789
        if (args === undefined) return;
×
2790
        const [xDir, yDir] = args.scrollEdge;
×
2791
        let [col, row] = args.location;
×
2792
        const visible = visibleRegionRef.current;
×
2793
        if (xDir === -1) {
×
2794
            col = visible.extras?.freezeRegion?.x ?? visible.x;
×
2795
        } else if (xDir === 1) {
×
2796
            col = visible.x + visible.width;
×
2797
        }
×
2798
        if (yDir === -1) {
×
2799
            row = Math.max(0, visible.y);
×
2800
        } else if (yDir === 1) {
×
2801
            row = Math.min(rows - 1, visible.y + visible.height);
×
2802
        }
×
UNCOV
2803
        col = clamp(col, 0, mangledCols.length - 1);
×
UNCOV
2804
        row = clamp(row, 0, rows - 1);
×
UNCOV
2805
        onItemHoveredImpl({
×
UNCOV
2806
            ...args,
×
UNCOV
2807
            location: [col, row] as any,
×
UNCOV
2808
        });
×
2809
    }, [mangledCols.length, onItemHoveredImpl, rows]);
740✔
2810

740✔
2811
    useAutoscroll(scrollDir, scrollRef, adjustSelectionOnScroll);
740✔
2812

740✔
2813
    // 1 === move one
740✔
2814
    // 2 === move to end
740✔
2815
    const adjustSelection = React.useCallback(
740✔
2816
        (direction: [0 | 1 | -1 | 2 | -2, 0 | 1 | -1 | 2 | -2]) => {
740✔
2817
            if (gridSelection.current === undefined) return;
10!
2818

10✔
2819
            const [x, y] = direction;
10✔
2820
            const [col, row] = gridSelection.current.cell;
10✔
2821
            const old = gridSelection.current.range;
10✔
2822
            let left = old.x;
10✔
2823
            let right = old.x + old.width;
10✔
2824
            let top = old.y;
10✔
2825
            let bottom = old.y + old.height;
10✔
2826

10✔
2827
            const [minRow, maxRowRaw] = getSelectionRowLimits(row) ?? [0, rows - 1];
10✔
2828
            const maxRow = maxRowRaw + 1; // we need an inclusive value
10✔
2829

10✔
2830
            // take care of vertical first in case new spans come in
10✔
2831
            if (y !== 0) {
10✔
2832
                switch (y) {
4✔
2833
                    case 2: {
4✔
2834
                        // go to end
2✔
2835
                        bottom = maxRow;
2✔
2836
                        top = row;
2✔
2837
                        scrollTo(0, bottom, "vertical");
2✔
2838

2✔
2839
                        break;
2✔
2840
                    }
2✔
2841
                    case -2: {
4✔
2842
                        // go to start
1✔
2843
                        top = minRow;
1✔
2844
                        bottom = row + 1;
1✔
2845
                        scrollTo(0, top, "vertical");
1✔
2846

1✔
2847
                        break;
1✔
2848
                    }
1✔
2849
                    case 1: {
4✔
2850
                        // motion down
1✔
2851
                        if (top < row) {
1!
UNCOV
2852
                            top++;
×
UNCOV
2853
                            scrollTo(0, top, "vertical");
×
2854
                        } else {
1✔
2855
                            bottom = Math.min(maxRow, bottom + 1);
1✔
2856
                            scrollTo(0, bottom, "vertical");
1✔
2857
                        }
1✔
2858

1✔
2859
                        break;
1✔
2860
                    }
1✔
2861
                    case -1: {
4!
2862
                        // motion up
×
2863
                        if (bottom > row + 1) {
×
2864
                            bottom--;
×
2865
                            scrollTo(0, bottom, "vertical");
×
2866
                        } else {
×
UNCOV
2867
                            top = Math.max(minRow, top - 1);
×
2868
                            scrollTo(0, top, "vertical");
×
2869
                        }
×
UNCOV
2870

×
UNCOV
2871
                        break;
×
UNCOV
2872
                    }
×
2873
                    default: {
4!
UNCOV
2874
                        assertNever(y);
×
UNCOV
2875
                    }
×
2876
                }
4✔
2877
            }
4✔
2878

10✔
2879
            if (x !== 0) {
10✔
2880
                if (x === 2) {
8✔
2881
                    right = mangledCols.length;
2✔
2882
                    left = col;
2✔
2883
                    scrollTo(right - 1 - rowMarkerOffset, 0, "horizontal");
2✔
2884
                } else if (x === -2) {
8✔
2885
                    left = rowMarkerOffset;
1✔
2886
                    right = col + 1;
1✔
2887
                    scrollTo(left - rowMarkerOffset, 0, "horizontal");
1✔
2888
                } else {
6✔
2889
                    let disallowed: number[] = [];
5✔
2890
                    if (getCellsForSelection !== undefined) {
5✔
2891
                        const cells = getCellsForSelection(
5✔
2892
                            {
5✔
2893
                                x: left,
5✔
2894
                                y: top,
5✔
2895
                                width: right - left - rowMarkerOffset,
5✔
2896
                                height: bottom - top,
5✔
2897
                            },
5✔
2898
                            abortControllerRef.current.signal
5✔
2899
                        );
5✔
2900

5✔
2901
                        if (typeof cells === "object") {
5✔
2902
                            disallowed = getSpanStops(cells);
5✔
2903
                        }
5✔
2904
                    }
5✔
2905
                    if (x === 1) {
5✔
2906
                        // motion right
4✔
2907
                        let done = false;
4✔
2908
                        if (left < col) {
4!
2909
                            if (disallowed.length > 0) {
×
2910
                                const target = range(left + 1, col + 1).find(
×
2911
                                    n => !disallowed.includes(n - rowMarkerOffset)
×
2912
                                );
×
2913
                                if (target !== undefined) {
×
2914
                                    left = target;
×
2915
                                    done = true;
×
2916
                                }
×
UNCOV
2917
                            } else {
×
UNCOV
2918
                                left++;
×
UNCOV
2919
                                done = true;
×
UNCOV
2920
                            }
×
UNCOV
2921
                            if (done) scrollTo(left, 0, "horizontal");
×
UNCOV
2922
                        }
×
2923
                        if (!done) {
4✔
2924
                            right = Math.min(mangledCols.length, right + 1);
4✔
2925
                            scrollTo(right - 1 - rowMarkerOffset, 0, "horizontal");
4✔
2926
                        }
4✔
2927
                    } else if (x === -1) {
5✔
2928
                        // motion left
1✔
2929
                        let done = false;
1✔
2930
                        if (right > col + 1) {
1!
2931
                            if (disallowed.length > 0) {
×
2932
                                const target = range(right - 1, col, -1).find(
×
2933
                                    n => !disallowed.includes(n - rowMarkerOffset)
×
2934
                                );
×
2935
                                if (target !== undefined) {
×
2936
                                    right = target;
×
2937
                                    done = true;
×
2938
                                }
×
UNCOV
2939
                            } else {
×
UNCOV
2940
                                right--;
×
UNCOV
2941
                                done = true;
×
UNCOV
2942
                            }
×
UNCOV
2943
                            if (done) scrollTo(right - rowMarkerOffset, 0, "horizontal");
×
2944
                        }
×
2945
                        if (!done) {
1✔
2946
                            left = Math.max(rowMarkerOffset, left - 1);
1✔
2947
                            scrollTo(left - rowMarkerOffset, 0, "horizontal");
1✔
2948
                        }
1✔
2949
                    } else {
1!
UNCOV
2950
                        assertNever(x);
×
UNCOV
2951
                    }
×
2952
                }
5✔
2953
            }
8✔
2954

10✔
2955
            setCurrent(
10✔
2956
                {
10✔
2957
                    cell: gridSelection.current.cell,
10✔
2958
                    range: {
10✔
2959
                        x: left,
10✔
2960
                        y: top,
10✔
2961
                        width: right - left,
10✔
2962
                        height: bottom - top,
10✔
2963
                    },
10✔
2964
                },
10✔
2965
                true,
10✔
2966
                false,
10✔
2967
                "keyboard-select"
10✔
2968
            );
10✔
2969
        },
10✔
2970
        [
740✔
2971
            getCellsForSelection,
740✔
2972
            getSelectionRowLimits,
740✔
2973
            gridSelection,
740✔
2974
            mangledCols.length,
740✔
2975
            rowMarkerOffset,
740✔
2976
            rows,
740✔
2977
            scrollTo,
740✔
2978
            setCurrent,
740✔
2979
        ]
740✔
2980
    );
740✔
2981

740✔
2982
    const scrollToActiveCellRef = React.useRef(scrollToActiveCell);
740✔
2983
    scrollToActiveCellRef.current = scrollToActiveCell;
740✔
2984

740✔
2985
    const updateSelectedCell = React.useCallback(
740✔
2986
        (col: number, row: number, fromEditingTrailingRow: boolean, freeMove: boolean): boolean => {
740✔
2987
            const rowMax = mangledRows - (fromEditingTrailingRow ? 0 : 1);
68!
2988
            col = clamp(col, rowMarkerOffset, columns.length - 1 + rowMarkerOffset);
68✔
2989
            row = clamp(row, 0, rowMax);
68✔
2990

68✔
2991
            const curCol = currentCell?.[0];
68✔
2992
            const curRow = currentCell?.[1];
68✔
2993

68✔
2994
            if (col === curCol && row === curRow) return false;
68✔
2995
            if (freeMove && gridSelection.current !== undefined) {
68✔
2996
                const newStack = [...gridSelection.current.rangeStack];
1✔
2997
                if (gridSelection.current.range.width > 1 || gridSelection.current.range.height > 1) {
1!
2998
                    newStack.push(gridSelection.current.range);
1✔
2999
                }
1✔
3000
                setGridSelection(
1✔
3001
                    {
1✔
3002
                        ...gridSelection,
1✔
3003
                        current: {
1✔
3004
                            cell: [col, row],
1✔
3005
                            range: { x: col, y: row, width: 1, height: 1 },
1✔
3006
                            rangeStack: newStack,
1✔
3007
                        },
1✔
3008
                    },
1✔
3009
                    true
1✔
3010
                );
1✔
3011
            } else {
68✔
3012
                setCurrent(
29✔
3013
                    {
29✔
3014
                        cell: [col, row],
29✔
3015
                        range: { x: col, y: row, width: 1, height: 1 },
29✔
3016
                    },
29✔
3017
                    true,
29✔
3018
                    false,
29✔
3019
                    "keyboard-nav"
29✔
3020
                );
29✔
3021
            }
29✔
3022

30✔
3023
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
68✔
3024
                lastSent.current = undefined;
2✔
3025
            }
2✔
3026

30✔
3027
            if (scrollToActiveCellRef.current) {
30✔
3028
                scrollTo(col - rowMarkerOffset, row);
30✔
3029
            }
30✔
3030

30✔
3031
            return true;
30✔
3032
        },
68✔
3033
        [
740✔
3034
            mangledRows,
740✔
3035
            rowMarkerOffset,
740✔
3036
            columns.length,
740✔
3037
            currentCell,
740✔
3038
            gridSelection,
740✔
3039
            scrollTo,
740✔
3040
            setGridSelection,
740✔
3041
            setCurrent,
740✔
3042
        ]
740✔
3043
    );
740✔
3044

740✔
3045
    const onFinishEditing = React.useCallback(
740✔
3046
        (newValue: GridCell | undefined, movement: readonly [-1 | 0 | 1, -1 | 0 | 1]) => {
740✔
3047
            if (overlay?.cell !== undefined && newValue !== undefined && isEditableGridCell(newValue)) {
12✔
3048
                mangledOnCellsEdited([{ location: overlay.cell, value: newValue }]);
4✔
3049
                window.requestAnimationFrame(() => {
4✔
3050
                    gridRef.current?.damage([
4✔
3051
                        {
4✔
3052
                            cell: overlay.cell,
4✔
3053
                        },
4✔
3054
                    ]);
4✔
3055
                });
4✔
3056
            }
4✔
3057
            focus(true);
12✔
3058
            setOverlay(undefined);
12✔
3059

12✔
3060
            const [movX, movY] = movement;
12✔
3061
            if (gridSelection.current !== undefined && (movX !== 0 || movY !== 0)) {
12✔
3062
                const isEditingLastRow = gridSelection.current.cell[1] === mangledRows - 1 && newValue !== undefined;
3!
3063
                const isEditingLastCol =
3✔
3064
                    gridSelection.current.cell[0] === mangledCols.length - 1 && newValue !== undefined;
3!
3065
                let updateSelected = true;
3✔
3066
                if (isEditingLastRow && movY === 1 && onRowAppended !== undefined) {
3!
NEW
3067
                    updateSelected = false;
×
NEW
3068
                    const col = gridSelection.current.cell[0] + movX;
×
NEW
3069
                    const customTargetColumn = getCustomNewRowTargetColumn(col);
×
NEW
3070
                    void appendRow(customTargetColumn ?? col, false);
×
NEW
3071
                }
×
3072
                if (isEditingLastCol && movX === 1 && onColumnAppended !== undefined) {
3!
NEW
3073
                    updateSelected = false;
×
NEW
3074
                    const row = gridSelection.current.cell[1] + movY;
×
NEW
3075
                    void appendColumn(row, false);
×
NEW
3076
                }
×
3077
                if (updateSelected) {
3✔
3078
                    updateSelectedCell(
3✔
3079
                        clamp(gridSelection.current.cell[0] + movX, 0, mangledCols.length - 1),
3✔
3080
                        clamp(gridSelection.current.cell[1] + movY, 0, mangledRows - 1),
3✔
3081
                        isEditingLastRow,
3✔
3082
                        false
3✔
3083
                    );
3✔
3084
                }
3✔
3085
            }
3✔
3086
            onFinishedEditing?.(newValue, movement);
12✔
3087
        },
12✔
3088
        [
740✔
3089
            overlay?.cell,
740✔
3090
            focus,
740✔
3091
            gridSelection,
740✔
3092
            onFinishedEditing,
740✔
3093
            mangledOnCellsEdited,
740✔
3094
            mangledRows,
740✔
3095
            updateSelectedCell,
740✔
3096
            mangledCols.length,
740✔
3097
            appendRow,
740✔
3098
            appendColumn,
740✔
3099
            onRowAppended,
740✔
3100
            onColumnAppended,
740✔
3101
            getCustomNewRowTargetColumn,
740✔
3102
        ]
740✔
3103
    );
740✔
3104

740✔
3105
    const overlayID = React.useMemo(() => {
740✔
3106
        return `gdg-overlay-${idCounter++}`;
151✔
3107
    }, []);
740✔
3108

740✔
3109
    const deleteRange = React.useCallback(
740✔
3110
        (r: Rectangle) => {
740✔
3111
            focus();
8✔
3112
            const editList: EditListItem[] = [];
8✔
3113
            for (let x = r.x; x < r.x + r.width; x++) {
8✔
3114
                for (let y = r.y; y < r.y + r.height; y++) {
23✔
3115
                    const cellValue = getCellContent([x - rowMarkerOffset, y]);
1,066✔
3116
                    if (!cellValue.allowOverlay && cellValue.kind !== GridCellKind.Boolean) continue;
1,066✔
3117
                    let newVal: InnerGridCell | undefined = undefined;
1,042✔
3118
                    if (cellValue.kind === GridCellKind.Custom) {
1,066✔
3119
                        const toDelete = getCellRenderer(cellValue);
1✔
3120
                        const editor = toDelete?.provideEditor?.({
1!
3121
                            ...cellValue,
×
3122
                            location: [x - rowMarkerOffset, y],
×
UNCOV
3123
                        });
×
3124
                        if (toDelete?.onDelete !== undefined) {
1✔
3125
                            newVal = toDelete.onDelete(cellValue);
1✔
3126
                        } else if (isObjectEditorCallbackResult(editor)) {
1!
UNCOV
3127
                            newVal = editor?.deletedValue?.(cellValue);
×
UNCOV
3128
                        }
×
3129
                    } else if (
1✔
3130
                        (isEditableGridCell(cellValue) && cellValue.allowOverlay) ||
1,041✔
3131
                        cellValue.kind === GridCellKind.Boolean
1✔
3132
                    ) {
1,041✔
3133
                        const toDelete = getCellRenderer(cellValue);
1,041✔
3134
                        newVal = toDelete?.onDelete?.(cellValue);
1,041✔
3135
                    }
1,041✔
3136
                    if (newVal !== undefined && !isInnerOnlyCell(newVal) && isEditableGridCell(newVal)) {
1,066✔
3137
                        editList.push({ location: [x, y], value: newVal });
1,041✔
3138
                    }
1,041✔
3139
                }
1,066✔
3140
            }
23✔
3141
            mangledOnCellsEdited(editList);
8✔
3142
            gridRef.current?.damage(editList.map(x => ({ cell: x.location })));
8✔
3143
        },
8✔
3144
        [focus, getCellContent, getCellRenderer, mangledOnCellsEdited, rowMarkerOffset]
740✔
3145
    );
740✔
3146

740✔
3147
    const overlayOpen = overlay !== undefined;
740✔
3148

740✔
3149
    const handleFixedKeybindings = React.useCallback(
740✔
3150
        (event: GridKeyEventArgs): boolean => {
740✔
3151
            const cancel = () => {
74✔
3152
                event.stopPropagation();
50✔
3153
                event.preventDefault();
50✔
3154
            };
50✔
3155

74✔
3156
            const details = {
74✔
3157
                didMatch: false,
74✔
3158
            };
74✔
3159

74✔
3160
            const { bounds } = event;
74✔
3161
            const selectedColumns = gridSelection.columns;
74✔
3162
            const selectedRows = gridSelection.rows;
74✔
3163

74✔
3164
            const keys = keybindings;
74✔
3165

74✔
3166
            if (!overlayOpen && isHotkey(keys.clear, event, details)) {
74✔
3167
                setGridSelection(emptyGridSelection, false);
2✔
3168
                onSelectionCleared?.();
2!
3169
            } else if (!overlayOpen && isHotkey(keys.selectAll, event, details)) {
74✔
3170
                setGridSelection(
1✔
3171
                    {
1✔
3172
                        columns: CompactSelection.empty(),
1✔
3173
                        rows: CompactSelection.empty(),
1✔
3174
                        current: {
1✔
3175
                            cell: gridSelection.current?.cell ?? [rowMarkerOffset, 0],
1!
3176
                            range: {
1✔
3177
                                x: rowMarkerOffset,
1✔
3178
                                y: 0,
1✔
3179
                                width: columnsIn.length,
1✔
3180
                                height: rows,
1✔
3181
                            },
1✔
3182
                            rangeStack: [],
1✔
3183
                        },
1✔
3184
                    },
1✔
3185
                    false
1✔
3186
                );
1✔
3187
            } else if (isHotkey(keys.search, event, details)) {
72!
UNCOV
3188
                searchInputRef?.current?.focus({ preventScroll: true });
×
UNCOV
3189
                setShowSearchInner(true);
×
3190
            } else if (isHotkey(keys.delete, event, details)) {
71✔
3191
                const callbackResult = onDelete?.(gridSelection) ?? true;
8✔
3192
                if (callbackResult !== false) {
8✔
3193
                    const toDelete = callbackResult === true ? gridSelection : callbackResult;
8✔
3194

8✔
3195
                    // delete order:
8✔
3196
                    // 1) primary range
8✔
3197
                    // 2) secondary ranges
8✔
3198
                    // 3) columns
8✔
3199
                    // 4) rows
8✔
3200

8✔
3201
                    if (toDelete.current !== undefined) {
8✔
3202
                        deleteRange(toDelete.current.range);
5✔
3203
                        for (const r of toDelete.current.rangeStack) {
5!
UNCOV
3204
                            deleteRange(r);
×
UNCOV
3205
                        }
×
3206
                    }
5✔
3207

8✔
3208
                    for (const r of toDelete.rows) {
8✔
3209
                        deleteRange({
1✔
3210
                            x: rowMarkerOffset,
1✔
3211
                            y: r,
1✔
3212
                            width: columnsIn.length,
1✔
3213
                            height: 1,
1✔
3214
                        });
1✔
3215
                    }
1✔
3216

8✔
3217
                    for (const col of toDelete.columns) {
8✔
3218
                        deleteRange({
1✔
3219
                            x: col,
1✔
3220
                            y: 0,
1✔
3221
                            width: 1,
1✔
3222
                            height: rows,
1✔
3223
                        });
1✔
3224
                    }
1✔
3225
                }
8✔
3226
            }
8✔
3227

74✔
3228
            if (details.didMatch) {
74✔
3229
                cancel();
11✔
3230
                return true;
11✔
3231
            }
11✔
3232

63✔
3233
            if (gridSelection.current === undefined) return false;
74✔
3234
            let [col, row] = gridSelection.current.cell;
60✔
3235
            const [, startRow] = gridSelection.current.cell;
60✔
3236
            let freeMove = false;
60✔
3237
            let cancelOnlyOnMove = false;
60✔
3238

60✔
3239
            if (isHotkey(keys.scrollToSelectedCell, event, details)) {
74!
3240
                scrollToRef.current(col - rowMarkerOffset, row);
×
3241
            } else if (columnSelect !== "none" && isHotkey(keys.selectColumn, event, details)) {
74✔
3242
                if (selectedColumns.hasIndex(col)) {
2!
UNCOV
3243
                    setSelectedColumns(selectedColumns.remove(col), undefined, true);
×
3244
                } else {
2✔
3245
                    if (columnSelect === "single") {
2!
UNCOV
3246
                        setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, true);
×
3247
                    } else {
2✔
3248
                        setSelectedColumns(undefined, col, true);
2✔
3249
                    }
2✔
3250
                }
2✔
3251
            } else if (rowSelect !== "none" && isHotkey(keys.selectRow, event, details)) {
60✔
3252
                if (selectedRows.hasIndex(row)) {
2!
UNCOV
3253
                    setSelectedRows(selectedRows.remove(row), undefined, true);
×
3254
                } else {
2✔
3255
                    if (rowSelect === "single") {
2!
UNCOV
3256
                        setSelectedRows(CompactSelection.fromSingleSelection(row), undefined, true);
×
3257
                    } else {
2✔
3258
                        setSelectedRows(undefined, row, true);
2✔
3259
                    }
2✔
3260
                }
2✔
3261
            } else if (!overlayOpen && bounds !== undefined && isHotkey(keys.activateCell, event, details)) {
58✔
3262
                if (row === rows && showTrailingBlankRow) {
7!
UNCOV
3263
                    window.setTimeout(() => {
×
UNCOV
3264
                        const customTargetColumn = getCustomNewRowTargetColumn(col);
×
UNCOV
3265
                        void appendRow(customTargetColumn ?? col);
×
UNCOV
3266
                    }, 0);
×
3267
                } else {
7✔
3268
                    onCellActivated?.([col - rowMarkerOffset, row]);
7✔
3269
                    reselect(bounds, true);
7✔
3270
                }
7✔
3271
            } else if (gridSelection.current.range.height > 1 && isHotkey(keys.downFill, event, details)) {
56✔
3272
                fillDown();
1✔
3273
            } else if (gridSelection.current.range.width > 1 && isHotkey(keys.rightFill, event, details)) {
49✔
3274
                fillRight();
1✔
3275
            } else if (isHotkey(keys.goToNextPage, event, details)) {
48✔
3276
                row += Math.max(1, visibleRegionRef.current.height - 4); // partial cell accounting
1✔
3277
            } else if (isHotkey(keys.goToPreviousPage, event, details)) {
47✔
3278
                row -= Math.max(1, visibleRegionRef.current.height - 4); // partial cell accounting
1✔
3279
            } else if (isHotkey(keys.goToFirstCell, event, details)) {
46✔
3280
                setOverlay(undefined);
1✔
3281
                row = 0;
1✔
3282
                col = 0;
1✔
3283
            } else if (isHotkey(keys.goToLastCell, event, details)) {
45✔
3284
                setOverlay(undefined);
1✔
3285
                row = Number.MAX_SAFE_INTEGER;
1✔
3286
                col = Number.MAX_SAFE_INTEGER;
1✔
3287
            } else if (isHotkey(keys.selectToFirstCell, event, details)) {
44✔
3288
                setOverlay(undefined);
1✔
3289
                adjustSelection([-2, -2]);
1✔
3290
            } else if (isHotkey(keys.selectToLastCell, event, details)) {
43✔
3291
                setOverlay(undefined);
1✔
3292
                adjustSelection([2, 2]);
1✔
3293
            } else if (!overlayOpen) {
42✔
3294
                if (isHotkey(keys.goDownCell, event, details)) {
37✔
3295
                    row += 1;
5✔
3296
                } else if (isHotkey(keys.goUpCell, event, details)) {
37✔
3297
                    row -= 1;
1✔
3298
                } else if (isHotkey(keys.goRightCell, event, details)) {
32✔
3299
                    col += 1;
2✔
3300
                } else if (isHotkey(keys.goLeftCell, event, details)) {
31✔
3301
                    col -= 1;
2✔
3302
                } else if (isHotkey(keys.goDownCellRetainSelection, event, details)) {
29!
3303
                    row += 1;
×
3304
                    freeMove = true;
×
3305
                } else if (isHotkey(keys.goUpCellRetainSelection, event, details)) {
27!
UNCOV
3306
                    row -= 1;
×
UNCOV
3307
                    freeMove = true;
×
3308
                } else if (isHotkey(keys.goRightCellRetainSelection, event, details)) {
27!
UNCOV
3309
                    col += 1;
×
UNCOV
3310
                    freeMove = true;
×
3311
                } else if (isHotkey(keys.goLeftCellRetainSelection, event, details)) {
27✔
3312
                    col -= 1;
1✔
3313
                    freeMove = true;
1✔
3314
                } else if (isHotkey(keys.goToLastRow, event, details)) {
27✔
3315
                    row = rows - 1;
1✔
3316
                } else if (isHotkey(keys.goToFirstRow, event, details)) {
26✔
3317
                    row = Number.MIN_SAFE_INTEGER;
1✔
3318
                } else if (isHotkey(keys.goToLastColumn, event, details)) {
25✔
3319
                    col = Number.MAX_SAFE_INTEGER;
2✔
3320
                } else if (isHotkey(keys.goToFirstColumn, event, details)) {
24✔
3321
                    col = Number.MIN_SAFE_INTEGER;
1✔
3322
                } else if (rangeSelect === "rect" || rangeSelect === "multi-rect") {
22!
3323
                    if (isHotkey(keys.selectGrowDown, event, details)) {
21✔
3324
                        adjustSelection([0, 1]);
1✔
3325
                    } else if (isHotkey(keys.selectGrowUp, event, details)) {
21!
UNCOV
3326
                        adjustSelection([0, -1]);
×
3327
                    } else if (isHotkey(keys.selectGrowRight, event, details)) {
20✔
3328
                        adjustSelection([1, 0]);
4✔
3329
                    } else if (isHotkey(keys.selectGrowLeft, event, details)) {
20✔
3330
                        adjustSelection([-1, 0]);
1✔
3331
                    } else if (isHotkey(keys.selectToLastRow, event, details)) {
16✔
3332
                        adjustSelection([0, 2]);
1✔
3333
                    } else if (isHotkey(keys.selectToFirstRow, event, details)) {
15!
UNCOV
3334
                        adjustSelection([0, -2]);
×
3335
                    } else if (isHotkey(keys.selectToLastColumn, event, details)) {
14✔
3336
                        adjustSelection([2, 0]);
1✔
3337
                    } else if (isHotkey(keys.selectToFirstColumn, event, details)) {
14!
UNCOV
3338
                        adjustSelection([-2, 0]);
×
UNCOV
3339
                    }
×
3340
                }
21✔
3341
                cancelOnlyOnMove = details.didMatch;
37✔
3342
            } else {
41✔
3343
                if (isHotkey(keys.closeOverlay, event, details)) {
4✔
3344
                    setOverlay(undefined);
2✔
3345
                }
2✔
3346

4✔
3347
                if (isHotkey(keys.acceptOverlayDown, event, details)) {
4✔
3348
                    setOverlay(undefined);
2✔
3349
                    row++;
2✔
3350
                }
2✔
3351

4✔
3352
                if (isHotkey(keys.acceptOverlayUp, event, details)) {
4!
3353
                    setOverlay(undefined);
×
3354
                    row--;
×
UNCOV
3355
                }
×
3356

4✔
3357
                if (isHotkey(keys.acceptOverlayLeft, event, details)) {
4!
3358
                    setOverlay(undefined);
×
3359
                    col--;
×
UNCOV
3360
                }
×
3361

4✔
3362
                if (isHotkey(keys.acceptOverlayRight, event, details)) {
4!
UNCOV
3363
                    setOverlay(undefined);
×
UNCOV
3364
                    col++;
×
UNCOV
3365
                }
×
3366
            }
4✔
3367
            // #endregion
60✔
3368

60✔
3369
            const mustRestrictRow = rowGroupingNavBehavior !== undefined && rowGroupingNavBehavior !== "normal";
74!
3370

74✔
3371
            if (mustRestrictRow && row !== startRow) {
74!
3372
                const skipUp =
×
3373
                    rowGroupingNavBehavior === "skip-up" ||
×
3374
                    rowGroupingNavBehavior === "skip" ||
×
3375
                    rowGroupingNavBehavior === "block";
×
3376
                const skipDown =
×
3377
                    rowGroupingNavBehavior === "skip-down" ||
×
3378
                    rowGroupingNavBehavior === "skip" ||
×
3379
                    rowGroupingNavBehavior === "block";
×
3380
                const didMoveUp = row < startRow;
×
3381
                if (didMoveUp && skipUp) {
×
3382
                    while (row >= 0 && mapper(row).isGroupHeader) {
×
3383
                        row--;
×
3384
                    }
×
3385

×
3386
                    if (row < 0) {
×
3387
                        row = startRow;
×
3388
                    }
×
3389
                } else if (!didMoveUp && skipDown) {
×
3390
                    while (row < rows && mapper(row).isGroupHeader) {
×
3391
                        row++;
×
3392
                    }
×
UNCOV
3393

×
UNCOV
3394
                    if (row >= rows) {
×
UNCOV
3395
                        row = startRow;
×
UNCOV
3396
                    }
×
UNCOV
3397
                }
×
UNCOV
3398
            }
✔
3399

60✔
3400
            const moved = updateSelectedCell(col, row, false, freeMove);
60✔
3401

60✔
3402
            const didMatch = details.didMatch;
60✔
3403

60✔
3404
            if (didMatch && (moved || !cancelOnlyOnMove || trapFocus)) {
74✔
3405
                cancel();
39✔
3406
            }
39✔
3407

60✔
3408
            return didMatch;
60✔
3409
        },
74✔
3410
        [
740✔
3411
            rowGroupingNavBehavior,
740✔
3412
            overlayOpen,
740✔
3413
            gridSelection,
740✔
3414
            keybindings,
740✔
3415
            columnSelect,
740✔
3416
            rowSelect,
740✔
3417
            rangeSelect,
740✔
3418
            rowMarkerOffset,
740✔
3419
            mapper,
740✔
3420
            rows,
740✔
3421
            updateSelectedCell,
740✔
3422
            setGridSelection,
740✔
3423
            onSelectionCleared,
740✔
3424
            columnsIn.length,
740✔
3425
            onDelete,
740✔
3426
            trapFocus,
740✔
3427
            deleteRange,
740✔
3428
            setSelectedColumns,
740✔
3429
            setSelectedRows,
740✔
3430
            showTrailingBlankRow,
740✔
3431
            getCustomNewRowTargetColumn,
740✔
3432
            appendRow,
740✔
3433
            onCellActivated,
740✔
3434
            reselect,
740✔
3435
            fillDown,
740✔
3436
            fillRight,
740✔
3437
            adjustSelection,
740✔
3438
        ]
740✔
3439
    );
740✔
3440

740✔
3441
    const onKeyDown = React.useCallback(
740✔
3442
        (event: GridKeyEventArgs) => {
740✔
3443
            let cancelled = false;
74✔
3444
            if (onKeyDownIn !== undefined) {
74✔
3445
                onKeyDownIn({
1✔
3446
                    ...event,
1✔
3447
                    ...(event.location && {
1✔
3448
                        location: [event.location[0] - rowMarkerOffset, event.location[1]] as any,
1✔
3449
                    }),
1✔
3450
                    cancel: () => {
1✔
UNCOV
3451
                        cancelled = true;
×
UNCOV
3452
                    },
×
3453
                });
1✔
3454
            }
1✔
3455

74✔
3456
            if (cancelled) return;
74!
3457

74✔
3458
            if (handleFixedKeybindings(event)) return;
74✔
3459

16✔
3460
            if (gridSelection.current === undefined) return;
16✔
3461
            const [col, row] = gridSelection.current.cell;
13✔
3462
            const vr = visibleRegionRef.current;
13✔
3463

13✔
3464
            if (
13✔
3465
                editOnType &&
13✔
3466
                !event.metaKey &&
13✔
3467
                !event.ctrlKey &&
13✔
3468
                gridSelection.current !== undefined &&
13✔
3469
                event.key.length === 1 &&
13✔
3470
                /[\p{L}\p{M}\p{N}\p{S}\p{P}]/u.test(event.key) &&
13✔
3471
                event.bounds !== undefined &&
13✔
3472
                isReadWriteCell(getCellContent([col - rowMarkerOffset, Math.max(0, Math.min(row, rows - 1))]))
13✔
3473
            ) {
74✔
3474
                if (
13✔
3475
                    (!showTrailingBlankRow || row !== rows) &&
13✔
3476
                    (vr.y > row || row > vr.y + vr.height || vr.x > col || col > vr.x + vr.width)
13✔
3477
                ) {
13!
UNCOV
3478
                    return;
×
UNCOV
3479
                }
×
3480
                onCellActivated?.([col - rowMarkerOffset, row]);
13✔
3481
                reselect(event.bounds, true, event.key);
13✔
3482
                event.stopPropagation();
13✔
3483
                event.preventDefault();
13✔
3484
            }
13✔
3485
        },
74✔
3486
        [
740✔
3487
            editOnType,
740✔
3488
            onKeyDownIn,
740✔
3489
            handleFixedKeybindings,
740✔
3490
            gridSelection,
740✔
3491
            getCellContent,
740✔
3492
            rowMarkerOffset,
740✔
3493
            rows,
740✔
3494
            showTrailingBlankRow,
740✔
3495
            onCellActivated,
740✔
3496
            reselect,
740✔
3497
        ]
740✔
3498
    );
740✔
3499

740✔
3500
    const onContextMenu = React.useCallback(
740✔
3501
        (args: GridMouseEventArgs, preventDefault: () => void) => {
740✔
3502
            const adjustedCol = args.location[0] - rowMarkerOffset;
7✔
3503
            if (args.kind === "header") {
7!
3504
                onHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
3505
            }
×
3506

7✔
3507
            if (args.kind === groupHeaderKind) {
7!
UNCOV
3508
                if (adjustedCol < 0) {
×
UNCOV
3509
                    return;
×
UNCOV
3510
                }
×
UNCOV
3511
                onGroupHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
UNCOV
3512
            }
×
3513

7✔
3514
            if (args.kind === "cell") {
7✔
3515
                const [col, row] = args.location;
7✔
3516
                onCellContextMenu?.([adjustedCol, row], {
7✔
3517
                    ...args,
7✔
3518
                    preventDefault,
7✔
3519
                });
7✔
3520

7✔
3521
                if (!gridSelectionHasItem(gridSelection, args.location)) {
7✔
3522
                    updateSelectedCell(col, row, false, false);
3✔
3523
                }
3✔
3524
            }
7✔
3525
        },
7✔
3526
        [
740✔
3527
            gridSelection,
740✔
3528
            onCellContextMenu,
740✔
3529
            onGroupHeaderContextMenu,
740✔
3530
            onHeaderContextMenu,
740✔
3531
            rowMarkerOffset,
740✔
3532
            updateSelectedCell,
740✔
3533
        ]
740✔
3534
    );
740✔
3535

740✔
3536
    const onPasteInternal = React.useCallback(
740✔
3537
        async (e?: ClipboardEvent) => {
740✔
3538
            if (!keybindings.paste) return;
6!
3539
            function pasteToCell(
6✔
3540
                inner: InnerGridCell,
51✔
3541
                target: Item,
51✔
3542
                rawValue: string | boolean | string[] | number | boolean | BooleanEmpty | BooleanIndeterminate,
51✔
3543
                formatted?: string | string[]
51✔
3544
            ): EditListItem | undefined {
51✔
3545
                const stringifiedRawValue =
51✔
3546
                    typeof rawValue === "object" ? rawValue?.join("\n") ?? "" : rawValue?.toString() ?? "";
51!
3547

51✔
3548
                if (!isInnerOnlyCell(inner) && isReadWriteCell(inner) && inner.readonly !== true) {
51✔
3549
                    const coerced = coercePasteValue?.(stringifiedRawValue, inner);
51!
3550
                    if (coerced !== undefined && isEditableGridCell(coerced)) {
51!
3551
                        if (process.env.NODE_ENV !== "production" && coerced.kind !== inner.kind) {
×
3552
                            // eslint-disable-next-line no-console
×
3553
                            console.warn("Coercion should not change cell kind.");
×
UNCOV
3554
                        }
×
UNCOV
3555
                        return {
×
UNCOV
3556
                            location: target,
×
UNCOV
3557
                            value: coerced,
×
UNCOV
3558
                        };
×
UNCOV
3559
                    }
×
3560
                    const r = getCellRenderer(inner);
51✔
3561
                    if (r === undefined) return undefined;
51!
3562
                    if (r.kind === GridCellKind.Custom) {
51✔
3563
                        assert(inner.kind === GridCellKind.Custom);
1✔
3564
                        const newVal = (r as unknown as CustomRenderer<CustomCell<any>>).onPaste?.(
1✔
3565
                            stringifiedRawValue,
1✔
3566
                            inner.data
1✔
3567
                        );
1✔
3568
                        if (newVal === undefined) return undefined;
1!
3569
                        return {
×
UNCOV
3570
                            location: target,
×
UNCOV
3571
                            value: {
×
UNCOV
3572
                                ...inner,
×
UNCOV
3573
                                data: newVal,
×
UNCOV
3574
                            },
×
UNCOV
3575
                        };
×
3576
                    } else {
51✔
3577
                        const newVal = r.onPaste?.(stringifiedRawValue, inner, {
50✔
3578
                            formatted,
50✔
3579
                            formattedString: typeof formatted === "string" ? formatted : formatted?.join("\n"),
50!
3580
                            rawValue,
50✔
3581
                        });
50✔
3582
                        if (newVal === undefined) return undefined;
50✔
3583
                        assert(newVal.kind === inner.kind);
36✔
3584
                        return {
36✔
3585
                            location: target,
36✔
3586
                            value: newVal,
36✔
3587
                        };
36✔
3588
                    }
36✔
3589
                }
51!
UNCOV
3590
                return undefined;
×
3591
            }
51✔
3592

6✔
3593
            const selectedColumns = gridSelection.columns;
6✔
3594
            const selectedRows = gridSelection.rows;
6✔
3595
            const focused =
6✔
3596
                scrollRef.current?.contains(document.activeElement) === true ||
6✔
3597
                canvasRef.current?.contains(document.activeElement) === true;
6✔
3598

6✔
3599
            let target: Item | undefined;
6✔
3600

6✔
3601
            if (gridSelection.current !== undefined) {
6✔
3602
                target = [gridSelection.current.range.x, gridSelection.current.range.y];
5✔
3603
            } else if (selectedColumns.length === 1) {
6!
UNCOV
3604
                target = [selectedColumns.first() ?? 0, 0];
×
3605
            } else if (selectedRows.length === 1) {
1!
UNCOV
3606
                target = [rowMarkerOffset, selectedRows.first() ?? 0];
×
UNCOV
3607
            }
×
3608

6✔
3609
            if (focused && target !== undefined) {
6✔
3610
                let data: CopyBuffer | undefined;
5✔
3611
                let text: string | undefined;
5✔
3612

5✔
3613
                const textPlain = "text/plain";
5✔
3614
                const textHtml = "text/html";
5✔
3615

5✔
3616
                if (navigator.clipboard.read !== undefined) {
5!
3617
                    const clipboardContent = await navigator.clipboard.read();
×
3618

×
3619
                    for (const item of clipboardContent) {
×
3620
                        if (item.types.includes(textHtml)) {
×
3621
                            const htmlBlob = await item.getType(textHtml);
×
3622
                            const html = await htmlBlob.text();
×
3623
                            const decoded = decodeHTML(html);
×
3624
                            if (decoded !== undefined) {
×
3625
                                data = decoded;
×
3626
                                break;
×
3627
                            }
×
UNCOV
3628
                        }
×
UNCOV
3629
                        if (item.types.includes(textPlain)) {
×
UNCOV
3630
                            // eslint-disable-next-line unicorn/no-await-expression-member
×
3631
                            text = await (await item.getType(textPlain)).text();
×
3632
                        }
×
3633
                    }
×
3634
                } else if (navigator.clipboard.readText !== undefined) {
5✔
3635
                    text = await navigator.clipboard.readText();
5✔
3636
                } else if (e !== undefined && e?.clipboardData !== null) {
5!
3637
                    if (e.clipboardData.types.includes(textHtml)) {
×
3638
                        const html = e.clipboardData.getData(textHtml);
×
3639
                        data = decodeHTML(html);
×
3640
                    }
×
UNCOV
3641
                    if (data === undefined && e.clipboardData.types.includes(textPlain)) {
×
UNCOV
3642
                        text = e.clipboardData.getData(textPlain);
×
UNCOV
3643
                    }
×
UNCOV
3644
                } else {
×
UNCOV
3645
                    return; // I didn't want to read that paste value anyway
×
UNCOV
3646
                }
×
3647

5✔
3648
                const [targetCol, targetRow] = target;
5✔
3649

5✔
3650
                const editList: EditListItem[] = [];
5✔
3651
                do {
5✔
3652
                    if (onPaste === undefined) {
5✔
3653
                        const cellData = getMangledCellContent(target);
2✔
3654
                        const rawValue = text ?? data?.map(r => r.map(cb => cb.rawValue).join("\t")).join("\t") ?? "";
2!
3655
                        const newVal = pasteToCell(cellData, target, rawValue, undefined);
2✔
3656
                        if (newVal !== undefined) {
2✔
3657
                            editList.push(newVal);
1✔
3658
                        }
1✔
3659
                        break;
2✔
3660
                    }
2✔
3661

3✔
3662
                    if (data === undefined) {
3✔
3663
                        if (text === undefined) return;
3!
3664
                        data = unquote(text);
3✔
3665
                    }
3✔
3666

3✔
3667
                    if (
3✔
3668
                        onPaste === false ||
3✔
3669
                        (typeof onPaste === "function" &&
3✔
3670
                            onPaste?.(
2✔
3671
                                [target[0] - rowMarkerOffset, target[1]],
2✔
3672
                                data.map(r => r.map(cb => cb.rawValue?.toString() ?? ""))
2!
3673
                            ) !== true)
2✔
3674
                    ) {
5!
UNCOV
3675
                        return;
×
UNCOV
3676
                    }
✔
3677

3✔
3678
                    for (const [row, dataRow] of data.entries()) {
5✔
3679
                        if (row + targetRow >= rows) break;
21!
3680
                        for (const [col, dataItem] of dataRow.entries()) {
21✔
3681
                            const index = [col + targetCol, row + targetRow] as const;
63✔
3682
                            const [writeCol, writeRow] = index;
63✔
3683
                            if (writeCol >= mangledCols.length) continue;
63✔
3684
                            if (writeRow >= mangledRows) continue;
49!
3685
                            const cellData = getMangledCellContent(index);
49✔
3686
                            const newVal = pasteToCell(cellData, index, dataItem.rawValue, dataItem.formatted);
49✔
3687
                            if (newVal !== undefined) {
63✔
3688
                                editList.push(newVal);
35✔
3689
                            }
35✔
3690
                        }
63✔
3691
                    }
21✔
3692
                    // eslint-disable-next-line no-constant-condition
3✔
3693
                } while (false);
5✔
3694

5✔
3695
                mangledOnCellsEdited(editList);
5✔
3696

5✔
3697
                gridRef.current?.damage(
5✔
3698
                    editList.map(c => ({
5✔
3699
                        cell: c.location,
36✔
3700
                    }))
5✔
3701
                );
5✔
3702
            }
5✔
3703
        },
6✔
3704
        [
740✔
3705
            coercePasteValue,
740✔
3706
            getCellRenderer,
740✔
3707
            getMangledCellContent,
740✔
3708
            gridSelection,
740✔
3709
            keybindings.paste,
740✔
3710
            scrollRef,
740✔
3711
            mangledCols.length,
740✔
3712
            mangledOnCellsEdited,
740✔
3713
            mangledRows,
740✔
3714
            onPaste,
740✔
3715
            rowMarkerOffset,
740✔
3716
            rows,
740✔
3717
        ]
740✔
3718
    );
740✔
3719

740✔
3720
    useEventListener("paste", onPasteInternal, safeWindow, false, true);
740✔
3721

740✔
3722
    // While this function is async, we deeply prefer not to await if we don't have to. This will lead to unpacking
740✔
3723
    // promises in rather awkward ways when possible to avoid awaiting. We have to use fallback copy mechanisms when
740✔
3724
    // an await has happened.
740✔
3725
    const onCopy = React.useCallback(
740✔
3726
        async (e?: ClipboardEvent, ignoreFocus?: boolean) => {
740✔
3727
            if (!keybindings.copy) return;
6!
3728
            const focused =
6✔
3729
                ignoreFocus === true ||
6✔
3730
                scrollRef.current?.contains(document.activeElement) === true ||
5✔
3731
                canvasRef.current?.contains(document.activeElement) === true;
5✔
3732

6✔
3733
            const selectedColumns = gridSelection.columns;
6✔
3734
            const selectedRows = gridSelection.rows;
6✔
3735

6✔
3736
            const copyToClipboardWithHeaders = (
6✔
3737
                cells: readonly (readonly GridCell[])[],
5✔
3738
                columnIndexes: readonly number[]
5✔
3739
            ) => {
5✔
3740
                if (!copyHeaders) {
5✔
3741
                    copyToClipboard(cells, columnIndexes, e);
5✔
3742
                } else {
5!
3743
                    const headers = columnIndexes.map(index => ({
×
3744
                        kind: GridCellKind.Text,
×
UNCOV
3745
                        data: columnsIn[index].title,
×
UNCOV
3746
                        displayData: columnsIn[index].title,
×
UNCOV
3747
                        allowOverlay: false,
×
UNCOV
3748
                    })) as GridCell[];
×
UNCOV
3749
                    copyToClipboard([headers, ...cells], columnIndexes, e);
×
UNCOV
3750
                }
×
3751
            };
5✔
3752

6✔
3753
            if (focused && getCellsForSelection !== undefined) {
6✔
3754
                if (gridSelection.current !== undefined) {
6✔
3755
                    let thunk = getCellsForSelection(gridSelection.current.range, abortControllerRef.current.signal);
3✔
3756
                    if (typeof thunk !== "object") {
3!
UNCOV
3757
                        thunk = await thunk();
×
UNCOV
3758
                    }
×
3759
                    copyToClipboardWithHeaders(
3✔
3760
                        thunk,
3✔
3761
                        range(
3✔
3762
                            gridSelection.current.range.x - rowMarkerOffset,
3✔
3763
                            gridSelection.current.range.x + gridSelection.current.range.width - rowMarkerOffset
3✔
3764
                        )
3✔
3765
                    );
3✔
3766
                } else if (selectedRows !== undefined && selectedRows.length > 0) {
3✔
3767
                    const toCopy = [...selectedRows];
1✔
3768
                    const cells = toCopy.map(rowIndex => {
1✔
3769
                        const thunk = getCellsForSelection(
1✔
3770
                            {
1✔
3771
                                x: rowMarkerOffset,
1✔
3772
                                y: rowIndex,
1✔
3773
                                width: columnsIn.length,
1✔
3774
                                height: 1,
1✔
3775
                            },
1✔
3776
                            abortControllerRef.current.signal
1✔
3777
                        );
1✔
3778
                        if (typeof thunk === "object") {
1✔
3779
                            return thunk[0];
1✔
3780
                        }
1!
UNCOV
3781
                        return thunk().then(v => v[0]);
×
3782
                    });
1✔
3783
                    if (cells.some(x => x instanceof Promise)) {
1!
UNCOV
3784
                        const settled = await Promise.all(cells);
×
UNCOV
3785
                        copyToClipboardWithHeaders(settled, range(columnsIn.length));
×
3786
                    } else {
1✔
3787
                        copyToClipboardWithHeaders(cells as (readonly GridCell[])[], range(columnsIn.length));
1✔
3788
                    }
1✔
3789
                } else if (selectedColumns.length > 0) {
3✔
3790
                    const results: (readonly (readonly GridCell[])[])[] = [];
1✔
3791
                    const cols: number[] = [];
1✔
3792
                    for (const col of selectedColumns) {
1✔
3793
                        let thunk = getCellsForSelection(
3✔
3794
                            {
3✔
3795
                                x: col,
3✔
3796
                                y: 0,
3✔
3797
                                width: 1,
3✔
3798
                                height: rows,
3✔
3799
                            },
3✔
3800
                            abortControllerRef.current.signal
3✔
3801
                        );
3✔
3802
                        if (typeof thunk !== "object") {
3!
3803
                            thunk = await thunk();
×
UNCOV
3804
                        }
×
3805
                        results.push(thunk);
3✔
3806
                        cols.push(col - rowMarkerOffset);
3✔
3807
                    }
3✔
3808
                    if (results.length === 1) {
1!
UNCOV
3809
                        copyToClipboardWithHeaders(results[0], cols);
×
3810
                    } else {
1✔
3811
                        // FIXME: this is dumb
1✔
3812
                        const toCopy = results.reduce((pv, cv) => pv.map((row, index) => [...row, ...cv[index]]));
1✔
3813
                        copyToClipboardWithHeaders(toCopy, cols);
1✔
3814
                    }
1✔
3815
                }
1✔
3816
            }
6✔
3817
        },
6✔
3818
        [
740✔
3819
            columnsIn,
740✔
3820
            getCellsForSelection,
740✔
3821
            gridSelection,
740✔
3822
            keybindings.copy,
740✔
3823
            rowMarkerOffset,
740✔
3824
            scrollRef,
740✔
3825
            rows,
740✔
3826
            copyHeaders,
740✔
3827
        ]
740✔
3828
    );
740✔
3829

740✔
3830
    useEventListener("copy", onCopy, safeWindow, false, false);
740✔
3831

740✔
3832
    const onCut = React.useCallback(
740✔
3833
        async (e?: ClipboardEvent) => {
740✔
3834
            if (!keybindings.cut) return;
1!
3835
            const focused =
1✔
3836
                scrollRef.current?.contains(document.activeElement) === true ||
1✔
3837
                canvasRef.current?.contains(document.activeElement) === true;
1✔
3838

1✔
3839
            if (!focused) return;
1!
3840
            await onCopy(e);
1✔
3841
            if (gridSelection.current !== undefined) {
1✔
3842
                let effectiveSelection: GridSelection = {
1✔
3843
                    current: {
1✔
3844
                        cell: gridSelection.current.cell,
1✔
3845
                        range: gridSelection.current.range,
1✔
3846
                        rangeStack: [],
1✔
3847
                    },
1✔
3848
                    rows: CompactSelection.empty(),
1✔
3849
                    columns: CompactSelection.empty(),
1✔
3850
                };
1✔
3851
                const onDeleteResult = onDelete?.(effectiveSelection);
1✔
3852
                if (onDeleteResult === false) return;
1!
3853
                effectiveSelection = onDeleteResult === true ? effectiveSelection : onDeleteResult;
1!
3854
                if (effectiveSelection.current === undefined) return;
1!
3855
                deleteRange(effectiveSelection.current.range);
1✔
3856
            }
1✔
3857
        },
1✔
3858
        [deleteRange, gridSelection, keybindings.cut, onCopy, scrollRef, onDelete]
740✔
3859
    );
740✔
3860

740✔
3861
    useEventListener("cut", onCut, safeWindow, false, false);
740✔
3862

740✔
3863
    const onSearchResultsChanged = React.useCallback(
740✔
3864
        (results: readonly Item[], navIndex: number) => {
740✔
3865
            if (onSearchResultsChangedIn !== undefined) {
7!
UNCOV
3866
                if (rowMarkerOffset !== 0) {
×
UNCOV
3867
                    results = results.map(item => [item[0] - rowMarkerOffset, item[1]]);
×
UNCOV
3868
                }
×
UNCOV
3869
                onSearchResultsChangedIn(results, navIndex);
×
3870
                return;
×
3871
            }
×
3872
            if (results.length === 0 || navIndex === -1) return;
7✔
3873

2✔
3874
            const [col, row] = results[navIndex];
2✔
3875
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
7!
UNCOV
3876
                return;
×
UNCOV
3877
            }
✔
3878
            lastSent.current = [col, row];
2✔
3879
            updateSelectedCell(col, row, false, false);
2✔
3880
        },
7✔
3881
        [onSearchResultsChangedIn, rowMarkerOffset, updateSelectedCell]
740✔
3882
    );
740✔
3883

740✔
3884
    // this effects purpose in life is to scroll the newly selected cell into view when and ONLY when that cell
740✔
3885
    // is from an external gridSelection change. Also note we want the unmangled out selection because scrollTo
740✔
3886
    // expects unmangled indexes
740✔
3887
    const [outCol, outRow] = gridSelectionOuter?.current?.cell ?? [];
740✔
3888
    const scrollToRef = React.useRef(scrollTo);
740✔
3889
    scrollToRef.current = scrollTo;
740✔
3890
    React.useLayoutEffect(() => {
740✔
3891
        if (
237✔
3892
            scrollToActiveCellRef.current &&
237✔
3893
            !hasJustScrolled.current &&
237✔
3894
            outCol !== undefined &&
237✔
3895
            outRow !== undefined &&
90✔
3896
            (outCol !== expectedExternalGridSelection.current?.current?.cell[0] ||
90✔
3897
                outRow !== expectedExternalGridSelection.current?.current?.cell[1])
90✔
3898
        ) {
237!
UNCOV
3899
            scrollToRef.current(outCol, outRow);
×
UNCOV
3900
        }
×
3901
        hasJustScrolled.current = false; //only allow skipping a single scroll
237✔
3902
    }, [outCol, outRow]);
740✔
3903

740✔
3904
    const selectionOutOfBounds =
740✔
3905
        gridSelection.current !== undefined &&
740✔
3906
        (gridSelection.current.cell[0] >= mangledCols.length || gridSelection.current.cell[1] >= mangledRows);
367✔
3907
    React.useLayoutEffect(() => {
740✔
3908
        if (selectionOutOfBounds) {
161✔
3909
            setGridSelection(emptyGridSelection, false);
1✔
3910
        }
1✔
3911
    }, [selectionOutOfBounds, setGridSelection]);
740✔
3912

740✔
3913
    const disabledRows = React.useMemo(() => {
740✔
3914
        if (showTrailingBlankRow === true && trailingRowOptions?.tint === true) {
154✔
3915
            return CompactSelection.fromSingleSelection(mangledRows - 1);
148✔
3916
        }
148✔
3917
        return CompactSelection.empty();
6✔
3918
    }, [mangledRows, showTrailingBlankRow, trailingRowOptions?.tint]);
740✔
3919

740✔
3920
    const mangledVerticalBorder = React.useCallback(
740✔
3921
        (col: number) => {
740✔
3922
            return typeof verticalBorder === "boolean"
7,937!
UNCOV
3923
                ? verticalBorder
×
3924
                : verticalBorder?.(col - rowMarkerOffset) ?? true;
7,937!
3925
        },
7,937✔
3926
        [rowMarkerOffset, verticalBorder]
740✔
3927
    );
740✔
3928

740✔
3929
    const renameGroupNode = React.useMemo(() => {
740✔
3930
        if (renameGroup === undefined || canvasRef.current === null) return null;
154✔
3931
        const { bounds, group } = renameGroup;
2✔
3932
        const canvasBounds = canvasRef.current.getBoundingClientRect();
2✔
3933
        return (
2✔
3934
            <GroupRename
2✔
3935
                bounds={bounds}
2✔
3936
                group={group}
2✔
3937
                canvasBounds={canvasBounds}
2✔
3938
                onClose={() => setRenameGroup(undefined)}
2✔
3939
                onFinish={newVal => {
2✔
3940
                    setRenameGroup(undefined);
1✔
3941
                    onGroupHeaderRenamed?.(group, newVal);
1✔
3942
                }}
1✔
3943
            />
2✔
3944
        );
154✔
3945
    }, [onGroupHeaderRenamed, renameGroup]);
740✔
3946

740✔
3947
    const mangledFreezeColumns = Math.min(mangledCols.length, freezeColumns + (hasRowMarkers ? 1 : 0));
740✔
3948

740✔
3949
    React.useImperativeHandle(
740✔
3950
        forwardedRef,
740✔
3951
        () => ({
740✔
3952
            appendRow: (col: number, openOverlay?: boolean) => appendRow(col + rowMarkerOffset, openOverlay),
30✔
3953
            appendColumn: (row: number, openOverlay?: boolean) => appendColumn(row, openOverlay),
30✔
3954
            updateCells: damageList => {
30✔
3955
                if (rowMarkerOffset !== 0) {
2✔
3956
                    damageList = damageList.map(x => ({ cell: [x.cell[0] + rowMarkerOffset, x.cell[1]] }));
1✔
3957
                }
1✔
3958
                return gridRef.current?.damage(damageList);
2✔
3959
            },
2✔
3960
            getBounds: (col, row) => {
30✔
3961
                if (canvasRef?.current === null || scrollRef?.current === null) {
2!
UNCOV
3962
                    return undefined;
×
UNCOV
3963
                }
×
3964

2✔
3965
                if (col === undefined && row === undefined) {
2✔
3966
                    // Return the bounds of the entire scroll area:
1✔
3967
                    const rect = canvasRef.current.getBoundingClientRect();
1✔
3968
                    const scale = rect.width / scrollRef.current.clientWidth;
1✔
3969
                    return {
1✔
3970
                        x: rect.x - scrollRef.current.scrollLeft * scale,
1✔
3971
                        y: rect.y - scrollRef.current.scrollTop * scale,
1✔
3972
                        width: scrollRef.current.scrollWidth * scale,
1✔
3973
                        height: scrollRef.current.scrollHeight * scale,
1✔
3974
                    };
1✔
3975
                }
1✔
3976
                return gridRef.current?.getBounds((col ?? 0) + rowMarkerOffset, row);
2!
3977
            },
2✔
3978
            focus: () => gridRef.current?.focus(),
30✔
3979
            emit: async e => {
30✔
3980
                switch (e) {
5✔
3981
                    case "delete":
5✔
3982
                        onKeyDown({
1✔
3983
                            bounds: undefined,
1✔
3984
                            cancel: () => undefined,
1✔
3985
                            stopPropagation: () => undefined,
1✔
3986
                            preventDefault: () => undefined,
1✔
3987
                            ctrlKey: false,
1✔
3988
                            key: "Delete",
1✔
3989
                            keyCode: 46,
1✔
3990
                            metaKey: false,
1✔
3991
                            shiftKey: false,
1✔
3992
                            altKey: false,
1✔
3993
                            rawEvent: undefined,
1✔
3994
                            location: undefined,
1✔
3995
                        });
1✔
3996
                        break;
1✔
3997
                    case "fill-right":
5✔
3998
                        onKeyDown({
1✔
3999
                            bounds: undefined,
1✔
4000
                            cancel: () => undefined,
1✔
4001
                            stopPropagation: () => undefined,
1✔
4002
                            preventDefault: () => undefined,
1✔
4003
                            ctrlKey: true,
1✔
4004
                            key: "r",
1✔
4005
                            keyCode: 82,
1✔
4006
                            metaKey: false,
1✔
4007
                            shiftKey: false,
1✔
4008
                            altKey: false,
1✔
4009
                            rawEvent: undefined,
1✔
4010
                            location: undefined,
1✔
4011
                        });
1✔
4012
                        break;
1✔
4013
                    case "fill-down":
5✔
4014
                        onKeyDown({
1✔
4015
                            bounds: undefined,
1✔
4016
                            cancel: () => undefined,
1✔
4017
                            stopPropagation: () => undefined,
1✔
4018
                            preventDefault: () => undefined,
1✔
4019
                            ctrlKey: true,
1✔
4020
                            key: "d",
1✔
4021
                            keyCode: 68,
1✔
4022
                            metaKey: false,
1✔
4023
                            shiftKey: false,
1✔
4024
                            altKey: false,
1✔
4025
                            rawEvent: undefined,
1✔
4026
                            location: undefined,
1✔
4027
                        });
1✔
4028
                        break;
1✔
4029
                    case "copy":
5✔
4030
                        await onCopy(undefined, true);
1✔
4031
                        break;
1✔
4032
                    case "paste":
5✔
4033
                        await onPasteInternal();
1✔
4034
                        break;
1✔
4035
                }
5✔
4036
            },
5✔
4037
            scrollTo,
30✔
4038
            remeasureColumns: cols => {
30✔
4039
                for (const col of cols) {
1✔
4040
                    void normalSizeColumn(col + rowMarkerOffset);
1✔
4041
                }
1✔
4042
            },
1✔
4043
            getMouseArgsForPosition: (
30✔
4044
                posX: number,
×
4045
                posY: number,
×
4046
                ev?: MouseEvent | TouchEvent
×
4047
            ): GridMouseEventArgs | undefined => {
×
4048
                if (gridRef?.current === null) {
×
4049
                    return undefined;
×
4050
                }
×
4051

×
4052
                const args = gridRef.current.getMouseArgsForPosition(posX, posY, ev);
×
4053
                if (args === undefined) {
×
4054
                    return undefined;
×
4055
                }
×
UNCOV
4056

×
NEW
4057
                return {
×
NEW
4058
                    ...args,
×
NEW
4059
                    location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
×
NEW
4060
                };
×
NEW
4061
            },
×
4062
        }),
30✔
4063
        [
740✔
4064
            appendRow,
740✔
4065
            appendColumn,
740✔
4066
            normalSizeColumn,
740✔
4067
            scrollRef,
740✔
4068
            onCopy,
740✔
4069
            onKeyDown,
740✔
4070
            onPasteInternal,
740✔
4071
            rowMarkerOffset,
740✔
4072
            scrollTo,
740✔
4073
        ]
740✔
4074
    );
740✔
4075

740✔
4076
    const [selCol, selRow] = currentCell ?? [];
740✔
4077
    const onCellFocused = React.useCallback(
740✔
4078
        (cell: Item) => {
740✔
4079
            const [col, row] = cell;
30✔
4080

30✔
4081
            if (row === -1) {
30!
UNCOV
4082
                if (columnSelect !== "none") {
×
UNCOV
4083
                    setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, false);
×
UNCOV
4084
                    focus();
×
UNCOV
4085
                }
×
UNCOV
4086
                return;
×
UNCOV
4087
            }
×
4088

30✔
4089
            if (selCol === col && selRow === row) return;
30✔
4090
            setCurrent(
1✔
4091
                {
1✔
4092
                    cell,
1✔
4093
                    range: { x: col, y: row, width: 1, height: 1 },
1✔
4094
                },
1✔
4095
                true,
1✔
4096
                false,
1✔
4097
                "keyboard-nav"
1✔
4098
            );
1✔
4099
            scrollTo(col, row);
1✔
4100
        },
30✔
4101
        [columnSelect, focus, scrollTo, selCol, selRow, setCurrent, setSelectedColumns]
740✔
4102
    );
740✔
4103

740✔
4104
    const [isFocused, setIsFocused] = React.useState(false);
740✔
4105
    const setIsFocusedDebounced = React.useRef(
740✔
4106
        debounce((val: boolean) => {
740✔
4107
            setIsFocused(val);
57✔
4108
        }, 5)
740✔
4109
    );
740✔
4110

740✔
4111
    const onCanvasFocused = React.useCallback(() => {
740✔
4112
        setIsFocusedDebounced.current(true);
76✔
4113

76✔
4114
        // check for mouse state, don't do anything if the user is clicked to focus.
76✔
4115
        if (
76✔
4116
            gridSelection.current === undefined &&
76✔
4117
            gridSelection.columns.length === 0 &&
6✔
4118
            gridSelection.rows.length === 0 &&
5✔
4119
            mouseState === undefined
5✔
4120
        ) {
76✔
4121
            setCurrent(
5✔
4122
                {
5✔
4123
                    cell: [rowMarkerOffset, cellYOffset],
5✔
4124
                    range: {
5✔
4125
                        x: rowMarkerOffset,
5✔
4126
                        y: cellYOffset,
5✔
4127
                        width: 1,
5✔
4128
                        height: 1,
5✔
4129
                    },
5✔
4130
                },
5✔
4131
                true,
5✔
4132
                false,
5✔
4133
                "keyboard-select"
5✔
4134
            );
5✔
4135
        }
5✔
4136
    }, [cellYOffset, gridSelection, mouseState, rowMarkerOffset, setCurrent]);
740✔
4137

740✔
4138
    const onFocusOut = React.useCallback(() => {
740✔
4139
        setIsFocusedDebounced.current(false);
39✔
4140
    }, []);
740✔
4141

740✔
4142
    const [idealWidth, idealHeight] = React.useMemo(() => {
740✔
4143
        let h: number;
167✔
4144
        const scrollbarWidth = experimental?.scrollbarWidthOverride ?? getScrollBarWidth();
167✔
4145
        const rowsCountWithTrailingRow = rows + (showTrailingBlankRow ? 1 : 0);
167✔
4146
        if (typeof rowHeight === "number") {
167✔
4147
            h = totalHeaderHeight + rowsCountWithTrailingRow * rowHeight;
166✔
4148
        } else {
167✔
4149
            let avg = 0;
1✔
4150
            const toAverage = Math.min(rowsCountWithTrailingRow, 10);
1✔
4151
            for (let i = 0; i < toAverage; i++) {
1✔
4152
                avg += rowHeight(i);
10✔
4153
            }
10✔
4154
            avg = Math.floor(avg / toAverage);
1✔
4155

1✔
4156
            h = totalHeaderHeight + rowsCountWithTrailingRow * avg;
1✔
4157
        }
1✔
4158
        h += scrollbarWidth;
167✔
4159

167✔
4160
        const w = mangledCols.reduce((acc, x) => x.width + acc, 0) + scrollbarWidth;
167✔
4161

167✔
4162
        // We need to set a reasonable cap here as some browsers will just ignore huge values
167✔
4163
        // rather than treat them as huge values.
167✔
4164
        return [`${Math.min(100_000, w)}px`, `${Math.min(100_000, h)}px`];
167✔
4165
    }, [mangledCols, experimental?.scrollbarWidthOverride, rowHeight, rows, showTrailingBlankRow, totalHeaderHeight]);
740✔
4166

740✔
4167
    const cssStyle = React.useMemo(() => {
740✔
4168
        return makeCSSStyle(mergedTheme);
151✔
4169
    }, [mergedTheme]);
740✔
4170

740✔
4171
    return (
740✔
4172
        <ThemeContext.Provider value={mergedTheme}>
740✔
4173
            <DataEditorContainer
740✔
4174
                style={cssStyle}
740✔
4175
                className={className}
740✔
4176
                inWidth={width ?? idealWidth}
740✔
4177
                inHeight={height ?? idealHeight}>
740✔
4178
                <DataGridSearch
740✔
4179
                    fillHandle={fillHandle}
740✔
4180
                    drawFocusRing={drawFocusRing}
740✔
4181
                    experimental={experimental}
740✔
4182
                    fixedShadowX={fixedShadowX}
740✔
4183
                    fixedShadowY={fixedShadowY}
740✔
4184
                    getRowThemeOverride={getRowThemeOverride}
740✔
4185
                    headerIcons={headerIcons}
740✔
4186
                    imageWindowLoader={imageWindowLoader}
740✔
4187
                    initialSize={initialSize}
740✔
4188
                    isDraggable={isDraggable}
740✔
4189
                    onDragLeave={onDragLeave}
740✔
4190
                    onRowMoved={onRowMoved}
740✔
4191
                    overscrollX={overscrollX}
740✔
4192
                    overscrollY={overscrollY}
740✔
4193
                    preventDiagonalScrolling={preventDiagonalScrolling}
740✔
4194
                    rightElement={rightElement}
740✔
4195
                    rightElementProps={rightElementProps}
740✔
4196
                    smoothScrollX={smoothScrollX}
740✔
4197
                    smoothScrollY={smoothScrollY}
740✔
4198
                    className={className}
740✔
4199
                    enableGroups={enableGroups}
740✔
4200
                    onCanvasFocused={onCanvasFocused}
740✔
4201
                    onCanvasBlur={onFocusOut}
740✔
4202
                    canvasRef={canvasRef}
740✔
4203
                    onContextMenu={onContextMenu}
740✔
4204
                    theme={mergedTheme}
740✔
4205
                    cellXOffset={cellXOffset}
740✔
4206
                    cellYOffset={cellYOffset}
740✔
4207
                    accessibilityHeight={visibleRegion.height}
740✔
4208
                    onDragEnd={onDragEnd}
740✔
4209
                    columns={mangledCols}
740✔
4210
                    nonGrowWidth={nonGrowWidth}
740✔
4211
                    drawHeader={drawHeader}
740✔
4212
                    onColumnProposeMove={onColumnProposeMoveImpl}
740✔
4213
                    drawCell={drawCell}
740✔
4214
                    disabledRows={disabledRows}
740✔
4215
                    freezeColumns={mangledFreezeColumns}
740✔
4216
                    lockColumns={rowMarkerOffset}
740✔
4217
                    firstColAccessible={rowMarkerOffset === 0}
740✔
4218
                    getCellContent={getMangledCellContent}
740✔
4219
                    minColumnWidth={minColumnWidth}
740✔
4220
                    maxColumnWidth={maxColumnWidth}
740✔
4221
                    searchInputRef={searchInputRef}
740✔
4222
                    showSearch={showSearch}
740✔
4223
                    onSearchClose={onSearchClose}
740✔
4224
                    highlightRegions={highlightRegions}
740✔
4225
                    getCellsForSelection={getCellsForSelection}
740✔
4226
                    getGroupDetails={mangledGetGroupDetails}
740✔
4227
                    headerHeight={headerHeight}
740✔
4228
                    isFocused={isFocused}
740✔
4229
                    groupHeaderHeight={enableGroups ? groupHeaderHeight : 0}
740✔
4230
                    freezeTrailingRows={
740✔
4231
                        freezeTrailingRows + (showTrailingBlankRow && trailingRowOptions?.sticky === true ? 1 : 0)
740✔
4232
                    }
740✔
4233
                    hasAppendRow={showTrailingBlankRow}
740✔
4234
                    onColumnResize={onColumnResize}
740✔
4235
                    onColumnResizeEnd={onColumnResizeEnd}
740✔
4236
                    onColumnResizeStart={onColumnResizeStart}
740✔
4237
                    onCellFocused={onCellFocused}
740✔
4238
                    onColumnMoved={onColumnMovedImpl}
740✔
4239
                    onDragStart={onDragStartImpl}
740✔
4240
                    onHeaderMenuClick={onHeaderMenuClickInner}
740✔
4241
                    onHeaderIndicatorClick={onHeaderIndicatorClickInner}
740✔
4242
                    onItemHovered={onItemHoveredImpl}
740✔
4243
                    isFilling={mouseState?.fillHandle === true}
740✔
4244
                    onMouseMove={onMouseMoveImpl}
740✔
4245
                    onKeyDown={onKeyDown}
740✔
4246
                    onKeyUp={onKeyUpIn}
740✔
4247
                    onMouseDown={onMouseDown}
740✔
4248
                    onMouseUp={onMouseUp}
740✔
4249
                    onDragOverCell={onDragOverCell}
740✔
4250
                    onDrop={onDrop}
740✔
4251
                    onSearchResultsChanged={onSearchResultsChanged}
740✔
4252
                    onVisibleRegionChanged={onVisibleRegionChangedImpl}
740✔
4253
                    clientSize={clientSize}
740✔
4254
                    rowHeight={rowHeight}
740✔
4255
                    searchResults={searchResults}
740✔
4256
                    searchValue={searchValue}
740✔
4257
                    onSearchValueChange={onSearchValueChange}
740✔
4258
                    rows={mangledRows}
740✔
4259
                    scrollRef={scrollRef}
740✔
4260
                    selection={gridSelection}
740✔
4261
                    translateX={visibleRegion.tx}
740✔
4262
                    translateY={visibleRegion.ty}
740✔
4263
                    verticalBorder={mangledVerticalBorder}
740✔
4264
                    gridRef={gridRef}
740✔
4265
                    getCellRenderer={getCellRenderer}
740✔
4266
                    resizeIndicator={resizeIndicator}
740✔
4267
                />
740✔
4268
                {renameGroupNode}
740✔
4269
                {overlay !== undefined && (
740✔
4270
                    <React.Suspense fallback={null}>
36✔
4271
                        <DataGridOverlayEditor
36✔
4272
                            {...overlay}
36✔
4273
                            validateCell={validateCell}
36✔
4274
                            bloom={editorBloom}
36✔
4275
                            id={overlayID}
36✔
4276
                            getCellRenderer={getCellRenderer}
36✔
4277
                            className={experimental?.isSubGrid === true ? "click-outside-ignore" : undefined}
36!
4278
                            provideEditor={provideEditor}
36✔
4279
                            imageEditorOverride={imageEditorOverride}
36✔
4280
                            portalElementRef={portalElementRef}
36✔
4281
                            onFinishEditing={onFinishEditing}
36✔
4282
                            markdownDivCreateNode={markdownDivCreateNode}
36✔
4283
                            isOutsideClick={isOutsideClick}
36✔
4284
                            customEventTarget={experimental?.eventTarget}
36✔
4285
                        />
36✔
4286
                    </React.Suspense>
36✔
4287
                )}
740✔
4288
            </DataEditorContainer>
740✔
4289
        </ThemeContext.Provider>
740✔
4290
    );
740✔
4291
};
740✔
4292

1✔
4293
/**
1✔
4294
 * The primary component of Glide Data Grid.
1✔
4295
 * @category DataEditor
1✔
4296
 * @param {DataEditorProps} props
1✔
4297
 */
1✔
4298
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