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

glideapps / glide-data-grid / 16380845235

18 Jul 2025 09:41PM UTC coverage: 90.987% (+0.03%) from 90.954%
16380845235

Pull #1070

github

web-flow
Merge da42bdefd into e7d8fce6d
Pull Request #1070: feat: draw grid lines for selected rows cols

2955 of 3670 branches covered (80.52%)

109 of 112 new or added lines in 5 files covered. (97.32%)

489 existing lines in 5 files now uncovered.

18110 of 19904 relevant lines covered (90.99%)

3096.01 hits per line

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

89.74
/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
     * When true (default) draws accent-coloured grid lines around selected columns in the header. Set to false to
1✔
692
     * revert to the original behaviour where only the header background is accented.
1✔
693
     * @group Style
1✔
694
     * @defaultValue true
1✔
695
     */
1✔
696
    readonly columnSelectionGridLines?: boolean;
1✔
697
}
1✔
698

1✔
699
type ScrollToFn = (
1✔
700
    col: number | { amount: number; unit: "cell" | "px" },
1✔
701
    row: number | { amount: number; unit: "cell" | "px" },
1✔
702
    dir?: "horizontal" | "vertical" | "both",
1✔
703
    paddingX?: number,
1✔
704
    paddingY?: number,
1✔
705
    options?: {
1✔
706
        hAlign?: "start" | "center" | "end";
1✔
707
        vAlign?: "start" | "center" | "end";
1✔
708
        behavior?: ScrollBehavior;
1✔
709
    }
1✔
710
) => void;
1✔
711

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

1✔
760
const loadingCell: GridCell = {
1✔
761
    kind: GridCellKind.Loading,
1✔
762
    allowOverlay: false,
1✔
763
};
1✔
764

1✔
765
export const emptyGridSelection: GridSelection = {
1✔
766
    columns: CompactSelection.empty(),
1✔
767
    rows: CompactSelection.empty(),
1✔
768
    current: undefined,
1✔
769
};
1✔
770

1✔
771
const DataEditorImpl: React.ForwardRefRenderFunction<DataEditorRef, DataEditorProps> = (p, forwardedRef) => {
1✔
772
    const [gridSelectionInner, setGridSelectionInner] = React.useState<GridSelection>(emptyGridSelection);
741✔
773

741✔
774
    const [overlay, setOverlay] = React.useState<{
741✔
775
        target: Rectangle;
741✔
776
        content: GridCell;
741✔
777
        theme: FullTheme;
741✔
778
        initialValue: string | undefined;
741✔
779
        cell: Item;
741✔
780
        highlight: boolean;
741✔
781
        forceEditMode: boolean;
741✔
782
    }>();
741✔
783
    const searchInputRef = React.useRef<HTMLInputElement | null>(null);
741✔
784
    const canvasRef = React.useRef<HTMLCanvasElement | null>(null);
741✔
785
    const [mouseState, setMouseState] = React.useState<MouseState>();
741✔
786
    const lastSent = React.useRef<[number, number]>();
741✔
787

741✔
788
    const safeWindow = typeof window === "undefined" ? null : window;
741!
789

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

741✔
906
    const drawFocusRing = drawFocusRingIn === "no-editor" ? overlay === undefined : drawFocusRingIn;
741!
907

741✔
908
    const rowMarkersObj = typeof p.rowMarkers === "string" ? undefined : p.rowMarkers;
741✔
909

741✔
910
    const rowMarkers = rowMarkersObj?.kind ?? (p.rowMarkers as RowMarkerOptions["kind"]) ?? "none";
741!
911
    const rowMarkerWidthRaw = rowMarkersObj?.width ?? p.rowMarkerWidth;
741!
912
    const rowMarkerStartIndex = rowMarkersObj?.startIndex ?? p.rowMarkerStartIndex ?? 1;
741!
913
    const rowMarkerTheme = rowMarkersObj?.theme ?? p.rowMarkerTheme;
741!
914
    const headerRowMarkerTheme = rowMarkersObj?.headerTheme;
741!
915
    const headerRowMarkerAlwaysVisible = rowMarkersObj?.headerAlwaysVisible;
741!
916
    const headerRowMarkerDisabled = rowSelect !== "multi" || rowMarkersObj?.headerDisabled === true;
741!
917
    const rowMarkerCheckboxStyle = rowMarkersObj?.checkboxStyle ?? "square";
741!
918

741✔
919
    const minColumnWidth = Math.max(minColumnWidthIn, 20);
741✔
920
    const maxColumnWidth = Math.max(maxColumnWidthIn, minColumnWidth);
741✔
921
    const maxColumnAutoWidth = Math.max(maxColumnAutoWidthIn ?? maxColumnWidth, minColumnWidth);
741✔
922

741✔
923
    const docStyle = React.useMemo(() => {
741✔
924
        if (typeof window === "undefined") return { fontSize: "16px" };
151!
925
        return window.getComputedStyle(document.documentElement);
151✔
926
    }, []);
741✔
927

741✔
928
    const {
741✔
929
        rows,
741✔
930
        rowNumberMapper,
741✔
931
        rowHeight: rowHeightPostGrouping,
741✔
932
        getRowThemeOverride,
741✔
933
    } = useRowGroupingInner(rowGrouping, rowsIn, rowHeightIn, getRowThemeOverrideIn);
741✔
934

741✔
935
    const remSize = React.useMemo(() => Number.parseFloat(docStyle.fontSize), [docStyle]);
741✔
936
    const { rowHeight, headerHeight, groupHeaderHeight, theme, overscrollX, overscrollY } = useRemAdjuster({
741✔
937
        groupHeaderHeight: groupHeaderHeightIn,
741✔
938
        headerHeight: headerHeightIn,
741✔
939
        overscrollX: overscrollXIn,
741✔
940
        overscrollY: overscrollYIn,
741✔
941
        remSize,
741✔
942
        rowHeight: rowHeightPostGrouping,
741✔
943
        scaleToRem,
741✔
944
        theme: themeIn,
741✔
945
    });
741✔
946

741✔
947
    const keybindings = useKeybindingsWithDefaults(keybindingsIn);
741✔
948

741✔
949
    const rowMarkerWidth = rowMarkerWidthRaw ?? (rowsIn > 10_000 ? 48 : rowsIn > 1000 ? 44 : rowsIn > 100 ? 36 : 32);
741!
950
    const hasRowMarkers = rowMarkers !== "none";
741✔
951
    const rowMarkerOffset = hasRowMarkers ? 1 : 0;
741✔
952
    const showTrailingBlankRow = trailingRowOptions !== undefined;
741✔
953
    const lastRowSticky = trailingRowOptions?.sticky === true;
741✔
954

741✔
955
    const [showSearchInner, setShowSearchInner] = React.useState(false);
741✔
956
    const showSearch = showSearchIn ?? showSearchInner;
741✔
957

741✔
958
    const onSearchClose = React.useCallback(() => {
741✔
959
        if (onSearchCloseIn !== undefined) {
2✔
960
            onSearchCloseIn();
2✔
961
        } else {
2!
UNCOV
962
            setShowSearchInner(false);
×
UNCOV
963
        }
×
964
    }, [onSearchCloseIn]);
741✔
965

741✔
966
    const gridSelectionOuterMangled: GridSelection | undefined = React.useMemo((): GridSelection | undefined => {
741✔
967
        return gridSelectionOuter === undefined ? undefined : shiftSelection(gridSelectionOuter, rowMarkerOffset);
290✔
968
    }, [gridSelectionOuter, rowMarkerOffset]);
741✔
969
    const gridSelection = gridSelectionOuterMangled ?? gridSelectionInner;
741✔
970

741✔
971
    const abortControllerRef = React.useRef() as React.MutableRefObject<AbortController>;
741✔
972
    if (abortControllerRef.current === undefined) abortControllerRef.current = new AbortController();
741✔
973

741✔
974
    React.useEffect(() => () => abortControllerRef?.current.abort(), []);
741✔
975

741✔
976
    const [getCellsForSelection, getCellsForSeletionDirect] = useCellsForSelection(
741✔
977
        getCellsForSelectionIn,
741✔
978
        getCellContent,
741✔
979
        rowMarkerOffset,
741✔
980
        abortControllerRef.current,
741✔
981
        rows
741✔
982
    );
741✔
983

741✔
984
    const validateCell = React.useCallback<NonNullable<typeof validateCellIn>>(
741✔
985
        (cell, newValue, prevValue) => {
741✔
986
            if (validateCellIn === undefined) return true;
17✔
987
            const item: Item = [cell[0] - rowMarkerOffset, cell[1]];
1✔
988
            return validateCellIn?.(item, newValue, prevValue);
1✔
989
        },
17✔
990
        [rowMarkerOffset, validateCellIn]
741✔
991
    );
741✔
992

741✔
993
    const expectedExternalGridSelection = React.useRef<GridSelection | undefined>(gridSelectionOuter);
741✔
994
    const setGridSelection = React.useCallback(
741✔
995
        (newVal: GridSelection, expand: boolean): void => {
741✔
996
            if (expand) {
185✔
997
                newVal = expandSelection(
142✔
998
                    newVal,
142✔
999
                    getCellsForSelection,
142✔
1000
                    rowMarkerOffset,
142✔
1001
                    spanRangeBehavior,
142✔
1002
                    abortControllerRef.current
142✔
1003
                );
142✔
1004
            }
142✔
1005
            if (onGridSelectionChange !== undefined) {
185✔
1006
                expectedExternalGridSelection.current = shiftSelection(newVal, -rowMarkerOffset);
143✔
1007
                onGridSelectionChange(expectedExternalGridSelection.current);
143✔
1008
            } else {
185✔
1009
                setGridSelectionInner(newVal);
42✔
1010
            }
42✔
1011
        },
185✔
1012
        [onGridSelectionChange, getCellsForSelection, rowMarkerOffset, spanRangeBehavior]
741✔
1013
    );
741✔
1014

741✔
1015
    const onColumnResize = whenDefined(
741✔
1016
        onColumnResizeIn,
741✔
1017
        React.useCallback<NonNullable<typeof onColumnResizeIn>>(
741✔
1018
            (_, w, ind, wg) => {
741✔
1019
                onColumnResizeIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
11✔
1020
            },
11✔
1021
            [onColumnResizeIn, rowMarkerOffset, columnsIn]
741✔
1022
        )
741✔
1023
    );
741✔
1024

741✔
1025
    const onColumnResizeEnd = whenDefined(
741✔
1026
        onColumnResizeEndIn,
741✔
1027
        React.useCallback<NonNullable<typeof onColumnResizeEndIn>>(
741✔
1028
            (_, w, ind, wg) => {
741✔
1029
                onColumnResizeEndIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
2✔
1030
            },
2✔
1031
            [onColumnResizeEndIn, rowMarkerOffset, columnsIn]
741✔
1032
        )
741✔
1033
    );
741✔
1034

741✔
1035
    const onColumnResizeStart = whenDefined(
741✔
1036
        onColumnResizeStartIn,
741✔
1037
        React.useCallback<NonNullable<typeof onColumnResizeStartIn>>(
741✔
1038
            (_, w, ind, wg) => {
741✔
UNCOV
1039
                onColumnResizeStartIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
×
UNCOV
1040
            },
×
1041
            [onColumnResizeStartIn, rowMarkerOffset, columnsIn]
741✔
1042
        )
741✔
1043
    );
741✔
1044

741✔
1045
    const drawHeader = whenDefined(
741✔
1046
        drawHeaderIn,
741✔
1047
        React.useCallback<NonNullable<typeof drawHeaderIn>>(
741✔
1048
            (args, draw) => {
741✔
1049
                return drawHeaderIn?.({ ...args, columnIndex: args.columnIndex - rowMarkerOffset }, draw) ?? false;
×
UNCOV
1050
            },
×
1051
            [drawHeaderIn, rowMarkerOffset]
741✔
1052
        )
741✔
1053
    );
741✔
1054

741✔
1055
    const drawCell = whenDefined(
741✔
1056
        drawCellIn,
741✔
1057
        React.useCallback<NonNullable<typeof drawCellIn>>(
741✔
1058
            (args, draw) => {
741✔
1059
                return drawCellIn?.({ ...args, col: args.col - rowMarkerOffset }, draw) ?? false;
×
UNCOV
1060
            },
×
1061
            [drawCellIn, rowMarkerOffset]
741✔
1062
        )
741✔
1063
    );
741✔
1064

741✔
1065
    const onDelete = React.useCallback<NonNullable<DataEditorProps["onDelete"]>>(
741✔
1066
        sel => {
741✔
1067
            if (onDeleteIn !== undefined) {
9✔
1068
                const result = onDeleteIn(shiftSelection(sel, -rowMarkerOffset));
5✔
1069
                if (typeof result === "boolean") {
5!
UNCOV
1070
                    return result;
×
UNCOV
1071
                }
×
1072
                return shiftSelection(result, rowMarkerOffset);
5✔
1073
            }
5✔
1074
            return true;
4✔
1075
        },
9✔
1076
        [onDeleteIn, rowMarkerOffset]
741✔
1077
    );
741✔
1078

741✔
1079
    const [setCurrent, setSelectedRows, setSelectedColumns] = useSelectionBehavior(
741✔
1080
        gridSelection,
741✔
1081
        setGridSelection,
741✔
1082
        rangeSelectionBlending,
741✔
1083
        columnSelectionBlending,
741✔
1084
        rowSelectionBlending,
741✔
1085
        rangeSelect,
741✔
1086
        rangeSelectionColumnSpanning
741✔
1087
    );
741✔
1088

741✔
1089
    const mergedTheme = React.useMemo(() => {
741✔
1090
        return mergeAndRealizeTheme(getDataEditorTheme(), theme);
151✔
1091
    }, [theme]);
741✔
1092

741✔
1093
    const [clientSize, setClientSize] = React.useState<readonly [number, number, number]>([0, 0, 0]);
741✔
1094

741✔
1095
    const rendererMap = React.useMemo(() => {
741✔
1096
        if (renderers === undefined) return {};
151!
1097
        const result: Partial<Record<InnerGridCellKind | GridCellKind, InternalCellRenderer<InnerGridCell>>> = {};
151✔
1098
        for (const r of renderers) {
151✔
1099
            result[r.kind] = r;
1,964✔
1100
        }
1,964✔
1101
        return result;
151✔
1102
    }, [renderers]);
741✔
1103

741✔
1104
    const getCellRenderer: <T extends InnerGridCell>(cell: T) => CellRenderer<T> | undefined = React.useCallback(
741✔
1105
        <T extends InnerGridCell>(cell: T) => {
741✔
1106
            if (cell.kind !== GridCellKind.Custom) {
148,541✔
1107
                return rendererMap[cell.kind] as unknown as CellRenderer<T>;
144,811✔
1108
            }
144,811✔
1109
            return additionalRenderers?.find(x => x.isMatch(cell)) as CellRenderer<T>;
148,541✔
1110
        },
148,541✔
1111
        [additionalRenderers, rendererMap]
741✔
1112
    );
741✔
1113

741✔
1114
    // eslint-disable-next-line prefer-const
741✔
1115
    let { sizedColumns: columns, nonGrowWidth } = useColumnSizer(
741✔
1116
        columnsIn,
741✔
1117
        rows,
741✔
1118
        getCellsForSeletionDirect,
741✔
1119
        clientSize[0] - (rowMarkerOffset === 0 ? 0 : rowMarkerWidth) - clientSize[2],
741✔
1120
        minColumnWidth,
741✔
1121
        maxColumnAutoWidth,
741✔
1122
        mergedTheme,
741✔
1123
        getCellRenderer,
741✔
1124
        abortControllerRef.current
741✔
1125
    );
741✔
1126
    if (rowMarkers !== "none") nonGrowWidth += rowMarkerWidth;
741✔
1127

741✔
1128
    const enableGroups = React.useMemo(() => {
741✔
1129
        return columns.some(c => c.group !== undefined);
152✔
1130
    }, [columns]);
741✔
1131

741✔
1132
    const totalHeaderHeight = enableGroups ? headerHeight + groupHeaderHeight : headerHeight;
741✔
1133

741✔
1134
    const numSelectedRows = gridSelection.rows.length;
741✔
1135
    const rowMarkerChecked =
741✔
1136
        rowMarkers === "none" ? undefined : numSelectedRows === 0 ? false : numSelectedRows === rows ? true : undefined;
741✔
1137

741✔
1138
    const mangledCols = React.useMemo(() => {
741✔
1139
        if (rowMarkers === "none") return columns;
166✔
1140
        return [
46✔
1141
            {
46✔
1142
                title: "",
46✔
1143
                width: rowMarkerWidth,
46✔
1144
                icon: undefined,
46✔
1145
                hasMenu: false,
46✔
1146
                style: "normal" as const,
46✔
1147
                themeOverride: rowMarkerTheme,
46✔
1148
                rowMarker: rowMarkerCheckboxStyle,
46✔
1149
                rowMarkerChecked,
46✔
1150
                headerRowMarkerTheme,
46✔
1151
                headerRowMarkerAlwaysVisible,
46✔
1152
                headerRowMarkerDisabled,
46✔
1153
            },
46✔
1154
            ...columns,
46✔
1155
        ];
46✔
1156
    }, [
741✔
1157
        rowMarkers,
741✔
1158
        columns,
741✔
1159
        rowMarkerWidth,
741✔
1160
        rowMarkerTheme,
741✔
1161
        rowMarkerCheckboxStyle,
741✔
1162
        rowMarkerChecked,
741✔
1163
        headerRowMarkerTheme,
741✔
1164
        headerRowMarkerAlwaysVisible,
741✔
1165
        headerRowMarkerDisabled,
741✔
1166
    ]);
741✔
1167

741✔
1168
    const visibleRegionRef = React.useRef<VisibleRegion>({
741✔
1169
        height: 1,
741✔
1170
        width: 1,
741✔
1171
        x: 0,
741✔
1172
        y: 0,
741✔
1173
    });
741✔
1174

741✔
1175
    const hasJustScrolled = React.useRef(false);
741✔
1176

741✔
1177
    const { setVisibleRegion, visibleRegion, scrollRef } = useInitialScrollOffset(
741✔
1178
        scrollOffsetX,
741✔
1179
        scrollOffsetY,
741✔
1180
        rowHeight,
741✔
1181
        visibleRegionRef,
741✔
1182
        () => (hasJustScrolled.current = true)
741✔
1183
    );
741✔
1184

741✔
1185
    visibleRegionRef.current = visibleRegion;
741✔
1186

741✔
1187
    const cellXOffset = visibleRegion.x + rowMarkerOffset;
741✔
1188
    const cellYOffset = visibleRegion.y;
741✔
1189

741✔
1190
    const gridRef = React.useRef<DataGridRef | null>(null);
741✔
1191

741✔
1192
    const focus = React.useCallback((immediate?: boolean) => {
741✔
1193
        if (immediate === true) {
135✔
1194
            gridRef.current?.focus();
12✔
1195
        } else {
135✔
1196
            window.requestAnimationFrame(() => {
123✔
1197
                gridRef.current?.focus();
122✔
1198
            });
123✔
1199
        }
123✔
1200
    }, []);
741✔
1201

741✔
1202
    const mangledRows = showTrailingBlankRow ? rows + 1 : rows;
741✔
1203

741✔
1204
    const mangledOnCellsEdited = React.useCallback<NonNullable<typeof onCellsEdited>>(
741✔
1205
        (items: readonly EditListItem[]) => {
741✔
1206
            const mangledItems =
29✔
1207
                rowMarkerOffset === 0
29✔
1208
                    ? items
24✔
1209
                    : items.map(x => ({
5✔
1210
                          ...x,
29✔
1211
                          location: [x.location[0] - rowMarkerOffset, x.location[1]] as const,
29✔
1212
                      }));
5✔
1213
            const r = onCellsEdited?.(mangledItems);
29✔
1214

29✔
1215
            if (r !== true) {
29✔
1216
                for (const i of mangledItems) onCellEdited?.(i.location, i.value);
28✔
1217
            }
28✔
1218

29✔
1219
            return r;
29✔
1220
        },
29✔
1221
        [onCellEdited, onCellsEdited, rowMarkerOffset]
741✔
1222
    );
741✔
1223

741✔
1224
    const [fillHighlightRegion, setFillHighlightRegion] = React.useState<Rectangle | undefined>();
741✔
1225

741✔
1226
    // this will generally be undefined triggering the memo less often
741✔
1227
    const highlightRange =
741✔
1228
        gridSelection.current !== undefined &&
741✔
1229
        gridSelection.current.range.width * gridSelection.current.range.height > 1
368✔
1230
            ? gridSelection.current.range
44✔
1231
            : undefined;
697✔
1232

741✔
1233
    const highlightFocus = drawFocusRing ? gridSelection.current?.cell : undefined;
741!
1234
    const highlightFocusCol = highlightFocus?.[0];
741✔
1235
    const highlightFocusRow = highlightFocus?.[1];
741✔
1236

741✔
1237
    const highlightRegions = React.useMemo(() => {
741✔
1238
        if (
305✔
1239
            (highlightRegionsIn === undefined || highlightRegionsIn.length === 0) &&
305✔
1240
            (highlightRange ?? highlightFocusCol ?? highlightFocusRow ?? fillHighlightRegion) === undefined
304✔
1241
        )
305✔
1242
            return undefined;
305✔
1243

158✔
1244
        const regions: Highlight[] = [];
158✔
1245

158✔
1246
        if (highlightRegionsIn !== undefined) {
298✔
1247
            for (const r of highlightRegionsIn) {
1✔
1248
                const maxWidth = mangledCols.length - r.range.x - rowMarkerOffset;
1✔
1249
                if (maxWidth > 0) {
1✔
1250
                    regions.push({
1✔
1251
                        color: r.color,
1✔
1252
                        range: {
1✔
1253
                            ...r.range,
1✔
1254
                            x: r.range.x + rowMarkerOffset,
1✔
1255
                            width: Math.min(maxWidth, r.range.width),
1✔
1256
                        },
1✔
1257
                        style: r.style,
1✔
1258
                    });
1✔
1259
                }
1✔
1260
            }
1✔
1261
        }
1✔
1262

158✔
1263
        if (fillHighlightRegion !== undefined) {
298✔
1264
            regions.push({
6✔
1265
                color: withAlpha(mergedTheme.accentColor, 0),
6✔
1266
                range: fillHighlightRegion,
6✔
1267
                style: "dashed",
6✔
1268
            });
6✔
1269
        }
6✔
1270

158✔
1271
        if (highlightRange !== undefined) {
298✔
1272
            regions.push({
30✔
1273
                color: withAlpha(mergedTheme.accentColor, 0.5),
30✔
1274
                range: highlightRange,
30✔
1275
                style: "solid-outline",
30✔
1276
            });
30✔
1277
        }
30✔
1278

158✔
1279
        if (highlightFocusCol !== undefined && highlightFocusRow !== undefined) {
305✔
1280
            regions.push({
157✔
1281
                color: mergedTheme.accentColor,
157✔
1282
                range: {
157✔
1283
                    x: highlightFocusCol,
157✔
1284
                    y: highlightFocusRow,
157✔
1285
                    width: 1,
157✔
1286
                    height: 1,
157✔
1287
                },
157✔
1288
                style: "solid-outline",
157✔
1289
            });
157✔
1290
        }
157✔
1291

158✔
1292
        return regions.length > 0 ? regions : undefined;
305!
1293
    }, [
741✔
1294
        fillHighlightRegion,
741✔
1295
        highlightRange,
741✔
1296
        highlightFocusCol,
741✔
1297
        highlightFocusRow,
741✔
1298
        highlightRegionsIn,
741✔
1299
        mangledCols.length,
741✔
1300
        mergedTheme.accentColor,
741✔
1301
        rowMarkerOffset,
741✔
1302
    ]);
741✔
1303

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

3,919✔
1330
                const maybeFirstColumnHint = isFirst ? trailingRowOptions?.hint ?? "" : "";
3,919✔
1331
                const c = mangledColsRef.current[col];
3,919✔
1332

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

26,505✔
1366
                    if (isOutsideMainArea && !isSelected && !isInFreezeArea) {
26,505!
UNCOV
1367
                        return loadingCell;
×
1368
                    }
×
1369
                }
26,505✔
1370
                let result = getCellContent([outerCol, row]);
143,624✔
1371
                if (rowMarkerOffset !== 0 && result.span !== undefined) {
143,624!
1372
                    result = {
×
UNCOV
1373
                        ...result,
×
UNCOV
1374
                        span: [result.span[0] + rowMarkerOffset, result.span[1] + rowMarkerOffset],
×
UNCOV
1375
                    };
×
1376
                }
×
1377
                return result;
143,624✔
1378
            }
143,624✔
1379
        },
149,665✔
1380
        [
741✔
1381
            showTrailingBlankRow,
741✔
1382
            mangledRows,
741✔
1383
            hasRowMarkers,
741✔
1384
            rowNumberMapper,
741✔
1385
            rowMarkerCheckboxStyle,
741✔
1386
            gridSelection?.rows,
741✔
1387
            rowMarkers,
741✔
1388
            rowMarkerStartIndex,
741✔
1389
            onRowMoved,
741✔
1390
            rowMarkerOffset,
741✔
1391
            trailingRowOptions?.hint,
741✔
1392
            trailingRowOptions?.addIcon,
741✔
1393
            experimental?.strict,
741✔
1394
            getCellContent,
741✔
1395
        ]
741✔
1396
    );
741✔
1397

741✔
1398
    const mangledGetGroupDetails = React.useCallback<NonNullable<DataEditorProps["getGroupDetails"]>>(
741✔
1399
        group => {
741✔
1400
            let result = getGroupDetails?.(group) ?? { name: group };
8,525✔
1401
            if (onGroupHeaderRenamed !== undefined && group !== "") {
8,525✔
1402
                result = {
88✔
1403
                    icon: result.icon,
88✔
1404
                    name: result.name,
88✔
1405
                    overrideTheme: result.overrideTheme,
88✔
1406
                    actions: [
88✔
1407
                        ...(result.actions ?? []),
88✔
1408
                        {
88✔
1409
                            title: "Rename",
88✔
1410
                            icon: "renameIcon",
88✔
1411
                            onClick: e =>
88✔
1412
                                setRenameGroup({
2✔
1413
                                    group: result.name,
2✔
1414
                                    bounds: e.bounds,
2✔
1415
                                }),
2✔
1416
                        },
88✔
1417
                    ],
88✔
1418
                };
88✔
1419
            }
88✔
1420
            return result;
8,525✔
1421
        },
8,525✔
1422
        [getGroupDetails, onGroupHeaderRenamed]
741✔
1423
    );
741✔
1424

741✔
1425
    const setOverlaySimple = React.useCallback(
741✔
1426
        (val: Omit<NonNullable<typeof overlay>, "theme">) => {
741✔
1427
            const [col, row] = val.cell;
25✔
1428
            const column = mangledCols[col];
25✔
1429
            const groupTheme =
25✔
1430
                column?.group !== undefined ? mangledGetGroupDetails(column.group)?.overrideTheme : undefined;
25!
1431
            const colTheme = column?.themeOverride;
25✔
1432
            const rowTheme = getRowThemeOverride?.(row);
25!
1433

25✔
1434
            setOverlay({
25✔
1435
                ...val,
25✔
1436
                theme: mergeAndRealizeTheme(mergedTheme, groupTheme, colTheme, rowTheme, val.content.themeOverride),
25✔
1437
            });
25✔
1438
        },
25✔
1439
        [getRowThemeOverride, mangledCols, mangledGetGroupDetails, mergedTheme]
741✔
1440
    );
741✔
1441

741✔
1442
    const reselect = React.useCallback(
741✔
1443
        (bounds: Rectangle, fromKeyboard: boolean, initialValue?: string) => {
741✔
1444
            if (gridSelection.current === undefined) return;
26!
1445

26✔
1446
            const [col, row] = gridSelection.current.cell;
26✔
1447
            const c = getMangledCellContent([col, row]);
26✔
1448
            if (c.kind !== GridCellKind.Boolean && c.allowOverlay) {
26✔
1449
                let content = c;
24✔
1450
                if (initialValue !== undefined) {
24✔
1451
                    switch (content.kind) {
13✔
1452
                        case GridCellKind.Number: {
13!
UNCOV
1453
                            const d = maybe(() => (initialValue === "-" ? -0 : Number.parseFloat(initialValue)), 0);
×
UNCOV
1454
                            content = {
×
UNCOV
1455
                                ...content,
×
UNCOV
1456
                                data: Number.isNaN(d) ? 0 : d,
×
UNCOV
1457
                            };
×
UNCOV
1458
                            break;
×
UNCOV
1459
                        }
×
1460
                        case GridCellKind.Text:
13✔
1461
                        case GridCellKind.Markdown:
13✔
1462
                        case GridCellKind.Uri:
13✔
1463
                            content = {
13✔
1464
                                ...content,
13✔
1465
                                data: initialValue,
13✔
1466
                            };
13✔
1467
                            break;
13✔
1468
                    }
13✔
1469
                }
13✔
1470

24✔
1471
                setOverlaySimple({
24✔
1472
                    target: bounds,
24✔
1473
                    content,
24✔
1474
                    initialValue,
24✔
1475
                    cell: [col, row],
24✔
1476
                    highlight: initialValue === undefined,
24✔
1477
                    forceEditMode: initialValue !== undefined,
24✔
1478
                });
24✔
1479
            } else if (c.kind === GridCellKind.Boolean && fromKeyboard && c.readonly !== true) {
26✔
1480
                mangledOnCellsEdited([
1✔
1481
                    {
1✔
1482
                        location: gridSelection.current.cell,
1✔
1483
                        value: {
1✔
1484
                            ...c,
1✔
1485
                            data: toggleBoolean(c.data),
1✔
1486
                        },
1✔
1487
                    },
1✔
1488
                ]);
1✔
1489
                gridRef.current?.damage([{ cell: gridSelection.current.cell }]);
1✔
1490
            }
1✔
1491
        },
26✔
1492
        [getMangledCellContent, gridSelection, mangledOnCellsEdited, setOverlaySimple]
741✔
1493
    );
741✔
1494

741✔
1495
    const focusOnRowFromTrailingBlankRow = React.useCallback(
741✔
1496
        (col: number, row: number) => {
741✔
1497
            const bounds = gridRef.current?.getBounds(col, row);
1✔
1498
            if (bounds === undefined || scrollRef.current === null) {
1!
UNCOV
1499
                return;
×
UNCOV
1500
            }
×
1501

1✔
1502
            const content = getMangledCellContent([col, row]);
1✔
1503
            if (!content.allowOverlay) {
1!
UNCOV
1504
                return;
×
UNCOV
1505
            }
×
1506

1✔
1507
            setOverlaySimple({
1✔
1508
                target: bounds,
1✔
1509
                content,
1✔
1510
                initialValue: undefined,
1✔
1511
                highlight: true,
1✔
1512
                cell: [col, row],
1✔
1513
                forceEditMode: true,
1✔
1514
            });
1✔
1515
        },
1✔
1516
        [getMangledCellContent, scrollRef, setOverlaySimple]
741✔
1517
    );
741✔
1518

741✔
1519
    const scrollTo = React.useCallback<ScrollToFn>(
741✔
1520
        (col, row, dir = "both", paddingX = 0, paddingY = 0, options = undefined): void => {
741✔
1521
            if (scrollRef.current !== null) {
53✔
1522
                const grid = gridRef.current;
53✔
1523
                const canvas = canvasRef.current;
53✔
1524

53✔
1525
                const trueCol = typeof col !== "number" ? (col.unit === "cell" ? col.amount : undefined) : col;
53!
1526
                const trueRow = typeof row !== "number" ? (row.unit === "cell" ? row.amount : undefined) : row;
53!
1527
                const desiredX = typeof col !== "number" && col.unit === "px" ? col.amount : undefined;
53!
1528
                const desiredY = typeof row !== "number" && row.unit === "px" ? row.amount : undefined;
53✔
1529
                if (grid !== null && canvas !== null) {
53✔
1530
                    let targetRect: Rectangle = {
53✔
1531
                        x: 0,
53✔
1532
                        y: 0,
53✔
1533
                        width: 0,
53✔
1534
                        height: 0,
53✔
1535
                    };
53✔
1536

53✔
1537
                    let scrollX = 0;
53✔
1538
                    let scrollY = 0;
53✔
1539

53✔
1540
                    if (trueCol !== undefined || trueRow !== undefined) {
53!
1541
                        targetRect = grid.getBounds((trueCol ?? 0) + rowMarkerOffset, trueRow ?? 0) ?? targetRect;
53!
1542
                        if (targetRect.width === 0 || targetRect.height === 0) return;
53!
1543
                    }
53✔
1544

53✔
1545
                    const scrollBounds = canvas.getBoundingClientRect();
53✔
1546
                    const scale = scrollBounds.width / canvas.offsetWidth;
53✔
1547

53✔
1548
                    if (desiredX !== undefined) {
53!
UNCOV
1549
                        targetRect = {
×
UNCOV
1550
                            ...targetRect,
×
UNCOV
1551
                            x: desiredX - scrollBounds.left - scrollRef.current.scrollLeft,
×
UNCOV
1552
                            width: 1,
×
UNCOV
1553
                        };
×
UNCOV
1554
                    }
×
1555
                    if (desiredY !== undefined) {
53✔
1556
                        targetRect = {
4✔
1557
                            ...targetRect,
4✔
1558
                            y: desiredY + scrollBounds.top - scrollRef.current.scrollTop,
4✔
1559
                            height: 1,
4✔
1560
                        };
4✔
1561
                    }
4✔
1562

53✔
1563
                    if (targetRect !== undefined) {
53✔
1564
                        const bounds = {
53✔
1565
                            x: targetRect.x - paddingX,
53✔
1566
                            y: targetRect.y - paddingY,
53✔
1567
                            width: targetRect.width + 2 * paddingX,
53✔
1568
                            height: targetRect.height + 2 * paddingY,
53✔
1569
                        };
53✔
1570

53✔
1571
                        let frozenWidth = 0;
53✔
1572
                        for (let i = 0; i < freezeColumns; i++) {
53!
UNCOV
1573
                            frozenWidth += columns[i].width;
×
UNCOV
1574
                        }
×
1575
                        let trailingRowHeight = 0;
53✔
1576
                        const freezeTrailingRowsEffective = freezeTrailingRows + (lastRowSticky ? 1 : 0);
53✔
1577
                        if (freezeTrailingRowsEffective > 0) {
53✔
1578
                            trailingRowHeight = getFreezeTrailingHeight(
51✔
1579
                                mangledRows,
51✔
1580
                                freezeTrailingRowsEffective,
51✔
1581
                                rowHeight
51✔
1582
                            );
51✔
1583
                        }
51✔
1584

53✔
1585
                        // scrollBounds is already scaled
53✔
1586
                        let sLeft = frozenWidth * scale + scrollBounds.left + rowMarkerOffset * rowMarkerWidth * scale;
53✔
1587
                        let sRight = scrollBounds.right;
53✔
1588
                        let sTop = scrollBounds.top + totalHeaderHeight * scale;
53✔
1589
                        let sBottom = scrollBounds.bottom - trailingRowHeight * scale;
53✔
1590

53✔
1591
                        const minx = targetRect.width + paddingX * 2;
53✔
1592
                        switch (options?.hAlign) {
53✔
1593
                            case "start":
53!
UNCOV
1594
                                sRight = sLeft + minx;
×
UNCOV
1595
                                break;
×
1596
                            case "end":
53!
UNCOV
1597
                                sLeft = sRight - minx;
×
UNCOV
1598
                                break;
×
1599
                            case "center":
53!
UNCOV
1600
                                sLeft = Math.floor((sLeft + sRight) / 2) - minx / 2;
×
UNCOV
1601
                                sRight = sLeft + minx;
×
UNCOV
1602
                                break;
×
1603
                        }
53✔
1604

53✔
1605
                        const miny = targetRect.height + paddingY * 2;
53✔
1606
                        switch (options?.vAlign) {
53✔
1607
                            case "start":
53✔
1608
                                sBottom = sTop + miny;
1✔
1609
                                break;
1✔
1610
                            case "end":
53✔
1611
                                sTop = sBottom - miny;
1✔
1612
                                break;
1✔
1613
                            case "center":
53✔
1614
                                sTop = Math.floor((sTop + sBottom) / 2) - miny / 2;
1✔
1615
                                sBottom = sTop + miny;
1✔
1616
                                break;
1✔
1617
                        }
53✔
1618

53✔
1619
                        if (sLeft > bounds.x) {
53!
UNCOV
1620
                            scrollX = bounds.x - sLeft;
×
1621
                        } else if (sRight < bounds.x + bounds.width) {
53✔
1622
                            scrollX = bounds.x + bounds.width - sRight;
7✔
1623
                        }
7✔
1624

53✔
1625
                        if (sTop > bounds.y) {
53!
UNCOV
1626
                            scrollY = bounds.y - sTop;
×
1627
                        } else if (sBottom < bounds.y + bounds.height) {
53✔
1628
                            scrollY = bounds.y + bounds.height - sBottom;
16✔
1629
                        }
16✔
1630

53✔
1631
                        if (dir === "vertical" || (typeof col === "number" && col < freezeColumns)) {
53✔
1632
                            scrollX = 0;
4✔
1633
                        } else if (
4✔
1634
                            dir === "horizontal" ||
49✔
1635
                            (typeof row === "number" && row >= mangledRows - freezeTrailingRowsEffective)
41✔
1636
                        ) {
49✔
1637
                            scrollY = 0;
10✔
1638
                        }
10✔
1639

53✔
1640
                        if (scrollX !== 0 || scrollY !== 0) {
53✔
1641
                            // Remove scaling as scrollTo method is unaffected by transform scale.
20✔
1642
                            if (scale !== 1) {
20!
UNCOV
1643
                                scrollX /= scale;
×
UNCOV
1644
                                scrollY /= scale;
×
UNCOV
1645
                            }
×
1646
                            scrollRef.current.scrollTo({
20✔
1647
                                left: scrollX + scrollRef.current.scrollLeft,
20✔
1648
                                top: scrollY + scrollRef.current.scrollTop,
20✔
1649
                                behavior: options?.behavior ?? "auto",
20✔
1650
                            });
20✔
1651
                        }
20✔
1652
                    }
53✔
1653
                }
53✔
1654
            }
53✔
1655
        },
53✔
1656
        [
741✔
1657
            rowMarkerOffset,
741✔
1658
            freezeTrailingRows,
741✔
1659
            rowMarkerWidth,
741✔
1660
            scrollRef,
741✔
1661
            totalHeaderHeight,
741✔
1662
            freezeColumns,
741✔
1663
            columns,
741✔
1664
            mangledRows,
741✔
1665
            lastRowSticky,
741✔
1666
            rowHeight,
741✔
1667
        ]
741✔
1668
    );
741✔
1669

741✔
1670
    const focusCallback = React.useRef(focusOnRowFromTrailingBlankRow);
741✔
1671
    const getCellContentRef = React.useRef(getCellContent);
741✔
1672

741✔
1673
    focusCallback.current = focusOnRowFromTrailingBlankRow;
741✔
1674
    getCellContentRef.current = getCellContent;
741✔
1675

741✔
1676
    const rowsRef = React.useRef(rows);
741✔
1677
    rowsRef.current = rows;
741✔
1678

741✔
1679
    const colsRef = React.useRef(mangledCols.length);
741✔
1680
    colsRef.current = mangledCols.length;
741✔
1681

741✔
1682
    const appendRow = React.useCallback(
741✔
1683
        async (col: number, openOverlay: boolean = true, behavior?: ScrollBehavior): Promise<void> => {
741✔
1684
            const c = mangledCols[col];
2✔
1685
            if (c?.trailingRowOptions?.disabled === true) {
2!
UNCOV
1686
                return;
×
UNCOV
1687
            }
×
1688
            const appendResult = onRowAppended?.();
2✔
1689

2✔
1690
            let r: "top" | "bottom" | number | undefined = undefined;
2✔
1691
            let bottom = true;
2✔
1692
            if (appendResult !== undefined) {
2!
UNCOV
1693
                r = await appendResult;
×
UNCOV
1694
                if (r === "top") bottom = false;
×
1695
                if (typeof r === "number") bottom = false;
×
1696
            }
×
1697

2✔
1698
            let backoff = 0;
2✔
1699
            const doFocus = () => {
2✔
1700
                if (rowsRef.current <= rows) {
4✔
1701
                    if (backoff < 500) {
2✔
1702
                        window.setTimeout(doFocus, backoff);
2✔
1703
                    }
2✔
1704
                    backoff = 50 + backoff * 2;
2✔
1705
                    return;
2✔
1706
                }
2✔
1707

2✔
1708
                const row = typeof r === "number" ? r : bottom ? rows : 0;
4!
1709
                scrollToRef.current(col - rowMarkerOffset, row, "both", 0, 0, behavior ? { behavior } : undefined);
4!
1710
                setCurrent(
4✔
1711
                    {
4✔
1712
                        cell: [col, row],
4✔
1713
                        range: {
4✔
1714
                            x: col,
4✔
1715
                            y: row,
4✔
1716
                            width: 1,
4✔
1717
                            height: 1,
4✔
1718
                        },
4✔
1719
                    },
4✔
1720
                    false,
4✔
1721
                    false,
4✔
1722
                    "edit"
4✔
1723
                );
4✔
1724

4✔
1725
                const cell = getCellContentRef.current([col - rowMarkerOffset, row]);
4✔
1726
                if (cell.allowOverlay && isReadWriteCell(cell) && cell.readonly !== true && openOverlay) {
4✔
1727
                    // wait for scroll to have a chance to process
1✔
1728
                    window.setTimeout(() => {
1✔
1729
                        focusCallback.current(col, row);
1✔
1730
                    }, 0);
1✔
1731
                }
1✔
1732
            };
4✔
1733
            // Queue up to allow the consumer to react to the event and let us check if they did
2✔
1734
            doFocus();
2✔
1735
        },
2✔
1736
        [mangledCols, onRowAppended, rowMarkerOffset, rows, setCurrent]
741✔
1737
    );
741✔
1738

741✔
1739
    const appendColumn = React.useCallback(
741✔
1740
        async (row: number, openOverlay: boolean = true): Promise<void> => {
741✔
1741
            const appendResult = onColumnAppended?.();
1✔
1742

1✔
1743
            let r: "left" | "right" | number | undefined = undefined;
1✔
1744
            let right = true;
1✔
1745
            if (appendResult !== undefined) {
1!
UNCOV
1746
                r = await appendResult;
×
UNCOV
1747
                if (r === "left") right = false;
×
UNCOV
1748
                if (typeof r === "number") right = false;
×
UNCOV
1749
            }
×
1750

1✔
1751
            let backoff = 0;
1✔
1752
            const doFocus = () => {
1✔
1753
                if (colsRef.current <= mangledCols.length) {
2✔
1754
                    if (backoff < 500) {
1✔
1755
                        window.setTimeout(doFocus, backoff);
1✔
1756
                    }
1✔
1757
                    backoff = 50 + backoff * 2;
1✔
1758
                    return;
1✔
1759
                }
1✔
1760

1✔
1761
                const col = typeof r === "number" ? r : right ? mangledCols.length : 0;
2!
1762
                scrollTo(col - rowMarkerOffset, row);
2✔
1763
                setCurrent(
2✔
1764
                    {
2✔
1765
                        cell: [col, row],
2✔
1766
                        range: {
2✔
1767
                            x: col,
2✔
1768
                            y: row,
2✔
1769
                            width: 1,
2✔
1770
                            height: 1,
2✔
1771
                        },
2✔
1772
                    },
2✔
1773
                    false,
2✔
1774
                    false,
2✔
1775
                    "edit"
2✔
1776
                );
2✔
1777

2✔
1778
                const cell = getCellContentRef.current([col - rowMarkerOffset, row]);
2✔
1779
                if (cell.allowOverlay && isReadWriteCell(cell) && cell.readonly !== true && openOverlay) {
2!
UNCOV
1780
                    window.setTimeout(() => {
×
UNCOV
1781
                        focusCallback.current(col, row);
×
UNCOV
1782
                    }, 0);
×
UNCOV
1783
                }
×
1784
            };
2✔
1785
            doFocus();
1✔
1786
        },
1✔
1787
        [mangledCols, onColumnAppended, rowMarkerOffset, scrollTo, setCurrent]
741✔
1788
    );
741✔
1789

741✔
1790
    const getCustomNewRowTargetColumn = React.useCallback(
741✔
1791
        (col: number): number | undefined => {
741✔
1792
            const customTargetColumn =
1✔
1793
                columns[col]?.trailingRowOptions?.targetColumn ?? trailingRowOptions?.targetColumn;
1!
1794

1✔
1795
            if (typeof customTargetColumn === "number") {
1!
UNCOV
1796
                const customTargetOffset = hasRowMarkers ? 1 : 0;
×
UNCOV
1797
                return customTargetColumn + customTargetOffset;
×
UNCOV
1798
            }
×
1799

1✔
1800
            if (typeof customTargetColumn === "object") {
1!
UNCOV
1801
                const maybeIndex = columnsIn.indexOf(customTargetColumn);
×
UNCOV
1802
                if (maybeIndex >= 0) {
×
UNCOV
1803
                    const customTargetOffset = hasRowMarkers ? 1 : 0;
×
UNCOV
1804
                    return maybeIndex + customTargetOffset;
×
1805
                }
×
1806
            }
×
1807

1✔
1808
            return undefined;
1✔
1809
        },
1✔
1810
        [columns, columnsIn, hasRowMarkers, trailingRowOptions?.targetColumn]
741✔
1811
    );
741✔
1812

741✔
1813
    const lastSelectedRowRef = React.useRef<number>();
741✔
1814
    const lastSelectedColRef = React.useRef<number>();
741✔
1815

741✔
1816
    const themeForCell = React.useCallback(
741✔
1817
        (cell: InnerGridCell, pos: Item): FullTheme => {
741✔
1818
            const [col, row] = pos;
28✔
1819
            return mergeAndRealizeTheme(
28✔
1820
                mergedTheme,
28✔
1821
                mangledCols[col]?.themeOverride,
28✔
1822
                getRowThemeOverride?.(row),
28!
1823
                cell.themeOverride
28✔
1824
            );
28✔
1825
        },
28✔
1826
        [getRowThemeOverride, mangledCols, mergedTheme]
741✔
1827
    );
741✔
1828

741✔
1829
    const { mapper } = useRowGrouping(rowGrouping, rowsIn);
741✔
1830

741✔
1831
    const rowGroupingNavBehavior = rowGrouping?.navigationBehavior;
741!
1832

741✔
1833
    const handleSelect = React.useCallback(
741✔
1834
        (args: GridMouseEventArgs) => {
741✔
1835
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
127!
1836
            const isMultiRow = isMultiKey && rowSelect === "multi";
127✔
1837
            const isMultiCol = isMultiKey && columnSelect === "multi";
127✔
1838
            const [col, row] = args.location;
127✔
1839
            const selectedColumns = gridSelection.columns;
127✔
1840
            const selectedRows = gridSelection.rows;
127✔
1841
            const [cellCol, cellRow] = gridSelection.current?.cell ?? [];
127✔
1842
            // eslint-disable-next-line unicorn/prefer-switch
127✔
1843
            if (args.kind === "cell") {
127✔
1844
                lastSelectedColRef.current = undefined;
111✔
1845

111✔
1846
                lastMouseSelectLocation.current = [col, row];
111✔
1847

111✔
1848
                if (col === 0 && hasRowMarkers) {
111✔
1849
                    if (
15✔
1850
                        (showTrailingBlankRow === true && row === rows) ||
15✔
1851
                        rowMarkers === "number" ||
15✔
1852
                        rowSelect === "none"
14✔
1853
                    )
15✔
1854
                        return;
15✔
1855

14✔
1856
                    const markerCell = getMangledCellContent(args.location);
14✔
1857
                    if (markerCell.kind !== InnerGridCellKind.Marker) {
15!
UNCOV
1858
                        return;
×
UNCOV
1859
                    }
✔
1860

14✔
1861
                    if (onRowMoved !== undefined) {
15!
UNCOV
1862
                        const renderer = getCellRenderer(markerCell);
×
UNCOV
1863
                        assert(renderer?.kind === InnerGridCellKind.Marker);
×
UNCOV
1864
                        const postClick = renderer?.onClick?.({
×
UNCOV
1865
                            ...args,
×
UNCOV
1866
                            cell: markerCell,
×
1867
                            posX: args.localEventX,
×
1868
                            posY: args.localEventY,
×
UNCOV
1869
                            bounds: args.bounds,
×
UNCOV
1870
                            theme: themeForCell(markerCell, args.location),
×
1871
                            preventDefault: () => undefined,
×
1872
                        }) as MarkerCell | undefined;
×
1873
                        if (postClick === undefined || postClick.checked === markerCell.checked) return;
×
1874
                    }
✔
1875

14✔
1876
                    setOverlay(undefined);
14✔
1877
                    focus();
14✔
1878
                    const isSelected = selectedRows.hasIndex(row);
14✔
1879

14✔
1880
                    const lastHighlighted = lastSelectedRowRef.current;
14✔
1881
                    if (
14✔
1882
                        rowSelect === "multi" &&
14✔
1883
                        (args.shiftKey || args.isLongTouch === true) &&
8✔
1884
                        lastHighlighted !== undefined &&
1✔
1885
                        selectedRows.hasIndex(lastHighlighted)
1✔
1886
                    ) {
15✔
1887
                        const newSlice: Slice = [Math.min(lastHighlighted, row), Math.max(lastHighlighted, row) + 1];
1✔
1888

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

89✔
1915
                        if (renderer?.onSelect !== undefined) {
89✔
1916
                            let prevented = false;
7✔
1917
                            renderer.onSelect({
7✔
1918
                                ...args,
7✔
1919
                                cell,
7✔
1920
                                posX: args.localEventX,
7✔
1921
                                posY: args.localEventY,
7✔
1922
                                bounds: args.bounds,
7✔
1923
                                preventDefault: () => (prevented = true),
7✔
1924
                                theme: themeForCell(cell, args.location),
7✔
1925
                            });
7✔
1926
                            if (prevented) {
7✔
1927
                                return;
4✔
1928
                            }
4✔
1929
                        }
7✔
1930

85✔
1931
                        if (rowGroupingNavBehavior === "block" && mapper(row).isGroupHeader) {
89!
UNCOV
1932
                            return;
×
UNCOV
1933
                        }
✔
1934

85✔
1935
                        const isLastStickyRow = lastRowSticky && row === rows;
85✔
1936

89✔
1937
                        const startedFromLastSticky =
89✔
1938
                            lastRowSticky && gridSelection !== undefined && gridSelection.current?.cell[1] === rows;
89✔
1939

89✔
1940
                        if (
89✔
1941
                            (args.shiftKey || args.isLongTouch === true) &&
89✔
1942
                            cellCol !== undefined &&
6✔
1943
                            cellRow !== undefined &&
6✔
1944
                            gridSelection.current !== undefined &&
6✔
1945
                            !startedFromLastSticky
6✔
1946
                        ) {
89✔
1947
                            if (isLastStickyRow) {
6!
UNCOV
1948
                                // If we're making a selection and shift click in to the last sticky row,
×
UNCOV
1949
                                // just drop the event. Don't kill the selection.
×
UNCOV
1950
                                return;
×
UNCOV
1951
                            }
×
1952

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

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

143✔
2092
            const time = performance.now();
143✔
2093
            mouseDownData.current = {
143✔
2094
                button: args.button,
143✔
2095
                time,
143✔
2096
                location: args.location,
143✔
2097
            };
143✔
2098

143✔
2099
            if (args?.kind === "header") {
144✔
2100
                isActivelyDraggingHeader.current = true;
17✔
2101
            }
17✔
2102

143✔
2103
            const fh = args.kind === "cell" && args.isFillHandle;
144✔
2104

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

136✔
2107
            setMouseState({
136✔
2108
                previousSelection: gridSelection,
136✔
2109
                fillHandle: fh,
136✔
2110
            });
136✔
2111
            lastMouseSelectLocation.current = undefined;
136✔
2112

136✔
2113
            if (!args.isTouch && args.button === 0 && !fh) {
144✔
2114
                handleSelect(args);
127✔
2115
            } else if (!args.isTouch && args.button === 1) {
137✔
2116
                lastMouseSelectLocation.current = args.location;
4✔
2117
            }
4✔
2118
        },
144✔
2119
        [gridSelection, handleSelect]
741✔
2120
    );
741✔
2121

741✔
2122
    const [renameGroup, setRenameGroup] = React.useState<{
741✔
2123
        group: string;
741✔
2124
        bounds: Rectangle;
741✔
2125
    }>();
741✔
2126

741✔
2127
    const handleGroupHeaderSelection = React.useCallback(
741✔
2128
        (args: GridMouseEventArgs) => {
741✔
2129
            if (args.kind !== groupHeaderKind || columnSelect !== "multi") {
4!
UNCOV
2130
                return;
×
UNCOV
2131
            }
×
2132
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
4!
2133
            const [col] = args.location;
4✔
2134
            const selectedColumns = gridSelection.columns;
4✔
2135

4✔
2136
            if (col < rowMarkerOffset) return;
4!
2137

4✔
2138
            const needle = mangledCols[col];
4✔
2139
            let start = col;
4✔
2140
            let end = col;
4✔
2141
            for (let i = col - 1; i >= rowMarkerOffset; i--) {
4✔
2142
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
4!
2143
                start--;
4✔
2144
            }
4✔
2145

4✔
2146
            for (let i = col + 1; i < mangledCols.length; i++) {
4✔
2147
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
36!
2148
                end++;
36✔
2149
            }
36✔
2150

4✔
2151
            focus();
4✔
2152

4✔
2153
            if (isMultiKey) {
4✔
2154
                if (selectedColumns.hasAll([start, end + 1])) {
2✔
2155
                    let newVal = selectedColumns;
1✔
2156
                    for (let index = start; index <= end; index++) {
1✔
2157
                        newVal = newVal.remove(index);
11✔
2158
                    }
11✔
2159
                    setSelectedColumns(newVal, undefined, isMultiKey);
1✔
2160
                } else {
1✔
2161
                    setSelectedColumns(undefined, [start, end + 1], isMultiKey);
1✔
2162
                }
1✔
2163
            } else {
2✔
2164
                setSelectedColumns(CompactSelection.fromSingleSelection([start, end + 1]), undefined, isMultiKey);
2✔
2165
            }
2✔
2166
        },
4✔
2167
        [columnSelect, focus, gridSelection.columns, mangledCols, rowMarkerOffset, setSelectedColumns]
741✔
2168
    );
741✔
2169

741✔
2170
    const isPrevented = React.useRef(false);
741✔
2171

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

741✔
2222
    const [scrollDir, setScrollDir] = React.useState<GridMouseEventArgs["scrollEdge"]>();
741✔
2223

741✔
2224
    const fillPattern = React.useCallback(
741✔
2225
        async (previousSelection: GridSelection, currentSelection: GridSelection) => {
741✔
2226
            const patternRange = previousSelection.current?.range;
7✔
2227

7✔
2228
            if (
7✔
2229
                patternRange === undefined ||
7✔
2230
                getCellsForSelection === undefined ||
7✔
2231
                currentSelection.current === undefined
7✔
2232
            ) {
7!
UNCOV
2233
                return;
×
UNCOV
2234
            }
×
2235
            const currentRange = currentSelection.current.range;
7✔
2236

7✔
2237
            if (onFillPattern !== undefined) {
7✔
2238
                let canceled = false;
1✔
2239
                onFillPattern({
1✔
2240
                    fillDestination: { ...currentRange, x: currentRange.x - rowMarkerOffset },
1✔
2241
                    patternSource: { ...patternRange, x: patternRange.x - rowMarkerOffset },
1✔
2242
                    preventDefault: () => (canceled = true),
1✔
2243
                });
1✔
2244
                if (canceled) return;
1!
2245
            }
1✔
2246

7✔
2247
            let cells = getCellsForSelection(patternRange, abortControllerRef.current.signal);
7✔
2248
            if (typeof cells !== "object") cells = await cells();
7!
2249

7✔
2250
            const pattern = cells;
7✔
2251

7✔
2252
            // loop through all cells in currentSelection.current.range
7✔
2253
            const editItemList: EditListItem[] = [];
7✔
2254
            for (let x = 0; x < currentRange.width; x++) {
7✔
2255
                for (let y = 0; y < currentRange.height; y++) {
9✔
2256
                    const cell: Item = [currentRange.x + x, currentRange.y + y];
41✔
2257
                    if (itemIsInRect(cell, patternRange)) continue;
41✔
2258
                    const patternCell = pattern[y % patternRange.height][x % patternRange.width];
29✔
2259
                    if (isInnerOnlyCell(patternCell) || !isReadWriteCell(patternCell)) continue;
41!
2260
                    editItemList.push({
29✔
2261
                        location: cell,
29✔
2262
                        value: { ...patternCell },
29✔
2263
                    });
29✔
2264
                }
29✔
2265
            }
9✔
2266
            mangledOnCellsEdited(editItemList);
7✔
2267

7✔
2268
            gridRef.current?.damage(
7✔
2269
                editItemList.map(c => ({
7✔
2270
                    cell: c.location,
29✔
2271
                }))
7✔
2272
            );
7✔
2273
        },
7✔
2274
        [getCellsForSelection, mangledOnCellsEdited, onFillPattern, rowMarkerOffset]
741✔
2275
    );
741✔
2276

741✔
2277
    const fillRight = React.useCallback(() => {
741✔
2278
        if (gridSelection.current === undefined || gridSelection.current.range.width <= 1) return;
1!
2279

1✔
2280
        const firstColSelection = {
1✔
2281
            ...gridSelection,
1✔
2282
            current: {
1✔
2283
                ...gridSelection.current,
1✔
2284
                range: {
1✔
2285
                    ...gridSelection.current.range,
1✔
2286
                    width: 1,
1✔
2287
                },
1✔
2288
            },
1✔
2289
        };
1✔
2290

1✔
2291
        void fillPattern(firstColSelection, gridSelection);
1✔
2292
    }, [fillPattern, gridSelection]);
741✔
2293

741✔
2294
    const fillDown = React.useCallback(() => {
741✔
2295
        if (gridSelection.current === undefined || gridSelection.current.range.height <= 1) return;
1!
2296

1✔
2297
        const firstRowSelection = {
1✔
2298
            ...gridSelection,
1✔
2299
            current: {
1✔
2300
                ...gridSelection.current,
1✔
2301
                range: {
1✔
2302
                    ...gridSelection.current.range,
1✔
2303
                    height: 1,
1✔
2304
                },
1✔
2305
            },
1✔
2306
        };
1✔
2307

1✔
2308
        void fillPattern(firstRowSelection, gridSelection);
1✔
2309
    }, [fillPattern, gridSelection]);
741✔
2310

741✔
2311
    const onMouseUp = React.useCallback(
741✔
2312
        (args: GridMouseEventArgs, isOutside: boolean) => {
741✔
2313
            const mouse = mouseState;
144✔
2314
            setMouseState(undefined);
144✔
2315
            setFillHighlightRegion(undefined);
144✔
2316
            setScrollDir(undefined);
144✔
2317
            isActivelyDraggingHeader.current = false;
144✔
2318

144✔
2319
            if (isOutside) return;
144✔
2320

143✔
2321
            if (
143✔
2322
                mouse?.fillHandle === true &&
144✔
2323
                gridSelection.current !== undefined &&
5✔
2324
                mouse.previousSelection?.current !== undefined
5✔
2325
            ) {
144✔
2326
                if (fillHighlightRegion === undefined) return;
5!
2327
                const newRange = {
5✔
2328
                    ...gridSelection,
5✔
2329
                    current: {
5✔
2330
                        ...gridSelection.current,
5✔
2331
                        range: combineRects(mouse.previousSelection.current.range, fillHighlightRegion),
5✔
2332
                    },
5✔
2333
                };
5✔
2334
                void fillPattern(mouse.previousSelection, newRange);
5✔
2335
                setGridSelection(newRange, true);
5✔
2336
                return;
5✔
2337
            }
5✔
2338

138✔
2339
            const [col, row] = args.location;
138✔
2340
            const [lastMouseDownCol, lastMouseDownRow] = lastMouseSelectLocation.current ?? [];
144✔
2341

144✔
2342
            const preventDefault = () => {
144✔
UNCOV
2343
                isPrevented.current = true;
×
UNCOV
2344
            };
×
2345

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

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

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

×
2431
                        onGroupHeaderContextMenu?.(clickLocation, { ...args, preventDefault });
×
2432
                        return;
×
2433
                    }
×
2434
                }
×
2435
                if (args.kind === "cell") {
×
2436
                    // click that cell
×
2437
                    if (!handleMaybeClick(args)) {
×
2438
                        handleSelect(args);
×
2439
                    }
×
2440
                } else if (args.kind === groupHeaderKind) {
×
2441
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
×
2442
                } else {
×
2443
                    if (args.kind === headerKind) {
×
2444
                        onHeaderClicked?.(clickLocation, {
×
2445
                            ...args,
×
2446
                            preventDefault,
×
2447
                        });
×
2448
                    }
×
2449
                    handleSelect(args);
×
2450
                }
×
2451
                return;
×
2452
            }
✔
2453

138✔
2454
            if (args.kind === "header") {
144✔
2455
                if (clickLocation < 0) {
17✔
2456
                    return;
3✔
2457
                }
3✔
2458

14✔
2459
                if (args.isEdge) {
17✔
2460
                    if (args.isDoubleClick === true) {
2✔
2461
                        void normalSizeColumn(col);
1✔
2462
                    }
1✔
2463
                } else if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
17✔
2464
                    onHeaderClicked?.(clickLocation, { ...args, preventDefault });
6✔
2465
                }
6✔
2466
            }
17✔
2467

135✔
2468
            if (args.kind === groupHeaderKind) {
144✔
2469
                if (clickLocation < 0) {
4!
UNCOV
2470
                    return;
×
UNCOV
2471
                }
×
2472

4✔
2473
                if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
4✔
2474
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
4✔
2475
                    if (!isPrevented.current) {
4✔
2476
                        handleGroupHeaderSelection(args);
4✔
2477
                    }
4✔
2478
                }
4✔
2479
            }
4✔
2480

135✔
2481
            if (args.kind === "cell" && (args.button === 0 || args.button === 1)) {
144✔
2482
                handleMaybeClick(args);
113✔
2483
            }
113✔
2484

135✔
2485
            lastMouseSelectLocation.current = undefined;
135✔
2486
        },
144✔
2487
        [
741✔
2488
            mouseState,
741✔
2489
            gridSelection,
741✔
2490
            rowMarkerOffset,
741✔
2491
            fillHighlightRegion,
741✔
2492
            fillPattern,
741✔
2493
            setGridSelection,
741✔
2494
            onCellClicked,
741✔
2495
            getMangledCellContent,
741✔
2496
            getCellRenderer,
741✔
2497
            cellActivationBehavior,
741✔
2498
            themeForCell,
741✔
2499
            mangledOnCellsEdited,
741✔
2500
            onCellActivated,
741✔
2501
            reselect,
741✔
2502
            onCellContextMenu,
741✔
2503
            onHeaderContextMenu,
741✔
2504
            onGroupHeaderContextMenu,
741✔
2505
            handleSelect,
741✔
2506
            onGroupHeaderClicked,
741✔
2507
            onHeaderClicked,
741✔
2508
            normalSizeColumn,
741✔
2509
            handleGroupHeaderSelection,
741✔
2510
        ]
741✔
2511
    );
741✔
2512

741✔
2513
    const onMouseMoveImpl = React.useCallback(
741✔
2514
        (args: GridMouseEventArgs) => {
741✔
2515
            const a: GridMouseEventArgs = {
39✔
2516
                ...args,
39✔
2517
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
39✔
2518
            };
39✔
2519
            onMouseMove?.(a);
39✔
2520

39✔
2521
            if (mouseState !== undefined && args.buttons === 0) {
39✔
2522
                setMouseState(undefined);
6✔
2523
                setFillHighlightRegion(undefined);
6✔
2524
                setScrollDir(undefined);
6✔
2525
                isActivelyDraggingHeader.current = false;
6✔
2526
            }
6✔
2527

39✔
2528
            setScrollDir(cv => {
39✔
2529
                if (isActivelyDraggingHeader.current) return [args.scrollEdge[0], 0];
39✔
2530
                if (args.scrollEdge[0] === cv?.[0] && args.scrollEdge[1] === cv[1]) return cv;
39✔
2531
                return mouseState === undefined || (mouseDownData.current?.location[0] ?? 0) < rowMarkerOffset
39!
2532
                    ? undefined
13✔
2533
                    : args.scrollEdge;
16✔
2534
            });
39✔
2535
        },
39✔
2536
        [mouseState, onMouseMove, rowMarkerOffset]
741✔
2537
    );
741✔
2538

741✔
2539
    const onHeaderMenuClickInner = React.useCallback(
741✔
2540
        (col: number, screenPosition: Rectangle) => {
741✔
2541
            onHeaderMenuClick?.(col - rowMarkerOffset, screenPosition);
1✔
2542
        },
1✔
2543
        [onHeaderMenuClick, rowMarkerOffset]
741✔
2544
    );
741✔
2545

741✔
2546
    const onHeaderIndicatorClickInner = React.useCallback(
741✔
2547
        (col: number, screenPosition: Rectangle) => {
741✔
UNCOV
2548
            onHeaderIndicatorClick?.(col - rowMarkerOffset, screenPosition);
×
UNCOV
2549
        },
×
2550
        [onHeaderIndicatorClick, rowMarkerOffset]
741✔
2551
    );
741✔
2552

741✔
2553
    const currentCell = gridSelection?.current?.cell;
741✔
2554
    const onVisibleRegionChangedImpl = React.useCallback(
741✔
2555
        (
741✔
2556
            region: Rectangle,
156✔
2557
            clientWidth: number,
156✔
2558
            clientHeight: number,
156✔
2559
            rightElWidth: number,
156✔
2560
            tx: number,
156✔
2561
            ty: number
156✔
2562
        ) => {
156✔
2563
            hasJustScrolled.current = false;
156✔
2564
            let selected = currentCell;
156✔
2565
            if (selected !== undefined) {
156✔
2566
                selected = [selected[0] - rowMarkerOffset, selected[1]];
11✔
2567
            }
11✔
2568

156✔
2569
            const freezeRegion =
156✔
2570
                freezeColumns === 0
156✔
2571
                    ? undefined
155✔
2572
                    : {
1✔
2573
                          x: 0,
1✔
2574
                          y: region.y,
1✔
2575
                          width: freezeColumns,
1✔
2576
                          height: region.height,
1✔
2577
                      };
1✔
2578

156✔
2579
            const freezeRegions: Rectangle[] = [];
156✔
2580
            if (freezeRegion !== undefined) freezeRegions.push(freezeRegion);
156✔
2581
            if (freezeTrailingRows > 0) {
156✔
2582
                freezeRegions.push({
1✔
2583
                    x: region.x - rowMarkerOffset,
1✔
2584
                    y: rows - freezeTrailingRows,
1✔
2585
                    width: region.width,
1✔
2586
                    height: freezeTrailingRows,
1✔
2587
                });
1✔
2588

1✔
2589
                if (freezeColumns > 0) {
1✔
2590
                    freezeRegions.push({
1✔
2591
                        x: 0,
1✔
2592
                        y: rows - freezeTrailingRows,
1✔
2593
                        width: freezeColumns,
1✔
2594
                        height: freezeTrailingRows,
1✔
2595
                    });
1✔
2596
                }
1✔
2597
            }
1✔
2598

156✔
2599
            const newRegion = {
156✔
2600
                x: region.x - rowMarkerOffset,
156✔
2601
                y: region.y,
156✔
2602
                width: region.width,
156✔
2603
                height: showTrailingBlankRow && region.y + region.height >= rows ? region.height - 1 : region.height,
156✔
2604
                tx,
156✔
2605
                ty,
156✔
2606
                extras: {
156✔
2607
                    selected,
156✔
2608
                    freezeRegion,
156✔
2609
                    freezeRegions,
156✔
2610
                },
156✔
2611
            };
156✔
2612
            visibleRegionRef.current = newRegion;
156✔
2613
            setVisibleRegion(newRegion);
156✔
2614
            setClientSize([clientWidth, clientHeight, rightElWidth]);
156✔
2615
            onVisibleRegionChanged?.(newRegion, newRegion.tx, newRegion.ty, newRegion.extras);
156✔
2616
        },
156✔
2617
        [
741✔
2618
            currentCell,
741✔
2619
            rowMarkerOffset,
741✔
2620
            showTrailingBlankRow,
741✔
2621
            rows,
741✔
2622
            freezeColumns,
741✔
2623
            freezeTrailingRows,
741✔
2624
            setVisibleRegion,
741✔
2625
            onVisibleRegionChanged,
741✔
2626
        ]
741✔
2627
    );
741✔
2628

741✔
2629
    const onColumnProposeMoveImpl = whenDefined(
741✔
2630
        onColumnProposeMove,
741✔
2631
        React.useCallback(
741✔
2632
            (startIndex: number, endIndex: number) => {
741✔
UNCOV
2633
                return onColumnProposeMove?.(startIndex - rowMarkerOffset, endIndex - rowMarkerOffset) !== false;
×
UNCOV
2634
            },
×
2635
            [onColumnProposeMove, rowMarkerOffset]
741✔
2636
        )
741✔
2637
    );
741✔
2638

741✔
2639
    const onColumnMovedImpl = whenDefined(
741✔
2640
        onColumnMoved,
741✔
2641
        React.useCallback(
741✔
2642
            (startIndex: number, endIndex: number) => {
741✔
2643
                onColumnMoved?.(startIndex - rowMarkerOffset, endIndex - rowMarkerOffset);
1✔
2644
                if (columnSelect !== "none") {
1✔
2645
                    setSelectedColumns(CompactSelection.fromSingleSelection(endIndex), undefined, true);
1✔
2646
                }
1✔
2647
            },
1✔
2648
            [columnSelect, onColumnMoved, rowMarkerOffset, setSelectedColumns]
741✔
2649
        )
741✔
2650
    );
741✔
2651

741✔
2652
    const isActivelyDragging = React.useRef(false);
741✔
2653
    const onDragStartImpl = React.useCallback(
741✔
2654
        (args: GridDragEventArgs) => {
741✔
2655
            if (args.location[0] === 0 && rowMarkerOffset > 0) {
1!
UNCOV
2656
                args.preventDefault();
×
UNCOV
2657
                return;
×
UNCOV
2658
            }
×
2659
            onDragStart?.({
1✔
2660
                ...args,
1✔
2661
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
1✔
2662
            });
1✔
2663

1✔
2664
            if (!args.defaultPrevented()) {
1✔
2665
                isActivelyDragging.current = true;
1✔
2666
            }
1✔
2667
            setMouseState(undefined);
1✔
2668
        },
1✔
2669
        [onDragStart, rowMarkerOffset]
741✔
2670
    );
741✔
2671

741✔
2672
    const onDragEnd = React.useCallback(() => {
741✔
UNCOV
2673
        isActivelyDragging.current = false;
×
2674
    }, []);
741✔
2675

741✔
2676
    const rowGroupingSelectionBehavior = rowGrouping?.selectionBehavior;
741!
2677

741✔
2678
    const getSelectionRowLimits = React.useCallback(
741✔
2679
        (selectedRow: number): readonly [number, number] | undefined => {
741✔
2680
            if (rowGroupingSelectionBehavior !== "block-spanning") return undefined;
16!
UNCOV
2681

×
2682
            const { isGroupHeader, path, groupRows } = mapper(selectedRow);
×
UNCOV
2683

×
UNCOV
2684
            if (isGroupHeader) {
×
UNCOV
2685
                return [selectedRow, selectedRow];
×
UNCOV
2686
            }
×
UNCOV
2687

×
UNCOV
2688
            const groupRowIndex = path[path.length - 1];
×
UNCOV
2689
            const lowerBounds = selectedRow - groupRowIndex;
×
2690
            const upperBounds = selectedRow + groupRows - groupRowIndex - 1;
×
2691

×
2692
            return [lowerBounds, upperBounds];
×
2693
        },
16✔
2694
        [mapper, rowGroupingSelectionBehavior]
741✔
2695
    );
741✔
2696

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

12✔
2731
                if (row < 0) {
12✔
2732
                    row = visibleRegionRef.current.y;
1✔
2733
                }
1✔
2734

12✔
2735
                if (mouseState.fillHandle === true && mouseState.previousSelection?.current !== undefined) {
12✔
2736
                    const prevRange = mouseState.previousSelection.current.range;
6✔
2737
                    row = Math.min(row, showTrailingBlankRow ? rows - 1 : rows);
6!
2738
                    const rect = getClosestRect(prevRange, col, row, allowedFillDirections);
6✔
2739
                    setFillHighlightRegion(rect);
6✔
2740
                } else {
6✔
2741
                    const startedFromLastStickyRow = showTrailingBlankRow && selectedRow === rows;
6✔
2742
                    if (startedFromLastStickyRow) return;
6!
2743

6✔
2744
                    const landedOnLastStickyRow = showTrailingBlankRow && row === rows;
6✔
2745
                    if (landedOnLastStickyRow) {
6!
UNCOV
2746
                        if (args.kind === outOfBoundsKind) row--;
×
UNCOV
2747
                        else return;
×
UNCOV
2748
                    }
×
2749

6✔
2750
                    col = Math.max(col, rowMarkerOffset);
6✔
2751
                    const clampLimits = getSelectionRowLimits(selectedRow);
6✔
2752
                    row = clampLimits === undefined ? row : clamp(row, clampLimits[0], clampLimits[1]);
6!
2753

6✔
2754
                    // FIXME: Restrict row based on rowGrouping.selectionBehavior here
6✔
2755

6✔
2756
                    const deltaX = col - selectedCol;
6✔
2757
                    const deltaY = row - selectedRow;
6✔
2758

6✔
2759
                    const newRange: Rectangle = {
6✔
2760
                        x: deltaX >= 0 ? selectedCol : col,
6!
2761
                        y: deltaY >= 0 ? selectedRow : row,
6✔
2762
                        width: Math.abs(deltaX) + 1,
6✔
2763
                        height: Math.abs(deltaY) + 1,
6✔
2764
                    };
6✔
2765

6✔
2766
                    setCurrent(
6✔
2767
                        {
6✔
2768
                            ...gridSelection.current,
6✔
2769
                            range: newRange,
6✔
2770
                        },
6✔
2771
                        true,
6✔
2772
                        false,
6✔
2773
                        "drag"
6✔
2774
                    );
6✔
2775
                }
6✔
2776
            }
12✔
2777

28✔
2778
            onItemHovered?.({ ...args, location: [args.location[0] - rowMarkerOffset, args.location[1]] as any });
29✔
2779
        },
29✔
2780
        [
741✔
2781
            mouseState,
741✔
2782
            rowMarkerOffset,
741✔
2783
            rowSelect,
741✔
2784
            gridSelection,
741✔
2785
            rangeSelect,
741✔
2786
            onItemHovered,
741✔
2787
            setSelectedRows,
741✔
2788
            showTrailingBlankRow,
741✔
2789
            rows,
741✔
2790
            allowedFillDirections,
741✔
2791
            getSelectionRowLimits,
741✔
2792
            setCurrent,
741✔
2793
        ]
741✔
2794
    );
741✔
2795

741✔
2796
    const adjustSelectionOnScroll = React.useCallback(() => {
741✔
UNCOV
2797
        const args = hoveredRef.current;
×
UNCOV
2798
        if (args === undefined) return;
×
UNCOV
2799
        const [xDir, yDir] = args.scrollEdge;
×
UNCOV
2800
        let [col, row] = args.location;
×
UNCOV
2801
        const visible = visibleRegionRef.current;
×
UNCOV
2802
        if (xDir === -1) {
×
UNCOV
2803
            col = visible.extras?.freezeRegion?.x ?? visible.x;
×
UNCOV
2804
        } else if (xDir === 1) {
×
UNCOV
2805
            col = visible.x + visible.width;
×
2806
        }
×
2807
        if (yDir === -1) {
×
2808
            row = Math.max(0, visible.y);
×
2809
        } else if (yDir === 1) {
×
2810
            row = Math.min(rows - 1, visible.y + visible.height);
×
2811
        }
×
2812
        col = clamp(col, 0, mangledCols.length - 1);
×
2813
        row = clamp(row, 0, rows - 1);
×
2814
        onItemHoveredImpl({
×
2815
            ...args,
×
2816
            location: [col, row] as any,
×
2817
        });
×
2818
    }, [mangledCols.length, onItemHoveredImpl, rows]);
741✔
2819

741✔
2820
    useAutoscroll(scrollDir, scrollRef, adjustSelectionOnScroll);
741✔
2821

741✔
2822
    // 1 === move one
741✔
2823
    // 2 === move to end
741✔
2824
    const adjustSelection = React.useCallback(
741✔
2825
        (direction: [0 | 1 | -1 | 2 | -2, 0 | 1 | -1 | 2 | -2]) => {
741✔
2826
            if (gridSelection.current === undefined) return;
10!
2827

10✔
2828
            const [x, y] = direction;
10✔
2829
            const [col, row] = gridSelection.current.cell;
10✔
2830
            const old = gridSelection.current.range;
10✔
2831
            let left = old.x;
10✔
2832
            let right = old.x + old.width;
10✔
2833
            let top = old.y;
10✔
2834
            let bottom = old.y + old.height;
10✔
2835

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

10✔
2839
            // take care of vertical first in case new spans come in
10✔
2840
            if (y !== 0) {
10✔
2841
                switch (y) {
4✔
2842
                    case 2: {
4✔
2843
                        // go to end
2✔
2844
                        bottom = maxRow;
2✔
2845
                        top = row;
2✔
2846
                        scrollTo(0, bottom, "vertical");
2✔
2847

2✔
2848
                        break;
2✔
2849
                    }
2✔
2850
                    case -2: {
4✔
2851
                        // go to start
1✔
2852
                        top = minRow;
1✔
2853
                        bottom = row + 1;
1✔
2854
                        scrollTo(0, top, "vertical");
1✔
2855

1✔
2856
                        break;
1✔
2857
                    }
1✔
2858
                    case 1: {
4✔
2859
                        // motion down
1✔
2860
                        if (top < row) {
1!
UNCOV
2861
                            top++;
×
UNCOV
2862
                            scrollTo(0, top, "vertical");
×
2863
                        } else {
1✔
2864
                            bottom = Math.min(maxRow, bottom + 1);
1✔
2865
                            scrollTo(0, bottom, "vertical");
1✔
2866
                        }
1✔
2867

1✔
2868
                        break;
1✔
2869
                    }
1✔
2870
                    case -1: {
4!
2871
                        // motion up
×
UNCOV
2872
                        if (bottom > row + 1) {
×
UNCOV
2873
                            bottom--;
×
UNCOV
2874
                            scrollTo(0, bottom, "vertical");
×
UNCOV
2875
                        } else {
×
UNCOV
2876
                            top = Math.max(minRow, top - 1);
×
UNCOV
2877
                            scrollTo(0, top, "vertical");
×
UNCOV
2878
                        }
×
UNCOV
2879

×
2880
                        break;
×
2881
                    }
×
2882
                    default: {
4!
2883
                        assertNever(y);
×
2884
                    }
×
2885
                }
4✔
2886
            }
4✔
2887

10✔
2888
            if (x !== 0) {
10✔
2889
                if (x === 2) {
8✔
2890
                    right = mangledCols.length;
2✔
2891
                    left = col;
2✔
2892
                    scrollTo(right - 1 - rowMarkerOffset, 0, "horizontal");
2✔
2893
                } else if (x === -2) {
8✔
2894
                    left = rowMarkerOffset;
1✔
2895
                    right = col + 1;
1✔
2896
                    scrollTo(left - rowMarkerOffset, 0, "horizontal");
1✔
2897
                } else {
6✔
2898
                    let disallowed: number[] = [];
5✔
2899
                    if (getCellsForSelection !== undefined) {
5✔
2900
                        const cells = getCellsForSelection(
5✔
2901
                            {
5✔
2902
                                x: left,
5✔
2903
                                y: top,
5✔
2904
                                width: right - left - rowMarkerOffset,
5✔
2905
                                height: bottom - top,
5✔
2906
                            },
5✔
2907
                            abortControllerRef.current.signal
5✔
2908
                        );
5✔
2909

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

10✔
2964
            setCurrent(
10✔
2965
                {
10✔
2966
                    cell: gridSelection.current.cell,
10✔
2967
                    range: {
10✔
2968
                        x: left,
10✔
2969
                        y: top,
10✔
2970
                        width: right - left,
10✔
2971
                        height: bottom - top,
10✔
2972
                    },
10✔
2973
                },
10✔
2974
                true,
10✔
2975
                false,
10✔
2976
                "keyboard-select"
10✔
2977
            );
10✔
2978
        },
10✔
2979
        [
741✔
2980
            getCellsForSelection,
741✔
2981
            getSelectionRowLimits,
741✔
2982
            gridSelection,
741✔
2983
            mangledCols.length,
741✔
2984
            rowMarkerOffset,
741✔
2985
            rows,
741✔
2986
            scrollTo,
741✔
2987
            setCurrent,
741✔
2988
        ]
741✔
2989
    );
741✔
2990

741✔
2991
    const scrollToActiveCellRef = React.useRef(scrollToActiveCell);
741✔
2992
    scrollToActiveCellRef.current = scrollToActiveCell;
741✔
2993

741✔
2994
    const updateSelectedCell = React.useCallback(
741✔
2995
        (col: number, row: number, fromEditingTrailingRow: boolean, freeMove: boolean): boolean => {
741✔
2996
            const rowMax = mangledRows - (fromEditingTrailingRow ? 0 : 1);
68!
2997
            col = clamp(col, rowMarkerOffset, columns.length - 1 + rowMarkerOffset);
68✔
2998
            row = clamp(row, 0, rowMax);
68✔
2999

68✔
3000
            const curCol = currentCell?.[0];
68✔
3001
            const curRow = currentCell?.[1];
68✔
3002

68✔
3003
            if (col === curCol && row === curRow) return false;
68✔
3004
            if (freeMove && gridSelection.current !== undefined) {
68✔
3005
                const newStack = [...gridSelection.current.rangeStack];
1✔
3006
                if (gridSelection.current.range.width > 1 || gridSelection.current.range.height > 1) {
1!
3007
                    newStack.push(gridSelection.current.range);
1✔
3008
                }
1✔
3009
                setGridSelection(
1✔
3010
                    {
1✔
3011
                        ...gridSelection,
1✔
3012
                        current: {
1✔
3013
                            cell: [col, row],
1✔
3014
                            range: { x: col, y: row, width: 1, height: 1 },
1✔
3015
                            rangeStack: newStack,
1✔
3016
                        },
1✔
3017
                    },
1✔
3018
                    true
1✔
3019
                );
1✔
3020
            } else {
68✔
3021
                setCurrent(
29✔
3022
                    {
29✔
3023
                        cell: [col, row],
29✔
3024
                        range: { x: col, y: row, width: 1, height: 1 },
29✔
3025
                    },
29✔
3026
                    true,
29✔
3027
                    false,
29✔
3028
                    "keyboard-nav"
29✔
3029
                );
29✔
3030
            }
29✔
3031

30✔
3032
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
68✔
3033
                lastSent.current = undefined;
2✔
3034
            }
2✔
3035

30✔
3036
            if (scrollToActiveCellRef.current) {
30✔
3037
                scrollTo(col - rowMarkerOffset, row);
30✔
3038
            }
30✔
3039

30✔
3040
            return true;
30✔
3041
        },
68✔
3042
        [
741✔
3043
            mangledRows,
741✔
3044
            rowMarkerOffset,
741✔
3045
            columns.length,
741✔
3046
            currentCell,
741✔
3047
            gridSelection,
741✔
3048
            scrollTo,
741✔
3049
            setGridSelection,
741✔
3050
            setCurrent,
741✔
3051
        ]
741✔
3052
    );
741✔
3053

741✔
3054
    const onFinishEditing = React.useCallback(
741✔
3055
        (newValue: GridCell | undefined, movement: readonly [-1 | 0 | 1, -1 | 0 | 1]) => {
741✔
3056
            if (overlay?.cell !== undefined && newValue !== undefined && isEditableGridCell(newValue)) {
12✔
3057
                mangledOnCellsEdited([{ location: overlay.cell, value: newValue }]);
4✔
3058
                window.requestAnimationFrame(() => {
4✔
3059
                    gridRef.current?.damage([
4✔
3060
                        {
4✔
3061
                            cell: overlay.cell,
4✔
3062
                        },
4✔
3063
                    ]);
4✔
3064
                });
4✔
3065
            }
4✔
3066
            focus(true);
12✔
3067
            setOverlay(undefined);
12✔
3068

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

741✔
3114
    const overlayID = React.useMemo(() => {
741✔
3115
        return `gdg-overlay-${idCounter++}`;
151✔
3116
    }, []);
741✔
3117

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

741✔
3156
    const overlayOpen = overlay !== undefined;
741✔
3157

741✔
3158
    const handleFixedKeybindings = React.useCallback(
741✔
3159
        (event: GridKeyEventArgs): boolean => {
741✔
3160
            const cancel = () => {
74✔
3161
                event.stopPropagation();
50✔
3162
                event.preventDefault();
50✔
3163
            };
50✔
3164

74✔
3165
            const details = {
74✔
3166
                didMatch: false,
74✔
3167
            };
74✔
3168

74✔
3169
            const { bounds } = event;
74✔
3170
            const selectedColumns = gridSelection.columns;
74✔
3171
            const selectedRows = gridSelection.rows;
74✔
3172

74✔
3173
            const keys = keybindings;
74✔
3174

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

8✔
3204
                    // delete order:
8✔
3205
                    // 1) primary range
8✔
3206
                    // 2) secondary ranges
8✔
3207
                    // 3) columns
8✔
3208
                    // 4) rows
8✔
3209

8✔
3210
                    if (toDelete.current !== undefined) {
8✔
3211
                        deleteRange(toDelete.current.range);
5✔
3212
                        for (const r of toDelete.current.rangeStack) {
5!
UNCOV
3213
                            deleteRange(r);
×
UNCOV
3214
                        }
×
3215
                    }
5✔
3216

8✔
3217
                    for (const r of toDelete.rows) {
8✔
3218
                        deleteRange({
1✔
3219
                            x: rowMarkerOffset,
1✔
3220
                            y: r,
1✔
3221
                            width: columnsIn.length,
1✔
3222
                            height: 1,
1✔
3223
                        });
1✔
3224
                    }
1✔
3225

8✔
3226
                    for (const col of toDelete.columns) {
8✔
3227
                        deleteRange({
1✔
3228
                            x: col,
1✔
3229
                            y: 0,
1✔
3230
                            width: 1,
1✔
3231
                            height: rows,
1✔
3232
                        });
1✔
3233
                    }
1✔
3234
                }
8✔
3235
            }
8✔
3236

74✔
3237
            if (details.didMatch) {
74✔
3238
                cancel();
11✔
3239
                return true;
11✔
3240
            }
11✔
3241

63✔
3242
            if (gridSelection.current === undefined) return false;
74✔
3243
            let [col, row] = gridSelection.current.cell;
60✔
3244
            const [, startRow] = gridSelection.current.cell;
60✔
3245
            let freeMove = false;
60✔
3246
            let cancelOnlyOnMove = false;
60✔
3247

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

4✔
3356
                if (isHotkey(keys.acceptOverlayDown, event, details)) {
4✔
3357
                    setOverlay(undefined);
2✔
3358
                    row++;
2✔
3359
                }
2✔
3360

4✔
3361
                if (isHotkey(keys.acceptOverlayUp, event, details)) {
4!
UNCOV
3362
                    setOverlay(undefined);
×
UNCOV
3363
                    row--;
×
UNCOV
3364
                }
×
3365

4✔
3366
                if (isHotkey(keys.acceptOverlayLeft, event, details)) {
4!
UNCOV
3367
                    setOverlay(undefined);
×
UNCOV
3368
                    col--;
×
UNCOV
3369
                }
×
3370

4✔
3371
                if (isHotkey(keys.acceptOverlayRight, event, details)) {
4!
3372
                    setOverlay(undefined);
×
3373
                    col++;
×
UNCOV
3374
                }
×
3375
            }
4✔
3376
            // #endregion
60✔
3377

60✔
3378
            const mustRestrictRow = rowGroupingNavBehavior !== undefined && rowGroupingNavBehavior !== "normal";
74!
3379

74✔
3380
            if (mustRestrictRow && row !== startRow) {
74!
3381
                const skipUp =
×
3382
                    rowGroupingNavBehavior === "skip-up" ||
×
3383
                    rowGroupingNavBehavior === "skip" ||
×
UNCOV
3384
                    rowGroupingNavBehavior === "block";
×
UNCOV
3385
                const skipDown =
×
UNCOV
3386
                    rowGroupingNavBehavior === "skip-down" ||
×
UNCOV
3387
                    rowGroupingNavBehavior === "skip" ||
×
UNCOV
3388
                    rowGroupingNavBehavior === "block";
×
UNCOV
3389
                const didMoveUp = row < startRow;
×
3390
                if (didMoveUp && skipUp) {
×
3391
                    while (row >= 0 && mapper(row).isGroupHeader) {
×
3392
                        row--;
×
3393
                    }
×
3394

×
3395
                    if (row < 0) {
×
3396
                        row = startRow;
×
3397
                    }
×
3398
                } else if (!didMoveUp && skipDown) {
×
3399
                    while (row < rows && mapper(row).isGroupHeader) {
×
3400
                        row++;
×
3401
                    }
×
3402

×
3403
                    if (row >= rows) {
×
3404
                        row = startRow;
×
3405
                    }
×
3406
                }
×
3407
            }
✔
3408

60✔
3409
            const moved = updateSelectedCell(col, row, false, freeMove);
60✔
3410

60✔
3411
            const didMatch = details.didMatch;
60✔
3412

60✔
3413
            if (didMatch && (moved || !cancelOnlyOnMove || trapFocus)) {
74✔
3414
                cancel();
39✔
3415
            }
39✔
3416

60✔
3417
            return didMatch;
60✔
3418
        },
74✔
3419
        [
741✔
3420
            rowGroupingNavBehavior,
741✔
3421
            overlayOpen,
741✔
3422
            gridSelection,
741✔
3423
            keybindings,
741✔
3424
            columnSelect,
741✔
3425
            rowSelect,
741✔
3426
            rangeSelect,
741✔
3427
            rowMarkerOffset,
741✔
3428
            mapper,
741✔
3429
            rows,
741✔
3430
            updateSelectedCell,
741✔
3431
            setGridSelection,
741✔
3432
            onSelectionCleared,
741✔
3433
            columnsIn.length,
741✔
3434
            onDelete,
741✔
3435
            trapFocus,
741✔
3436
            deleteRange,
741✔
3437
            setSelectedColumns,
741✔
3438
            setSelectedRows,
741✔
3439
            showTrailingBlankRow,
741✔
3440
            getCustomNewRowTargetColumn,
741✔
3441
            appendRow,
741✔
3442
            onCellActivated,
741✔
3443
            reselect,
741✔
3444
            fillDown,
741✔
3445
            fillRight,
741✔
3446
            adjustSelection,
741✔
3447
        ]
741✔
3448
    );
741✔
3449

741✔
3450
    const onKeyDown = React.useCallback(
741✔
3451
        (event: GridKeyEventArgs) => {
741✔
3452
            let cancelled = false;
74✔
3453
            if (onKeyDownIn !== undefined) {
74✔
3454
                onKeyDownIn({
1✔
3455
                    ...event,
1✔
3456
                    ...(event.location && {
1✔
3457
                        location: [event.location[0] - rowMarkerOffset, event.location[1]] as any,
1✔
3458
                    }),
1✔
3459
                    cancel: () => {
1✔
UNCOV
3460
                        cancelled = true;
×
UNCOV
3461
                    },
×
3462
                });
1✔
3463
            }
1✔
3464

74✔
3465
            if (cancelled) return;
74!
3466

74✔
3467
            if (handleFixedKeybindings(event)) return;
74✔
3468

16✔
3469
            if (gridSelection.current === undefined) return;
16✔
3470
            const [col, row] = gridSelection.current.cell;
13✔
3471
            const vr = visibleRegionRef.current;
13✔
3472

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

741✔
3509
    const onContextMenu = React.useCallback(
741✔
3510
        (args: GridMouseEventArgs, preventDefault: () => void) => {
741✔
3511
            const adjustedCol = args.location[0] - rowMarkerOffset;
7✔
3512
            if (args.kind === "header") {
7!
UNCOV
3513
                onHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
UNCOV
3514
            }
×
3515

7✔
3516
            if (args.kind === groupHeaderKind) {
7!
UNCOV
3517
                if (adjustedCol < 0) {
×
UNCOV
3518
                    return;
×
UNCOV
3519
                }
×
UNCOV
3520
                onGroupHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
UNCOV
3521
            }
×
3522

7✔
3523
            if (args.kind === "cell") {
7✔
3524
                const [col, row] = args.location;
7✔
3525
                onCellContextMenu?.([adjustedCol, row], {
7✔
3526
                    ...args,
7✔
3527
                    preventDefault,
7✔
3528
                });
7✔
3529

7✔
3530
                if (!gridSelectionHasItem(gridSelection, args.location)) {
7✔
3531
                    updateSelectedCell(col, row, false, false);
3✔
3532
                }
3✔
3533
            }
7✔
3534
        },
7✔
3535
        [
741✔
3536
            gridSelection,
741✔
3537
            onCellContextMenu,
741✔
3538
            onGroupHeaderContextMenu,
741✔
3539
            onHeaderContextMenu,
741✔
3540
            rowMarkerOffset,
741✔
3541
            updateSelectedCell,
741✔
3542
        ]
741✔
3543
    );
741✔
3544

741✔
3545
    const onPasteInternal = React.useCallback(
741✔
3546
        async (e?: ClipboardEvent) => {
741✔
3547
            if (!keybindings.paste) return;
6!
3548
            function pasteToCell(
6✔
3549
                inner: InnerGridCell,
51✔
3550
                target: Item,
51✔
3551
                rawValue: string | boolean | string[] | number | boolean | BooleanEmpty | BooleanIndeterminate,
51✔
3552
                formatted?: string | string[]
51✔
3553
            ): EditListItem | undefined {
51✔
3554
                const stringifiedRawValue =
51✔
3555
                    typeof rawValue === "object" ? rawValue?.join("\n") ?? "" : rawValue?.toString() ?? "";
51!
3556

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

6✔
3602
            const selectedColumns = gridSelection.columns;
6✔
3603
            const selectedRows = gridSelection.rows;
6✔
3604
            const focused =
6✔
3605
                scrollRef.current?.contains(document.activeElement) === true ||
6✔
3606
                canvasRef.current?.contains(document.activeElement) === true;
6✔
3607

6✔
3608
            let target: Item | undefined;
6✔
3609

6✔
3610
            if (gridSelection.current !== undefined) {
6✔
3611
                target = [gridSelection.current.range.x, gridSelection.current.range.y];
5✔
3612
            } else if (selectedColumns.length === 1) {
6!
UNCOV
3613
                target = [selectedColumns.first() ?? 0, 0];
×
3614
            } else if (selectedRows.length === 1) {
1!
UNCOV
3615
                target = [rowMarkerOffset, selectedRows.first() ?? 0];
×
UNCOV
3616
            }
×
3617

6✔
3618
            if (focused && target !== undefined) {
6✔
3619
                let data: CopyBuffer | undefined;
5✔
3620
                let text: string | undefined;
5✔
3621

5✔
3622
                const textPlain = "text/plain";
5✔
3623
                const textHtml = "text/html";
5✔
3624

5✔
3625
                if (navigator.clipboard.read !== undefined) {
5!
UNCOV
3626
                    const clipboardContent = await navigator.clipboard.read();
×
UNCOV
3627

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

5✔
3657
                const [targetCol, targetRow] = target;
5✔
3658

5✔
3659
                const editList: EditListItem[] = [];
5✔
3660
                do {
5✔
3661
                    if (onPaste === undefined) {
5✔
3662
                        const cellData = getMangledCellContent(target);
2✔
3663
                        const rawValue = text ?? data?.map(r => r.map(cb => cb.rawValue).join("\t")).join("\t") ?? "";
2!
3664
                        const newVal = pasteToCell(cellData, target, rawValue, undefined);
2✔
3665
                        if (newVal !== undefined) {
2✔
3666
                            editList.push(newVal);
1✔
3667
                        }
1✔
3668
                        break;
2✔
3669
                    }
2✔
3670

3✔
3671
                    if (data === undefined) {
3✔
3672
                        if (text === undefined) return;
3!
3673
                        data = unquote(text);
3✔
3674
                    }
3✔
3675

3✔
3676
                    if (
3✔
3677
                        onPaste === false ||
3✔
3678
                        (typeof onPaste === "function" &&
3✔
3679
                            onPaste?.(
2✔
3680
                                [target[0] - rowMarkerOffset, target[1]],
2✔
3681
                                data.map(r => r.map(cb => cb.rawValue?.toString() ?? ""))
2!
3682
                            ) !== true)
2✔
3683
                    ) {
5!
UNCOV
3684
                        return;
×
UNCOV
3685
                    }
✔
3686

3✔
3687
                    for (const [row, dataRow] of data.entries()) {
5✔
3688
                        if (row + targetRow >= rows) break;
21!
3689
                        for (const [col, dataItem] of dataRow.entries()) {
21✔
3690
                            const index = [col + targetCol, row + targetRow] as const;
63✔
3691
                            const [writeCol, writeRow] = index;
63✔
3692
                            if (writeCol >= mangledCols.length) continue;
63✔
3693
                            if (writeRow >= mangledRows) continue;
49!
3694
                            const cellData = getMangledCellContent(index);
49✔
3695
                            const newVal = pasteToCell(cellData, index, dataItem.rawValue, dataItem.formatted);
49✔
3696
                            if (newVal !== undefined) {
63✔
3697
                                editList.push(newVal);
35✔
3698
                            }
35✔
3699
                        }
63✔
3700
                    }
21✔
3701
                    // eslint-disable-next-line no-constant-condition
3✔
3702
                } while (false);
5✔
3703

5✔
3704
                mangledOnCellsEdited(editList);
5✔
3705

5✔
3706
                gridRef.current?.damage(
5✔
3707
                    editList.map(c => ({
5✔
3708
                        cell: c.location,
36✔
3709
                    }))
5✔
3710
                );
5✔
3711
            }
5✔
3712
        },
6✔
3713
        [
741✔
3714
            coercePasteValue,
741✔
3715
            getCellRenderer,
741✔
3716
            getMangledCellContent,
741✔
3717
            gridSelection,
741✔
3718
            keybindings.paste,
741✔
3719
            scrollRef,
741✔
3720
            mangledCols.length,
741✔
3721
            mangledOnCellsEdited,
741✔
3722
            mangledRows,
741✔
3723
            onPaste,
741✔
3724
            rowMarkerOffset,
741✔
3725
            rows,
741✔
3726
        ]
741✔
3727
    );
741✔
3728

741✔
3729
    useEventListener("paste", onPasteInternal, safeWindow, false, true);
741✔
3730

741✔
3731
    // While this function is async, we deeply prefer not to await if we don't have to. This will lead to unpacking
741✔
3732
    // promises in rather awkward ways when possible to avoid awaiting. We have to use fallback copy mechanisms when
741✔
3733
    // an await has happened.
741✔
3734
    const onCopy = React.useCallback(
741✔
3735
        async (e?: ClipboardEvent, ignoreFocus?: boolean) => {
741✔
3736
            if (!keybindings.copy) return;
6!
3737
            const focused =
6✔
3738
                ignoreFocus === true ||
6✔
3739
                scrollRef.current?.contains(document.activeElement) === true ||
5✔
3740
                canvasRef.current?.contains(document.activeElement) === true;
5✔
3741

6✔
3742
            const selectedColumns = gridSelection.columns;
6✔
3743
            const selectedRows = gridSelection.rows;
6✔
3744

6✔
3745
            const copyToClipboardWithHeaders = (
6✔
3746
                cells: readonly (readonly GridCell[])[],
5✔
3747
                columnIndexes: readonly number[]
5✔
3748
            ) => {
5✔
3749
                if (!copyHeaders) {
5✔
3750
                    copyToClipboard(cells, columnIndexes, e);
5✔
3751
                } else {
5!
UNCOV
3752
                    const headers = columnIndexes.map(index => ({
×
UNCOV
3753
                        kind: GridCellKind.Text,
×
UNCOV
3754
                        data: columnsIn[index].title,
×
UNCOV
3755
                        displayData: columnsIn[index].title,
×
UNCOV
3756
                        allowOverlay: false,
×
UNCOV
3757
                    })) as GridCell[];
×
UNCOV
3758
                    copyToClipboard([headers, ...cells], columnIndexes, e);
×
UNCOV
3759
                }
×
3760
            };
5✔
3761

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

741✔
3839
    useEventListener("copy", onCopy, safeWindow, false, false);
741✔
3840

741✔
3841
    const onCut = React.useCallback(
741✔
3842
        async (e?: ClipboardEvent) => {
741✔
3843
            if (!keybindings.cut) return;
1!
3844
            const focused =
1✔
3845
                scrollRef.current?.contains(document.activeElement) === true ||
1✔
3846
                canvasRef.current?.contains(document.activeElement) === true;
1✔
3847

1✔
3848
            if (!focused) return;
1!
3849
            await onCopy(e);
1✔
3850
            if (gridSelection.current !== undefined) {
1✔
3851
                let effectiveSelection: GridSelection = {
1✔
3852
                    current: {
1✔
3853
                        cell: gridSelection.current.cell,
1✔
3854
                        range: gridSelection.current.range,
1✔
3855
                        rangeStack: [],
1✔
3856
                    },
1✔
3857
                    rows: CompactSelection.empty(),
1✔
3858
                    columns: CompactSelection.empty(),
1✔
3859
                };
1✔
3860
                const onDeleteResult = onDelete?.(effectiveSelection);
1✔
3861
                if (onDeleteResult === false) return;
1!
3862
                effectiveSelection = onDeleteResult === true ? effectiveSelection : onDeleteResult;
1!
3863
                if (effectiveSelection.current === undefined) return;
1!
3864
                deleteRange(effectiveSelection.current.range);
1✔
3865
            }
1✔
3866
        },
1✔
3867
        [deleteRange, gridSelection, keybindings.cut, onCopy, scrollRef, onDelete]
741✔
3868
    );
741✔
3869

741✔
3870
    useEventListener("cut", onCut, safeWindow, false, false);
741✔
3871

741✔
3872
    const onSearchResultsChanged = React.useCallback(
741✔
3873
        (results: readonly Item[], navIndex: number) => {
741✔
3874
            if (onSearchResultsChangedIn !== undefined) {
7!
UNCOV
3875
                if (rowMarkerOffset !== 0) {
×
UNCOV
3876
                    results = results.map(item => [item[0] - rowMarkerOffset, item[1]]);
×
UNCOV
3877
                }
×
UNCOV
3878
                onSearchResultsChangedIn(results, navIndex);
×
UNCOV
3879
                return;
×
UNCOV
3880
            }
×
3881
            if (results.length === 0 || navIndex === -1) return;
7✔
3882

2✔
3883
            const [col, row] = results[navIndex];
2✔
3884
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
7!
3885
                return;
×
3886
            }
✔
3887
            lastSent.current = [col, row];
2✔
3888
            updateSelectedCell(col, row, false, false);
2✔
3889
        },
7✔
3890
        [onSearchResultsChangedIn, rowMarkerOffset, updateSelectedCell]
741✔
3891
    );
741✔
3892

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

741✔
3913
    const selectionOutOfBounds =
741✔
3914
        gridSelection.current !== undefined &&
741✔
3915
        (gridSelection.current.cell[0] >= mangledCols.length || gridSelection.current.cell[1] >= mangledRows);
368✔
3916
    React.useLayoutEffect(() => {
741✔
3917
        if (selectionOutOfBounds) {
161✔
3918
            setGridSelection(emptyGridSelection, false);
1✔
3919
        }
1✔
3920
    }, [selectionOutOfBounds, setGridSelection]);
741✔
3921

741✔
3922
    const disabledRows = React.useMemo(() => {
741✔
3923
        if (showTrailingBlankRow === true && trailingRowOptions?.tint === true) {
154✔
3924
            return CompactSelection.fromSingleSelection(mangledRows - 1);
148✔
3925
        }
148✔
3926
        return CompactSelection.empty();
6✔
3927
    }, [mangledRows, showTrailingBlankRow, trailingRowOptions?.tint]);
741✔
3928

741✔
3929
    const mangledVerticalBorder = React.useCallback(
741✔
3930
        (col: number) => {
741✔
3931
            return typeof verticalBorder === "boolean"
7,956!
UNCOV
3932
                ? verticalBorder
×
3933
                : verticalBorder?.(col - rowMarkerOffset) ?? true;
7,956!
3934
        },
7,956✔
3935
        [rowMarkerOffset, verticalBorder]
741✔
3936
    );
741✔
3937

741✔
3938
    const renameGroupNode = React.useMemo(() => {
741✔
3939
        if (renameGroup === undefined || canvasRef.current === null) return null;
154✔
3940
        const { bounds, group } = renameGroup;
2✔
3941
        const canvasBounds = canvasRef.current.getBoundingClientRect();
2✔
3942
        return (
2✔
3943
            <GroupRename
2✔
3944
                bounds={bounds}
2✔
3945
                group={group}
2✔
3946
                canvasBounds={canvasBounds}
2✔
3947
                onClose={() => setRenameGroup(undefined)}
2✔
3948
                onFinish={newVal => {
2✔
3949
                    setRenameGroup(undefined);
1✔
3950
                    onGroupHeaderRenamed?.(group, newVal);
1✔
3951
                }}
1✔
3952
            />
2✔
3953
        );
154✔
3954
    }, [onGroupHeaderRenamed, renameGroup]);
741✔
3955

741✔
3956
    const mangledFreezeColumns = Math.min(mangledCols.length, freezeColumns + (hasRowMarkers ? 1 : 0));
741✔
3957

741✔
3958
    React.useImperativeHandle(
741✔
3959
        forwardedRef,
741✔
3960
        () => ({
741✔
3961
            appendRow: (col: number, openOverlay?: boolean) => appendRow(col + rowMarkerOffset, openOverlay),
30✔
3962
            appendColumn: (row: number, openOverlay?: boolean) => appendColumn(row, openOverlay),
30✔
3963
            updateCells: damageList => {
30✔
3964
                if (rowMarkerOffset !== 0) {
2✔
3965
                    damageList = damageList.map(x => ({ cell: [x.cell[0] + rowMarkerOffset, x.cell[1]] }));
1✔
3966
                }
1✔
3967
                return gridRef.current?.damage(damageList);
2✔
3968
            },
2✔
3969
            getBounds: (col, row) => {
30✔
3970
                if (canvasRef?.current === null || scrollRef?.current === null) {
2!
UNCOV
3971
                    return undefined;
×
UNCOV
3972
                }
×
3973

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

×
UNCOV
4061
                const args = gridRef.current.getMouseArgsForPosition(posX, posY, ev);
×
4062
                if (args === undefined) {
×
4063
                    return undefined;
×
4064
                }
×
4065

×
4066
                return {
×
4067
                    ...args,
×
4068
                    location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
×
4069
                };
×
4070
            },
×
4071
        }),
30✔
4072
        [
741✔
4073
            appendRow,
741✔
4074
            appendColumn,
741✔
4075
            normalSizeColumn,
741✔
4076
            scrollRef,
741✔
4077
            onCopy,
741✔
4078
            onKeyDown,
741✔
4079
            onPasteInternal,
741✔
4080
            rowMarkerOffset,
741✔
4081
            scrollTo,
741✔
4082
        ]
741✔
4083
    );
741✔
4084

741✔
4085
    const [selCol, selRow] = currentCell ?? [];
741✔
4086
    const onCellFocused = React.useCallback(
741✔
4087
        (cell: Item) => {
741✔
4088
            const [col, row] = cell;
30✔
4089

30✔
4090
            if (row === -1) {
30!
UNCOV
4091
                if (columnSelect !== "none") {
×
UNCOV
4092
                    setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, false);
×
UNCOV
4093
                    focus();
×
UNCOV
4094
                }
×
UNCOV
4095
                return;
×
UNCOV
4096
            }
×
4097

30✔
4098
            if (selCol === col && selRow === row) return;
30✔
4099
            setCurrent(
1✔
4100
                {
1✔
4101
                    cell,
1✔
4102
                    range: { x: col, y: row, width: 1, height: 1 },
1✔
4103
                },
1✔
4104
                true,
1✔
4105
                false,
1✔
4106
                "keyboard-nav"
1✔
4107
            );
1✔
4108
            scrollTo(col, row);
1✔
4109
        },
30✔
4110
        [columnSelect, focus, scrollTo, selCol, selRow, setCurrent, setSelectedColumns]
741✔
4111
    );
741✔
4112

741✔
4113
    const [isFocused, setIsFocused] = React.useState(false);
741✔
4114
    const setIsFocusedDebounced = React.useRef(
741✔
4115
        debounce((val: boolean) => {
741✔
4116
            setIsFocused(val);
58✔
4117
        }, 5)
741✔
4118
    );
741✔
4119

741✔
4120
    const onCanvasFocused = React.useCallback(() => {
741✔
4121
        setIsFocusedDebounced.current(true);
76✔
4122

76✔
4123
        // check for mouse state, don't do anything if the user is clicked to focus.
76✔
4124
        if (
76✔
4125
            gridSelection.current === undefined &&
76✔
4126
            gridSelection.columns.length === 0 &&
6✔
4127
            gridSelection.rows.length === 0 &&
5✔
4128
            mouseState === undefined
5✔
4129
        ) {
76✔
4130
            setCurrent(
5✔
4131
                {
5✔
4132
                    cell: [rowMarkerOffset, cellYOffset],
5✔
4133
                    range: {
5✔
4134
                        x: rowMarkerOffset,
5✔
4135
                        y: cellYOffset,
5✔
4136
                        width: 1,
5✔
4137
                        height: 1,
5✔
4138
                    },
5✔
4139
                },
5✔
4140
                true,
5✔
4141
                false,
5✔
4142
                "keyboard-select"
5✔
4143
            );
5✔
4144
        }
5✔
4145
    }, [cellYOffset, gridSelection, mouseState, rowMarkerOffset, setCurrent]);
741✔
4146

741✔
4147
    const onFocusOut = React.useCallback(() => {
741✔
4148
        setIsFocusedDebounced.current(false);
39✔
4149
    }, []);
741✔
4150

741✔
4151
    const [idealWidth, idealHeight] = React.useMemo(() => {
741✔
4152
        let h: number;
167✔
4153
        const scrollbarWidth = experimental?.scrollbarWidthOverride ?? getScrollBarWidth();
167✔
4154
        const rowsCountWithTrailingRow = rows + (showTrailingBlankRow ? 1 : 0);
167✔
4155
        if (typeof rowHeight === "number") {
167✔
4156
            h = totalHeaderHeight + rowsCountWithTrailingRow * rowHeight;
166✔
4157
        } else {
167✔
4158
            let avg = 0;
1✔
4159
            const toAverage = Math.min(rowsCountWithTrailingRow, 10);
1✔
4160
            for (let i = 0; i < toAverage; i++) {
1✔
4161
                avg += rowHeight(i);
10✔
4162
            }
10✔
4163
            avg = Math.floor(avg / toAverage);
1✔
4164

1✔
4165
            h = totalHeaderHeight + rowsCountWithTrailingRow * avg;
1✔
4166
        }
1✔
4167
        h += scrollbarWidth;
167✔
4168

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

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

741✔
4176
    const cssStyle = React.useMemo(() => {
741✔
4177
        return makeCSSStyle(mergedTheme);
151✔
4178
    }, [mergedTheme]);
741✔
4179

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

1✔
4303
/**
1✔
4304
 * The primary component of Glide Data Grid.
1✔
4305
 * @category DataEditor
1✔
4306
 * @param {DataEditorProps} props
1✔
4307
 */
1✔
4308
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