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

glideapps / glide-data-grid / 15764144347

19 Jun 2025 06:23PM UTC coverage: 91.252% (-0.07%) from 91.321%
15764144347

push

github

lukasmasuch
Merge remote-tracking branch 'upstream/main' into fix/grid-zoom-crash

2925 of 3616 branches covered (80.89%)

138 of 184 new or added lines in 16 files covered. (75.0%)

1 existing line in 1 file now uncovered.

17941 of 19661 relevant lines covered (91.25%)

3125.18 hits per line

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

90.47
/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
}
1✔
105

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

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

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

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

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

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

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

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

1✔
277
    /** The columns to display in the data grid.
1✔
278
     * @group Data
1✔
279
     */
1✔
280
    readonly columns: readonly GridColumn[];
1✔
281

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

1✔
308
    /**
1✔
309
     * The number of rows in the grid.
1✔
310
     * @group Data
1✔
311
     */
1✔
312
    readonly rows: number;
1✔
313

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

1✔
339
    /** Changes the theme of the row marker column
1✔
340
     * @group Style
1✔
341
     * @deprecated Use `rowMarkers` instead.
1✔
342
     */
1✔
343
    readonly rowMarkerTheme?: Partial<Theme>;
1✔
344

1✔
345
    /** Sets the width of the data grid.
1✔
346
     * @group Style
1✔
347
     */
1✔
348
    readonly width?: number | string;
1✔
349
    /** Sets the height of the data grid.
1✔
350
     * @group Style
1✔
351
     */
1✔
352
    readonly height?: number | string;
1✔
353
    /** Custom classname for data grid wrapper.
1✔
354
     * @group Style
1✔
355
     */
1✔
356
    readonly className?: string;
1✔
357

1✔
358
    /** If set to `default`, `gridSelection` will be coerced to always include full spans.
1✔
359
     * @group Selection
1✔
360
     * @defaultValue `default`
1✔
361
     */
1✔
362
    readonly spanRangeBehavior?: "default" | "allowPartial";
1✔
363

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

1✔
399
    /** Controls if range selection is allowed to span columns.
1✔
400
     * @group Selection
1✔
401
     * @defaultValue `true`
1✔
402
     */
1✔
403
    readonly rangeSelectionColumnSpanning?: boolean;
1✔
404

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

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

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

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

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

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

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

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

1✔
527
            /**
1✔
528
             * All visible freeze regions
1✔
529
             */
1✔
530
            freezeRegions?: readonly Rectangle[];
1✔
531
        }
1✔
532
    ) => void;
1✔
533

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

1✔
549
    /**
1✔
550
     * Add table headers to copied data.
1✔
551
     * @group Editing
1✔
552
     * @defaultValue `false`
1✔
553
     */
1✔
554
    readonly copyHeaders?: boolean;
1✔
555

1✔
556
    /**
1✔
557
     * Determins which keybindings are enabled.
1✔
558
     * @group Editing
1✔
559
     */
1✔
560
    readonly keybindings?: Partial<Keybinds>;
1✔
561

1✔
562
    /**
1✔
563
     * Determines if the data editor should immediately begin editing when the user types on a selected cell
1✔
564
     * @group Editing
1✔
565
     */
1✔
566
    readonly editOnType?: boolean;
1✔
567

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

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

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

1✔
606
    /**
1✔
607
     * Controls the grouping of rows to be drawn in the grid.
1✔
608
     */
1✔
609
    readonly rowGrouping?: RowGroupingOptions;
1✔
610

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

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

1✔
630
    readonly renderers?: readonly InternalCellRenderer<InnerGridCell>[];
1✔
631

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

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

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

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

1✔
657
    /**
1✔
658
     * Determines when a cell is considered activated and will emit the `onCellActivated` event. Generally an activated
1✔
659
     * cell will open to edit mode.
1✔
660
     */
1✔
661
    readonly cellActivationBehavior?: CellActiviationBehavior;
1✔
662

1✔
663
    /**
1✔
664
     * Controls if focus will trap inside the data grid when doing tab and caret navigation.
1✔
665
     */
1✔
666
    readonly trapFocus?: boolean;
1✔
667

1✔
668
    /**
1✔
669
     * Allows overriding the default amount of bloom (the size growth of the overlay editor)
1✔
670
     */
1✔
671
    readonly editorBloom?: readonly [number, number];
1✔
672

1✔
673
    /**
1✔
674
     * If set to true, the data grid will attempt to scroll to keep the selction in view
1✔
675
     */
1✔
676
    readonly scrollToActiveCell?: boolean;
1✔
677

1✔
678
    readonly drawFocusRing?: boolean | "no-editor";
1✔
679
}
1✔
680

1✔
681
type ScrollToFn = (
1✔
682
    col: number | { amount: number; unit: "cell" | "px" },
1✔
683
    row: number | { amount: number; unit: "cell" | "px" },
1✔
684
    dir?: "horizontal" | "vertical" | "both",
1✔
685
    paddingX?: number,
1✔
686
    paddingY?: number,
1✔
687
    options?: {
1✔
688
        hAlign?: "start" | "center" | "end";
1✔
689
        vAlign?: "start" | "center" | "end";
1✔
690
        behavior?: ScrollBehavior;
1✔
691
    }
1✔
692
) => void;
1✔
693

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

1✔
736
const loadingCell: GridCell = {
1✔
737
    kind: GridCellKind.Loading,
1✔
738
    allowOverlay: false,
1✔
739
};
1✔
740

1✔
741
const emptyGridSelection: GridSelection = {
1✔
742
    columns: CompactSelection.empty(),
1✔
743
    rows: CompactSelection.empty(),
1✔
744
    current: undefined,
1✔
745
};
1✔
746

1✔
747
const DataEditorImpl: React.ForwardRefRenderFunction<DataEditorRef, DataEditorProps> = (p, forwardedRef) => {
1✔
748
    const [gridSelectionInner, setGridSelectionInner] = React.useState<GridSelection>(emptyGridSelection);
728✔
749

728✔
750
    const [overlay, setOverlay] = React.useState<{
728✔
751
        target: Rectangle;
728✔
752
        content: GridCell;
728✔
753
        theme: FullTheme;
728✔
754
        initialValue: string | undefined;
728✔
755
        cell: Item;
728✔
756
        highlight: boolean;
728✔
757
        forceEditMode: boolean;
728✔
758
    }>();
728✔
759
    const searchInputRef = React.useRef<HTMLInputElement | null>(null);
728✔
760
    const canvasRef = React.useRef<HTMLCanvasElement | null>(null);
728✔
761
    const [mouseState, setMouseState] = React.useState<MouseState>();
728✔
762
    const lastSent = React.useRef<[number, number]>();
728✔
763

728✔
764
    const safeWindow = typeof window === "undefined" ? null : window;
728!
765

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

728✔
879
    const drawFocusRing = drawFocusRingIn === "no-editor" ? overlay === undefined : drawFocusRingIn;
728!
880

728✔
881
    const rowMarkersObj = typeof p.rowMarkers === "string" ? undefined : p.rowMarkers;
728✔
882

728✔
883
    const rowMarkers = rowMarkersObj?.kind ?? (p.rowMarkers as RowMarkerOptions["kind"]) ?? "none";
728!
884
    const rowMarkerWidthRaw = rowMarkersObj?.width ?? p.rowMarkerWidth;
728!
885
    const rowMarkerStartIndex = rowMarkersObj?.startIndex ?? p.rowMarkerStartIndex ?? 1;
728!
886
    const rowMarkerTheme = rowMarkersObj?.theme ?? p.rowMarkerTheme;
728!
887
    const headerRowMarkerTheme = rowMarkersObj?.headerTheme;
728!
888
    const headerRowMarkerAlwaysVisible = rowMarkersObj?.headerAlwaysVisible;
728!
889
    const headerRowMarkerDisabled = rowSelect !== "multi";
728✔
890
    const rowMarkerCheckboxStyle = rowMarkersObj?.checkboxStyle ?? "square";
728!
891

728✔
892
    const minColumnWidth = Math.max(minColumnWidthIn, 20);
728✔
893
    const maxColumnWidth = Math.max(maxColumnWidthIn, minColumnWidth);
728✔
894
    const maxColumnAutoWidth = Math.max(maxColumnAutoWidthIn ?? maxColumnWidth, minColumnWidth);
728✔
895

728✔
896
    const docStyle = React.useMemo(() => {
728✔
897
        if (typeof window === "undefined") return { fontSize: "16px" };
148!
898
        return window.getComputedStyle(document.documentElement);
148✔
899
    }, []);
728✔
900

728✔
901
    const {
728✔
902
        rows,
728✔
903
        rowNumberMapper,
728✔
904
        rowHeight: rowHeightPostGrouping,
728✔
905
        getRowThemeOverride,
728✔
906
    } = useRowGroupingInner(rowGrouping, rowsIn, rowHeightIn, getRowThemeOverrideIn);
728✔
907

728✔
908
    const remSize = React.useMemo(() => Number.parseFloat(docStyle.fontSize), [docStyle]);
728✔
909
    const { rowHeight, headerHeight, groupHeaderHeight, theme, overscrollX, overscrollY } = useRemAdjuster({
728✔
910
        groupHeaderHeight: groupHeaderHeightIn,
728✔
911
        headerHeight: headerHeightIn,
728✔
912
        overscrollX: overscrollXIn,
728✔
913
        overscrollY: overscrollYIn,
728✔
914
        remSize,
728✔
915
        rowHeight: rowHeightPostGrouping,
728✔
916
        scaleToRem,
728✔
917
        theme: themeIn,
728✔
918
    });
728✔
919

728✔
920
    const keybindings = useKeybindingsWithDefaults(keybindingsIn);
728✔
921

728✔
922
    const rowMarkerWidth = rowMarkerWidthRaw ?? (rowsIn > 10_000 ? 48 : rowsIn > 1000 ? 44 : rowsIn > 100 ? 36 : 32);
728!
923
    const hasRowMarkers = rowMarkers !== "none";
728✔
924
    const rowMarkerOffset = hasRowMarkers ? 1 : 0;
728✔
925
    const showTrailingBlankRow = onRowAppended !== undefined;
728✔
926
    const lastRowSticky = trailingRowOptions?.sticky === true;
728✔
927

728✔
928
    const [showSearchInner, setShowSearchInner] = React.useState(false);
728✔
929
    const showSearch = showSearchIn ?? showSearchInner;
728✔
930

728✔
931
    const onSearchClose = React.useCallback(() => {
728✔
932
        if (onSearchCloseIn !== undefined) {
2✔
933
            onSearchCloseIn();
2✔
934
        } else {
2!
935
            setShowSearchInner(false);
×
936
        }
×
937
    }, [onSearchCloseIn]);
728✔
938

728✔
939
    const gridSelectionOuterMangled: GridSelection | undefined = React.useMemo((): GridSelection | undefined => {
728✔
940
        return gridSelectionOuter === undefined ? undefined : shiftSelection(gridSelectionOuter, rowMarkerOffset);
286✔
941
    }, [gridSelectionOuter, rowMarkerOffset]);
728✔
942
    const gridSelection = gridSelectionOuterMangled ?? gridSelectionInner;
728✔
943

728✔
944
    const abortControllerRef = React.useRef() as React.MutableRefObject<AbortController>;
728✔
945
    if (abortControllerRef.current === undefined) abortControllerRef.current = new AbortController();
728✔
946

728✔
947
    React.useEffect(() => () => abortControllerRef?.current.abort(), []);
728✔
948

728✔
949
    const [getCellsForSelection, getCellsForSeletionDirect] = useCellsForSelection(
728✔
950
        getCellsForSelectionIn,
728✔
951
        getCellContent,
728✔
952
        rowMarkerOffset,
728✔
953
        abortControllerRef.current,
728✔
954
        rows
728✔
955
    );
728✔
956

728✔
957
    const validateCell = React.useCallback<NonNullable<typeof validateCellIn>>(
728✔
958
        (cell, newValue, prevValue) => {
728✔
959
            if (validateCellIn === undefined) return true;
17✔
960
            const item: Item = [cell[0] - rowMarkerOffset, cell[1]];
1✔
961
            return validateCellIn?.(item, newValue, prevValue);
1✔
962
        },
17✔
963
        [rowMarkerOffset, validateCellIn]
728✔
964
    );
728✔
965

728✔
966
    const expectedExternalGridSelection = React.useRef<GridSelection | undefined>(gridSelectionOuter);
728✔
967
    const setGridSelection = React.useCallback(
728✔
968
        (newVal: GridSelection, expand: boolean): void => {
728✔
969
            if (expand) {
182✔
970
                newVal = expandSelection(
141✔
971
                    newVal,
141✔
972
                    getCellsForSelection,
141✔
973
                    rowMarkerOffset,
141✔
974
                    spanRangeBehavior,
141✔
975
                    abortControllerRef.current
141✔
976
                );
141✔
977
            }
141✔
978
            if (onGridSelectionChange !== undefined) {
182✔
979
                expectedExternalGridSelection.current = shiftSelection(newVal, -rowMarkerOffset);
142✔
980
                onGridSelectionChange(expectedExternalGridSelection.current);
142✔
981
            } else {
182✔
982
                setGridSelectionInner(newVal);
40✔
983
            }
40✔
984
        },
182✔
985
        [onGridSelectionChange, getCellsForSelection, rowMarkerOffset, spanRangeBehavior]
728✔
986
    );
728✔
987

728✔
988
    const onColumnResize = whenDefined(
728✔
989
        onColumnResizeIn,
728✔
990
        React.useCallback<NonNullable<typeof onColumnResizeIn>>(
728✔
991
            (_, w, ind, wg) => {
728✔
992
                onColumnResizeIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
11✔
993
            },
11✔
994
            [onColumnResizeIn, rowMarkerOffset, columnsIn]
728✔
995
        )
728✔
996
    );
728✔
997

728✔
998
    const onColumnResizeEnd = whenDefined(
728✔
999
        onColumnResizeEndIn,
728✔
1000
        React.useCallback<NonNullable<typeof onColumnResizeEndIn>>(
728✔
1001
            (_, w, ind, wg) => {
728✔
1002
                onColumnResizeEndIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
2✔
1003
            },
2✔
1004
            [onColumnResizeEndIn, rowMarkerOffset, columnsIn]
728✔
1005
        )
728✔
1006
    );
728✔
1007

728✔
1008
    const onColumnResizeStart = whenDefined(
728✔
1009
        onColumnResizeStartIn,
728✔
1010
        React.useCallback<NonNullable<typeof onColumnResizeStartIn>>(
728✔
1011
            (_, w, ind, wg) => {
728✔
1012
                onColumnResizeStartIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
×
1013
            },
×
1014
            [onColumnResizeStartIn, rowMarkerOffset, columnsIn]
728✔
1015
        )
728✔
1016
    );
728✔
1017

728✔
1018
    const drawHeader = whenDefined(
728✔
1019
        drawHeaderIn,
728✔
1020
        React.useCallback<NonNullable<typeof drawHeaderIn>>(
728✔
1021
            (args, draw) => {
728✔
1022
                return drawHeaderIn?.({ ...args, columnIndex: args.columnIndex - rowMarkerOffset }, draw) ?? false;
×
1023
            },
×
1024
            [drawHeaderIn, rowMarkerOffset]
728✔
1025
        )
728✔
1026
    );
728✔
1027

728✔
1028
    const drawCell = whenDefined(
728✔
1029
        drawCellIn,
728✔
1030
        React.useCallback<NonNullable<typeof drawCellIn>>(
728✔
1031
            (args, draw) => {
728✔
1032
                return drawCellIn?.({ ...args, col: args.col - rowMarkerOffset }, draw) ?? false;
×
1033
            },
×
1034
            [drawCellIn, rowMarkerOffset]
728✔
1035
        )
728✔
1036
    );
728✔
1037

728✔
1038
    const onDelete = React.useCallback<NonNullable<DataEditorProps["onDelete"]>>(
728✔
1039
        sel => {
728✔
1040
            if (onDeleteIn !== undefined) {
9✔
1041
                const result = onDeleteIn(shiftSelection(sel, -rowMarkerOffset));
5✔
1042
                if (typeof result === "boolean") {
5!
1043
                    return result;
×
1044
                }
×
1045
                return shiftSelection(result, rowMarkerOffset);
5✔
1046
            }
5✔
1047
            return true;
4✔
1048
        },
9✔
1049
        [onDeleteIn, rowMarkerOffset]
728✔
1050
    );
728✔
1051

728✔
1052
    const [setCurrent, setSelectedRows, setSelectedColumns] = useSelectionBehavior(
728✔
1053
        gridSelection,
728✔
1054
        setGridSelection,
728✔
1055
        rangeSelectionBlending,
728✔
1056
        columnSelectionBlending,
728✔
1057
        rowSelectionBlending,
728✔
1058
        rangeSelect,
728✔
1059
        rangeSelectionColumnSpanning
728✔
1060
    );
728✔
1061

728✔
1062
    const mergedTheme = React.useMemo(() => {
728✔
1063
        return mergeAndRealizeTheme(getDataEditorTheme(), theme);
148✔
1064
    }, [theme]);
728✔
1065

728✔
1066
    const [clientSize, setClientSize] = React.useState<readonly [number, number, number]>([0, 0, 0]);
728✔
1067

728✔
1068
    const rendererMap = React.useMemo(() => {
728✔
1069
        if (renderers === undefined) return {};
148!
1070
        const result: Partial<Record<InnerGridCellKind | GridCellKind, InternalCellRenderer<InnerGridCell>>> = {};
148✔
1071
        for (const r of renderers) {
148✔
1072
            result[r.kind] = r;
1,925✔
1073
        }
1,925✔
1074
        return result;
148✔
1075
    }, [renderers]);
728✔
1076

728✔
1077
    const getCellRenderer: <T extends InnerGridCell>(cell: T) => CellRenderer<T> | undefined = React.useCallback(
728✔
1078
        <T extends InnerGridCell>(cell: T) => {
728✔
1079
            if (cell.kind !== GridCellKind.Custom) {
147,422✔
1080
                return rendererMap[cell.kind] as unknown as CellRenderer<T>;
143,692✔
1081
            }
143,692✔
1082
            return additionalRenderers?.find(x => x.isMatch(cell)) as CellRenderer<T>;
147,422✔
1083
        },
147,422✔
1084
        [additionalRenderers, rendererMap]
728✔
1085
    );
728✔
1086

728✔
1087
    // eslint-disable-next-line prefer-const
728✔
1088
    let { sizedColumns: columns, nonGrowWidth } = useColumnSizer(
728✔
1089
        columnsIn,
728✔
1090
        rows,
728✔
1091
        getCellsForSeletionDirect,
728✔
1092
        clientSize[0] - (rowMarkerOffset === 0 ? 0 : rowMarkerWidth) - clientSize[2],
728✔
1093
        minColumnWidth,
728✔
1094
        maxColumnAutoWidth,
728✔
1095
        mergedTheme,
728✔
1096
        getCellRenderer,
728✔
1097
        abortControllerRef.current
728✔
1098
    );
728✔
1099
    if (rowMarkers !== "none") nonGrowWidth += rowMarkerWidth;
728✔
1100

728✔
1101
    const enableGroups = React.useMemo(() => {
728✔
1102
        return columns.some(c => c.group !== undefined);
148✔
1103
    }, [columns]);
728✔
1104

728✔
1105
    const totalHeaderHeight = enableGroups ? headerHeight + groupHeaderHeight : headerHeight;
728✔
1106

728✔
1107
    const numSelectedRows = gridSelection.rows.length;
728✔
1108
    const rowMarkerChecked =
728✔
1109
        rowMarkers === "none" ? undefined : numSelectedRows === 0 ? false : numSelectedRows === rows ? true : undefined;
728✔
1110

728✔
1111
    const mangledCols = React.useMemo(() => {
728✔
1112
        if (rowMarkers === "none") return columns;
162✔
1113
        return [
47✔
1114
            {
47✔
1115
                title: "",
47✔
1116
                width: rowMarkerWidth,
47✔
1117
                icon: undefined,
47✔
1118
                hasMenu: false,
47✔
1119
                style: "normal" as const,
47✔
1120
                themeOverride: rowMarkerTheme,
47✔
1121
                rowMarker: rowMarkerCheckboxStyle,
47✔
1122
                rowMarkerChecked,
47✔
1123
                headerRowMarkerTheme,
47✔
1124
                headerRowMarkerAlwaysVisible,
47✔
1125
                headerRowMarkerDisabled,
47✔
1126
            },
47✔
1127
            ...columns,
47✔
1128
        ];
47✔
1129
    }, [
728✔
1130
        rowMarkers,
728✔
1131
        columns,
728✔
1132
        rowMarkerWidth,
728✔
1133
        rowMarkerTheme,
728✔
1134
        rowMarkerCheckboxStyle,
728✔
1135
        rowMarkerChecked,
728✔
1136
        headerRowMarkerTheme,
728✔
1137
        headerRowMarkerAlwaysVisible,
728✔
1138
        headerRowMarkerDisabled,
728✔
1139
    ]);
728✔
1140

728✔
1141
    const visibleRegionRef = React.useRef<VisibleRegion>({
728✔
1142
        height: 1,
728✔
1143
        width: 1,
728✔
1144
        x: 0,
728✔
1145
        y: 0,
728✔
1146
    });
728✔
1147

728✔
1148
    const hasJustScrolled = React.useRef(false);
728✔
1149

728✔
1150
    const { setVisibleRegion, visibleRegion, scrollRef } = useInitialScrollOffset(
728✔
1151
        scrollOffsetX,
728✔
1152
        scrollOffsetY,
728✔
1153
        rowHeight,
728✔
1154
        visibleRegionRef,
728✔
1155
        () => (hasJustScrolled.current = true)
728✔
1156
    );
728✔
1157

728✔
1158
    visibleRegionRef.current = visibleRegion;
728✔
1159

728✔
1160
    const cellXOffset = visibleRegion.x + rowMarkerOffset;
728✔
1161
    const cellYOffset = visibleRegion.y;
728✔
1162

728✔
1163
    const gridRef = React.useRef<DataGridRef | null>(null);
728✔
1164

728✔
1165
    const focus = React.useCallback((immediate?: boolean) => {
728✔
1166
        if (immediate === true) {
134✔
1167
            gridRef.current?.focus();
12✔
1168
        } else {
134✔
1169
            window.requestAnimationFrame(() => {
122✔
1170
                gridRef.current?.focus();
121✔
1171
            });
122✔
1172
        }
122✔
1173
    }, []);
728✔
1174

728✔
1175
    const mangledRows = showTrailingBlankRow ? rows + 1 : rows;
728!
1176

728✔
1177
    const mangledOnCellsEdited = React.useCallback<NonNullable<typeof onCellsEdited>>(
728✔
1178
        (items: readonly EditListItem[]) => {
728✔
1179
            const mangledItems =
29✔
1180
                rowMarkerOffset === 0
29✔
1181
                    ? items
24✔
1182
                    : items.map(x => ({
5✔
1183
                          ...x,
29✔
1184
                          location: [x.location[0] - rowMarkerOffset, x.location[1]] as const,
29✔
1185
                      }));
5✔
1186
            const r = onCellsEdited?.(mangledItems);
29✔
1187

29✔
1188
            if (r !== true) {
29✔
1189
                for (const i of mangledItems) onCellEdited?.(i.location, i.value);
28✔
1190
            }
28✔
1191

29✔
1192
            return r;
29✔
1193
        },
29✔
1194
        [onCellEdited, onCellsEdited, rowMarkerOffset]
728✔
1195
    );
728✔
1196

728✔
1197
    const [fillHighlightRegion, setFillHighlightRegion] = React.useState<Rectangle | undefined>();
728✔
1198

728✔
1199
    // this will generally be undefined triggering the memo less often
728✔
1200
    const highlightRange =
728✔
1201
        gridSelection.current !== undefined &&
728✔
1202
        gridSelection.current.range.width * gridSelection.current.range.height > 1
360✔
1203
            ? gridSelection.current.range
44✔
1204
            : undefined;
684✔
1205

728✔
1206
    const highlightFocus = drawFocusRing ? gridSelection.current?.cell : undefined;
728!
1207
    const highlightFocusCol = highlightFocus?.[0];
728✔
1208
    const highlightFocusRow = highlightFocus?.[1];
728✔
1209

728✔
1210
    const highlightRegions = React.useMemo(() => {
728✔
1211
        if (
298✔
1212
            (highlightRegionsIn === undefined || highlightRegionsIn.length === 0) &&
298✔
1213
            (highlightRange ?? highlightFocusCol ?? highlightFocusRow ?? fillHighlightRegion) === undefined
297✔
1214
        )
298✔
1215
            return undefined;
298✔
1216

155✔
1217
        const regions: Highlight[] = [];
155✔
1218

155✔
1219
        if (highlightRegionsIn !== undefined) {
291✔
1220
            for (const r of highlightRegionsIn) {
1✔
1221
                const maxWidth = mangledCols.length - r.range.x - rowMarkerOffset;
1✔
1222
                if (maxWidth > 0) {
1✔
1223
                    regions.push({
1✔
1224
                        color: r.color,
1✔
1225
                        range: {
1✔
1226
                            ...r.range,
1✔
1227
                            x: r.range.x + rowMarkerOffset,
1✔
1228
                            width: Math.min(maxWidth, r.range.width),
1✔
1229
                        },
1✔
1230
                        style: r.style,
1✔
1231
                    });
1✔
1232
                }
1✔
1233
            }
1✔
1234
        }
1✔
1235

155✔
1236
        if (fillHighlightRegion !== undefined) {
291✔
1237
            regions.push({
6✔
1238
                color: withAlpha(mergedTheme.accentColor, 0),
6✔
1239
                range: fillHighlightRegion,
6✔
1240
                style: "dashed",
6✔
1241
            });
6✔
1242
        }
6✔
1243

155✔
1244
        if (highlightRange !== undefined) {
291✔
1245
            regions.push({
30✔
1246
                color: withAlpha(mergedTheme.accentColor, 0.5),
30✔
1247
                range: highlightRange,
30✔
1248
                style: "solid-outline",
30✔
1249
            });
30✔
1250
        }
30✔
1251

155✔
1252
        if (highlightFocusCol !== undefined && highlightFocusRow !== undefined) {
298✔
1253
            regions.push({
154✔
1254
                color: mergedTheme.accentColor,
154✔
1255
                range: {
154✔
1256
                    x: highlightFocusCol,
154✔
1257
                    y: highlightFocusRow,
154✔
1258
                    width: 1,
154✔
1259
                    height: 1,
154✔
1260
                },
154✔
1261
                style: "solid-outline",
154✔
1262
            });
154✔
1263
        }
154✔
1264

155✔
1265
        return regions.length > 0 ? regions : undefined;
298!
1266
    }, [
728✔
1267
        fillHighlightRegion,
728✔
1268
        highlightRange,
728✔
1269
        highlightFocusCol,
728✔
1270
        highlightFocusRow,
728✔
1271
        highlightRegionsIn,
728✔
1272
        mangledCols.length,
728✔
1273
        mergedTheme.accentColor,
728✔
1274
        rowMarkerOffset,
728✔
1275
    ]);
728✔
1276

728✔
1277
    const mangledColsRef = React.useRef(mangledCols);
728✔
1278
    mangledColsRef.current = mangledCols;
728✔
1279
    const getMangledCellContent = React.useCallback(
728✔
1280
        ([col, row]: Item, forceStrict: boolean = false): InnerGridCell => {
728✔
1281
            const isTrailing = showTrailingBlankRow && row === mangledRows - 1;
148,544✔
1282
            const isRowMarkerCol = col === 0 && hasRowMarkers;
148,544✔
1283
            if (isRowMarkerCol) {
148,544✔
1284
                if (isTrailing) {
2,185✔
1285
                    return loadingCell;
67✔
1286
                }
67✔
1287
                const mappedRow = rowNumberMapper(row);
2,118✔
1288
                if (mappedRow === undefined) return loadingCell;
2,185!
1289
                return {
2,118✔
1290
                    kind: InnerGridCellKind.Marker,
2,118✔
1291
                    allowOverlay: false,
2,118✔
1292
                    checkboxStyle: rowMarkerCheckboxStyle,
2,118✔
1293
                    checked: gridSelection?.rows.hasIndex(row) === true,
2,185✔
1294
                    markerKind: rowMarkers === "clickable-number" ? "number" : rowMarkers,
2,185!
1295
                    row: rowMarkerStartIndex + mappedRow,
2,185✔
1296
                    drawHandle: onRowMoved !== undefined,
2,185✔
1297
                    cursor: rowMarkers === "clickable-number" ? "pointer" : undefined,
2,185!
1298
                };
2,185✔
1299
            } else if (isTrailing) {
148,544✔
1300
                //If the grid is empty, we will return text
4,009✔
1301
                const isFirst = col === rowMarkerOffset;
4,009✔
1302

4,009✔
1303
                const maybeFirstColumnHint = isFirst ? trailingRowOptions?.hint ?? "" : "";
4,009✔
1304
                const c = mangledColsRef.current[col];
4,009✔
1305

4,009✔
1306
                if (c?.trailingRowOptions?.disabled === true) {
4,009!
1307
                    return loadingCell;
×
1308
                } else {
4,009✔
1309
                    const hint = c?.trailingRowOptions?.hint ?? maybeFirstColumnHint;
4,009!
1310
                    const icon = c?.trailingRowOptions?.addIcon ?? trailingRowOptions?.addIcon;
4,009!
1311
                    return {
4,009✔
1312
                        kind: InnerGridCellKind.NewRow,
4,009✔
1313
                        hint,
4,009✔
1314
                        allowOverlay: false,
4,009✔
1315
                        icon,
4,009✔
1316
                    };
4,009✔
1317
                }
4,009✔
1318
            } else {
146,359✔
1319
                const outerCol = col - rowMarkerOffset;
142,350✔
1320
                if (forceStrict || experimental?.strict === true) {
142,350✔
1321
                    const vr = visibleRegionRef.current;
25,865✔
1322
                    const isOutsideMainArea =
25,865✔
1323
                        vr.x > outerCol ||
25,865✔
1324
                        outerCol > vr.x + vr.width ||
25,865✔
1325
                        vr.y > row ||
25,865✔
1326
                        row > vr.y + vr.height ||
25,865✔
1327
                        row >= rowsRef.current;
25,865✔
1328
                    const isSelected = outerCol === vr.extras?.selected?.[0] && row === vr.extras?.selected[1];
25,865!
1329
                    let isInFreezeArea = false;
25,865✔
1330
                    if (vr.extras?.freezeRegions !== undefined) {
25,865✔
1331
                        for (const fr of vr.extras.freezeRegions) {
25,865!
1332
                            if (pointInRect(fr, outerCol, row)) {
×
1333
                                isInFreezeArea = true;
×
1334
                                break;
×
1335
                            }
×
1336
                        }
×
1337
                    }
25,865✔
1338

25,865✔
1339
                    if (isOutsideMainArea && !isSelected && !isInFreezeArea) {
25,865!
1340
                        return loadingCell;
×
1341
                    }
×
1342
                }
25,865✔
1343
                let result = getCellContent([outerCol, row]);
142,350✔
1344
                if (rowMarkerOffset !== 0 && result.span !== undefined) {
142,350!
1345
                    result = {
×
NEW
1346
                        ...result,
×
1347
                        span: [result.span[0] + rowMarkerOffset, result.span[1] + rowMarkerOffset],
×
1348
                    };
×
1349
                }
×
1350
                return result;
142,350✔
1351
            }
142,350✔
1352
        },
148,544✔
1353
        [
728✔
1354
            showTrailingBlankRow,
728✔
1355
            mangledRows,
728✔
1356
            hasRowMarkers,
728✔
1357
            rowNumberMapper,
728✔
1358
            rowMarkerCheckboxStyle,
728✔
1359
            gridSelection?.rows,
728✔
1360
            rowMarkers,
728✔
1361
            rowMarkerStartIndex,
728✔
1362
            onRowMoved,
728✔
1363
            rowMarkerOffset,
728✔
1364
            trailingRowOptions?.hint,
728✔
1365
            trailingRowOptions?.addIcon,
728✔
1366
            experimental?.strict,
728✔
1367
            getCellContent,
728✔
1368
        ]
728✔
1369
    );
728✔
1370

728✔
1371
    const mangledGetGroupDetails = React.useCallback<NonNullable<DataEditorProps["getGroupDetails"]>>(
728✔
1372
        group => {
728✔
1373
            let result = getGroupDetails?.(group) ?? { name: group };
8,491✔
1374
            if (onGroupHeaderRenamed !== undefined && group !== "") {
8,491✔
1375
                result = {
88✔
1376
                    icon: result.icon,
88✔
1377
                    name: result.name,
88✔
1378
                    overrideTheme: result.overrideTheme,
88✔
1379
                    actions: [
88✔
1380
                        ...(result.actions ?? []),
88✔
1381
                        {
88✔
1382
                            title: "Rename",
88✔
1383
                            icon: "renameIcon",
88✔
1384
                            onClick: e =>
88✔
1385
                                setRenameGroup({
2✔
1386
                                    group: result.name,
2✔
1387
                                    bounds: e.bounds,
2✔
1388
                                }),
2✔
1389
                        },
88✔
1390
                    ],
88✔
1391
                };
88✔
1392
            }
88✔
1393
            return result;
8,491✔
1394
        },
8,491✔
1395
        [getGroupDetails, onGroupHeaderRenamed]
728✔
1396
    );
728✔
1397

728✔
1398
    const setOverlaySimple = React.useCallback(
728✔
1399
        (val: Omit<NonNullable<typeof overlay>, "theme">) => {
728✔
1400
            const [col, row] = val.cell;
24✔
1401
            const column = mangledCols[col];
24✔
1402
            const groupTheme =
24✔
1403
                column?.group !== undefined ? mangledGetGroupDetails(column.group)?.overrideTheme : undefined;
24!
1404
            const colTheme = column?.themeOverride;
24✔
1405
            const rowTheme = getRowThemeOverride?.(row);
24!
1406

24✔
1407
            setOverlay({
24✔
1408
                ...val,
24✔
1409
                theme: mergeAndRealizeTheme(mergedTheme, groupTheme, colTheme, rowTheme, val.content.themeOverride),
24✔
1410
            });
24✔
1411
        },
24✔
1412
        [getRowThemeOverride, mangledCols, mangledGetGroupDetails, mergedTheme]
728✔
1413
    );
728✔
1414

728✔
1415
    const reselect = React.useCallback(
728✔
1416
        (bounds: Rectangle, fromKeyboard: boolean, initialValue?: string) => {
728✔
1417
            if (gridSelection.current === undefined) return;
25!
1418

25✔
1419
            const [col, row] = gridSelection.current.cell;
25✔
1420
            const c = getMangledCellContent([col, row]);
25✔
1421
            if (c.kind !== GridCellKind.Boolean && c.allowOverlay) {
25✔
1422
                let content = c;
23✔
1423
                if (initialValue !== undefined) {
23✔
1424
                    switch (content.kind) {
12✔
1425
                        case GridCellKind.Number: {
12!
1426
                            const d = maybe(() => (initialValue === "-" ? -0 : Number.parseFloat(initialValue)), 0);
×
1427
                            content = {
×
1428
                                ...content,
×
1429
                                data: Number.isNaN(d) ? 0 : d,
×
1430
                            };
×
1431
                            break;
×
1432
                        }
×
1433
                        case GridCellKind.Text:
12✔
1434
                        case GridCellKind.Markdown:
12✔
1435
                        case GridCellKind.Uri:
12✔
1436
                            content = {
12✔
1437
                                ...content,
12✔
1438
                                data: initialValue,
12✔
1439
                            };
12✔
1440
                            break;
12✔
1441
                    }
12✔
1442
                }
12✔
1443

23✔
1444
                setOverlaySimple({
23✔
1445
                    target: bounds,
23✔
1446
                    content,
23✔
1447
                    initialValue,
23✔
1448
                    cell: [col, row],
23✔
1449
                    highlight: initialValue === undefined,
23✔
1450
                    forceEditMode: initialValue !== undefined,
23✔
1451
                });
23✔
1452
            } else if (c.kind === GridCellKind.Boolean && fromKeyboard && c.readonly !== true) {
25✔
1453
                mangledOnCellsEdited([
1✔
1454
                    {
1✔
1455
                        location: gridSelection.current.cell,
1✔
1456
                        value: {
1✔
1457
                            ...c,
1✔
1458
                            data: toggleBoolean(c.data),
1✔
1459
                        },
1✔
1460
                    },
1✔
1461
                ]);
1✔
1462
                gridRef.current?.damage([{ cell: gridSelection.current.cell }]);
1✔
1463
            }
1✔
1464
        },
25✔
1465
        [getMangledCellContent, gridSelection, mangledOnCellsEdited, setOverlaySimple]
728✔
1466
    );
728✔
1467

728✔
1468
    const focusOnRowFromTrailingBlankRow = React.useCallback(
728✔
1469
        (col: number, row: number) => {
728✔
1470
            const bounds = gridRef.current?.getBounds(col, row);
1✔
1471
            if (bounds === undefined || scrollRef.current === null) {
1!
1472
                return;
×
1473
            }
×
1474

1✔
1475
            const content = getMangledCellContent([col, row]);
1✔
1476
            if (!content.allowOverlay) {
1!
1477
                return;
×
1478
            }
×
1479

1✔
1480
            setOverlaySimple({
1✔
1481
                target: bounds,
1✔
1482
                content,
1✔
1483
                initialValue: undefined,
1✔
1484
                highlight: true,
1✔
1485
                cell: [col, row],
1✔
1486
                forceEditMode: true,
1✔
1487
            });
1✔
1488
        },
1✔
1489
        [getMangledCellContent, scrollRef, setOverlaySimple]
728✔
1490
    );
728✔
1491

728✔
1492
    const scrollTo = React.useCallback<ScrollToFn>(
728✔
1493
        (col, row, dir = "both", paddingX = 0, paddingY = 0, options = undefined): void => {
728✔
1494
            if (scrollRef.current !== null) {
51✔
1495
                const grid = gridRef.current;
51✔
1496
                const canvas = canvasRef.current;
51✔
1497

51✔
1498
                const trueCol = typeof col !== "number" ? (col.unit === "cell" ? col.amount : undefined) : col;
51!
1499
                const trueRow = typeof row !== "number" ? (row.unit === "cell" ? row.amount : undefined) : row;
51!
1500
                const desiredX = typeof col !== "number" && col.unit === "px" ? col.amount : undefined;
51!
1501
                const desiredY = typeof row !== "number" && row.unit === "px" ? row.amount : undefined;
51✔
1502
                if (grid !== null && canvas !== null) {
51✔
1503
                    let targetRect: Rectangle = {
51✔
1504
                        x: 0,
51✔
1505
                        y: 0,
51✔
1506
                        width: 0,
51✔
1507
                        height: 0,
51✔
1508
                    };
51✔
1509

51✔
1510
                    let scrollX = 0;
51✔
1511
                    let scrollY = 0;
51✔
1512

51✔
1513
                    if (trueCol !== undefined || trueRow !== undefined) {
51!
1514
                        targetRect = grid.getBounds((trueCol ?? 0) + rowMarkerOffset, trueRow ?? 0) ?? targetRect;
51!
1515
                        if (targetRect.width === 0 || targetRect.height === 0) return;
51!
1516
                    }
51✔
1517

51✔
1518
                    const scrollBounds = canvas.getBoundingClientRect();
51✔
1519
                    const scale = scrollBounds.width / canvas.offsetWidth;
51✔
1520

51✔
1521
                    if (desiredX !== undefined) {
51!
1522
                        targetRect = {
×
1523
                            ...targetRect,
×
1524
                            x: desiredX - scrollBounds.left - scrollRef.current.scrollLeft,
×
1525
                            width: 1,
×
1526
                        };
×
1527
                    }
×
1528
                    if (desiredY !== undefined) {
51✔
1529
                        targetRect = {
4✔
1530
                            ...targetRect,
4✔
1531
                            y: desiredY + scrollBounds.top - scrollRef.current.scrollTop,
4✔
1532
                            height: 1,
4✔
1533
                        };
4✔
1534
                    }
4✔
1535

51✔
1536
                    if (targetRect !== undefined) {
51✔
1537
                        const bounds = {
51✔
1538
                            x: targetRect.x - paddingX,
51✔
1539
                            y: targetRect.y - paddingY,
51✔
1540
                            width: targetRect.width + 2 * paddingX,
51✔
1541
                            height: targetRect.height + 2 * paddingY,
51✔
1542
                        };
51✔
1543

51✔
1544
                        let frozenWidth = 0;
51✔
1545
                        for (let i = 0; i < freezeColumns; i++) {
51!
1546
                            frozenWidth += columns[i].width;
×
1547
                        }
×
1548
                        let trailingRowHeight = 0;
51✔
1549
                        const freezeTrailingRowsEffective = freezeTrailingRows + (lastRowSticky ? 1 : 0);
51!
1550
                        if (freezeTrailingRowsEffective > 0) {
51✔
1551
                            trailingRowHeight = getFreezeTrailingHeight(
51✔
1552
                                mangledRows,
51✔
1553
                                freezeTrailingRowsEffective,
51✔
1554
                                rowHeight
51✔
1555
                            );
51✔
1556
                        }
51✔
1557

51✔
1558
                        // scrollBounds is already scaled
51✔
1559
                        let sLeft = frozenWidth * scale + scrollBounds.left + rowMarkerOffset * rowMarkerWidth * scale;
51✔
1560
                        let sRight = scrollBounds.right;
51✔
1561
                        let sTop = scrollBounds.top + totalHeaderHeight * scale;
51✔
1562
                        let sBottom = scrollBounds.bottom - trailingRowHeight * scale;
51✔
1563

51✔
1564
                        const minx = targetRect.width + paddingX * 2;
51✔
1565
                        switch (options?.hAlign) {
51✔
1566
                            case "start":
51!
1567
                                sRight = sLeft + minx;
×
1568
                                break;
×
1569
                            case "end":
51!
1570
                                sLeft = sRight - minx;
×
1571
                                break;
×
1572
                            case "center":
51!
1573
                                sLeft = Math.floor((sLeft + sRight) / 2) - minx / 2;
×
1574
                                sRight = sLeft + minx;
×
1575
                                break;
×
1576
                        }
51✔
1577

51✔
1578
                        const miny = targetRect.height + paddingY * 2;
51✔
1579
                        switch (options?.vAlign) {
51✔
1580
                            case "start":
51✔
1581
                                sBottom = sTop + miny;
1✔
1582
                                break;
1✔
1583
                            case "end":
51✔
1584
                                sTop = sBottom - miny;
1✔
1585
                                break;
1✔
1586
                            case "center":
51✔
1587
                                sTop = Math.floor((sTop + sBottom) / 2) - miny / 2;
1✔
1588
                                sBottom = sTop + miny;
1✔
1589
                                break;
1✔
1590
                        }
51✔
1591

51✔
1592
                        if (sLeft > bounds.x) {
51!
1593
                            scrollX = bounds.x - sLeft;
×
1594
                        } else if (sRight < bounds.x + bounds.width) {
51✔
1595
                            scrollX = bounds.x + bounds.width - sRight;
6✔
1596
                        }
6✔
1597

51✔
1598
                        if (sTop > bounds.y) {
51!
1599
                            scrollY = bounds.y - sTop;
×
1600
                        } else if (sBottom < bounds.y + bounds.height) {
51✔
1601
                            scrollY = bounds.y + bounds.height - sBottom;
15✔
1602
                        }
15✔
1603

51✔
1604
                        if (dir === "vertical" || (typeof col === "number" && col < freezeColumns)) {
51✔
1605
                            scrollX = 0;
4✔
1606
                        } else if (
4✔
1607
                            dir === "horizontal" ||
47✔
1608
                            (typeof row === "number" && row >= mangledRows - freezeTrailingRowsEffective)
39✔
1609
                        ) {
47✔
1610
                            scrollY = 0;
10✔
1611
                        }
10✔
1612

51✔
1613
                        if (scrollX !== 0 || scrollY !== 0) {
51✔
1614
                            // Remove scaling as scrollTo method is unaffected by transform scale.
18✔
1615
                            if (scale !== 1) {
18!
1616
                                scrollX /= scale;
×
1617
                                scrollY /= scale;
×
1618
                            }
×
1619
                            scrollRef.current.scrollTo({
18✔
1620
                                left: scrollX + scrollRef.current.scrollLeft,
18✔
1621
                                top: scrollY + scrollRef.current.scrollTop,
18✔
1622
                                behavior: options?.behavior ?? "auto",
18✔
1623
                            });
18✔
1624
                        }
18✔
1625
                    }
51✔
1626
                }
51✔
1627
            }
51✔
1628
        },
51✔
1629
        [
728✔
1630
            rowMarkerOffset,
728✔
1631
            freezeTrailingRows,
728✔
1632
            rowMarkerWidth,
728✔
1633
            scrollRef,
728✔
1634
            totalHeaderHeight,
728✔
1635
            freezeColumns,
728✔
1636
            columns,
728✔
1637
            mangledRows,
728✔
1638
            lastRowSticky,
728✔
1639
            rowHeight,
728✔
1640
        ]
728✔
1641
    );
728✔
1642

728✔
1643
    const focusCallback = React.useRef(focusOnRowFromTrailingBlankRow);
728✔
1644
    const getCellContentRef = React.useRef(getCellContent);
728✔
1645
    const rowsRef = React.useRef(rows);
728✔
1646
    focusCallback.current = focusOnRowFromTrailingBlankRow;
728✔
1647
    getCellContentRef.current = getCellContent;
728✔
1648
    rowsRef.current = rows;
728✔
1649
    const appendRow = React.useCallback(
728✔
1650
        async (col: number, openOverlay: boolean = true, behavior?: ScrollBehavior): Promise<void> => {
728✔
1651
            const c = mangledCols[col];
1✔
1652
            if (c?.trailingRowOptions?.disabled === true) {
1!
1653
                return;
×
1654
            }
×
1655
            const appendResult = onRowAppended?.();
1✔
1656

1✔
1657
            let r: "top" | "bottom" | number | undefined = undefined;
1✔
1658
            let bottom = true;
1✔
1659
            if (appendResult !== undefined) {
1!
1660
                r = await appendResult;
×
1661
                if (r === "top") bottom = false;
×
1662
                if (typeof r === "number") bottom = false;
×
1663
            }
×
1664

1✔
1665
            let backoff = 0;
1✔
1666
            const doFocus = () => {
1✔
1667
                if (rowsRef.current <= rows) {
2✔
1668
                    if (backoff < 500) {
1✔
1669
                        window.setTimeout(doFocus, backoff);
1✔
1670
                    }
1✔
1671
                    backoff = 50 + backoff * 2;
1✔
1672
                    return;
1✔
1673
                }
1✔
1674

1✔
1675
                const row = typeof r === "number" ? r : bottom ? rows : 0;
2!
1676
                scrollToRef.current(col - rowMarkerOffset, row, "both", 0, 0, behavior ? { behavior } : undefined);
2!
1677
                setCurrent(
2✔
1678
                    {
2✔
1679
                        cell: [col, row],
2✔
1680
                        range: {
2✔
1681
                            x: col,
2✔
1682
                            y: row,
2✔
1683
                            width: 1,
2✔
1684
                            height: 1,
2✔
1685
                        },
2✔
1686
                    },
2✔
1687
                    false,
2✔
1688
                    false,
2✔
1689
                    "edit"
2✔
1690
                );
2✔
1691

2✔
1692
                const cell = getCellContentRef.current([col - rowMarkerOffset, row]);
2✔
1693
                if (cell.allowOverlay && isReadWriteCell(cell) && cell.readonly !== true && openOverlay) {
2✔
1694
                    // wait for scroll to have a chance to process
1✔
1695
                    window.setTimeout(() => {
1✔
1696
                        focusCallback.current(col, row);
1✔
1697
                    }, 0);
1✔
1698
                }
1✔
1699
            };
2✔
1700
            // Queue up to allow the consumer to react to the event and let us check if they did
1✔
1701
            doFocus();
1✔
1702
        },
1✔
1703
        [mangledCols, onRowAppended, rowMarkerOffset, rows, setCurrent]
728✔
1704
    );
728✔
1705

728✔
1706
    const getCustomNewRowTargetColumn = React.useCallback(
728✔
1707
        (col: number): number | undefined => {
728✔
1708
            const customTargetColumn =
1✔
1709
                columns[col]?.trailingRowOptions?.targetColumn ?? trailingRowOptions?.targetColumn;
1!
1710

1✔
1711
            if (typeof customTargetColumn === "number") {
1!
1712
                const customTargetOffset = hasRowMarkers ? 1 : 0;
×
1713
                return customTargetColumn + customTargetOffset;
×
1714
            }
×
1715

1✔
1716
            if (typeof customTargetColumn === "object") {
1!
1717
                const maybeIndex = columnsIn.indexOf(customTargetColumn);
×
1718
                if (maybeIndex >= 0) {
×
1719
                    const customTargetOffset = hasRowMarkers ? 1 : 0;
×
1720
                    return maybeIndex + customTargetOffset;
×
1721
                }
×
1722
            }
×
1723

1✔
1724
            return undefined;
1✔
1725
        },
1✔
1726
        [columns, columnsIn, hasRowMarkers, trailingRowOptions?.targetColumn]
728✔
1727
    );
728✔
1728

728✔
1729
    const lastSelectedRowRef = React.useRef<number>();
728✔
1730
    const lastSelectedColRef = React.useRef<number>();
728✔
1731

728✔
1732
    const themeForCell = React.useCallback(
728✔
1733
        (cell: InnerGridCell, pos: Item): FullTheme => {
728✔
1734
            const [col, row] = pos;
28✔
1735
            return mergeAndRealizeTheme(
28✔
1736
                mergedTheme,
28✔
1737
                mangledCols[col]?.themeOverride,
28✔
1738
                getRowThemeOverride?.(row),
28!
1739
                cell.themeOverride
28✔
1740
            );
28✔
1741
        },
28✔
1742
        [getRowThemeOverride, mangledCols, mergedTheme]
728✔
1743
    );
728✔
1744

728✔
1745
    const { mapper } = useRowGrouping(rowGrouping, rowsIn);
728✔
1746

728✔
1747
    const rowGroupingNavBehavior = rowGrouping?.navigationBehavior;
728!
1748

728✔
1749
    const handleSelect = React.useCallback(
728✔
1750
        (args: GridMouseEventArgs) => {
728✔
1751
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
126!
1752
            const isMultiRow = isMultiKey && rowSelect === "multi";
126✔
1753
            const isMultiCol = isMultiKey && columnSelect === "multi";
126✔
1754
            const [col, row] = args.location;
126✔
1755
            const selectedColumns = gridSelection.columns;
126✔
1756
            const selectedRows = gridSelection.rows;
126✔
1757
            const [cellCol, cellRow] = gridSelection.current?.cell ?? [];
126✔
1758
            // eslint-disable-next-line unicorn/prefer-switch
126✔
1759
            if (args.kind === "cell") {
126✔
1760
                lastSelectedColRef.current = undefined;
110✔
1761

110✔
1762
                lastMouseSelectLocation.current = [col, row];
110✔
1763

110✔
1764
                if (col === 0 && hasRowMarkers) {
110✔
1765
                    if (
15✔
1766
                        (showTrailingBlankRow === true && row === rows) ||
15✔
1767
                        rowMarkers === "number" ||
15✔
1768
                        rowSelect === "none"
14✔
1769
                    )
15✔
1770
                        return;
15✔
1771

14✔
1772
                    const markerCell = getMangledCellContent(args.location);
14✔
1773
                    if (markerCell.kind !== InnerGridCellKind.Marker) {
15!
1774
                        return;
×
1775
                    }
✔
1776

14✔
1777
                    if (onRowMoved !== undefined) {
15!
1778
                        const renderer = getCellRenderer(markerCell);
×
1779
                        assert(renderer?.kind === InnerGridCellKind.Marker);
×
1780
                        const postClick = renderer?.onClick?.({
×
1781
                            ...args,
×
1782
                            cell: markerCell,
×
1783
                            posX: args.localEventX,
×
1784
                            posY: args.localEventY,
×
1785
                            bounds: args.bounds,
×
1786
                            theme: themeForCell(markerCell, args.location),
×
1787
                            preventDefault: () => undefined,
×
1788
                        }) as MarkerCell | undefined;
×
1789
                        if (postClick === undefined || postClick.checked === markerCell.checked) return;
×
1790
                    }
✔
1791

14✔
1792
                    setOverlay(undefined);
14✔
1793
                    focus();
14✔
1794
                    const isSelected = selectedRows.hasIndex(row);
14✔
1795

14✔
1796
                    const lastHighlighted = lastSelectedRowRef.current;
14✔
1797
                    if (
14✔
1798
                        rowSelect === "multi" &&
14✔
1799
                        (args.shiftKey || args.isLongTouch === true) &&
8✔
1800
                        lastHighlighted !== undefined &&
1✔
1801
                        selectedRows.hasIndex(lastHighlighted)
1✔
1802
                    ) {
15✔
1803
                        const newSlice: Slice = [Math.min(lastHighlighted, row), Math.max(lastHighlighted, row) + 1];
1✔
1804

1✔
1805
                        if (isMultiRow || rowSelectionMode === "multi") {
1!
1806
                            setSelectedRows(undefined, newSlice, true);
×
1807
                        } else {
1✔
1808
                            setSelectedRows(CompactSelection.fromSingleSelection(newSlice), undefined, isMultiRow);
1✔
1809
                        }
1✔
1810
                    } else if (rowSelect === "multi" && (isMultiRow || args.isTouch || rowSelectionMode === "multi")) {
15✔
1811
                        if (isSelected) {
3✔
1812
                            setSelectedRows(selectedRows.remove(row), undefined, true);
1✔
1813
                        } else {
2✔
1814
                            setSelectedRows(undefined, row, true);
2✔
1815
                            lastSelectedRowRef.current = row;
2✔
1816
                        }
2✔
1817
                    } else if (isSelected && selectedRows.length === 1) {
13✔
1818
                        setSelectedRows(CompactSelection.empty(), undefined, isMultiKey);
1✔
1819
                    } else {
10✔
1820
                        setSelectedRows(CompactSelection.fromSingleSelection(row), undefined, isMultiKey);
9✔
1821
                        lastSelectedRowRef.current = row;
9✔
1822
                    }
9✔
1823
                } else if (col >= rowMarkerOffset && showTrailingBlankRow && row === rows) {
110✔
1824
                    const customTargetColumn = getCustomNewRowTargetColumn(col);
1✔
1825
                    void appendRow(customTargetColumn ?? col);
1✔
1826
                } else {
95✔
1827
                    if (cellCol !== col || cellRow !== row) {
94✔
1828
                        const cell = getMangledCellContent(args.location);
88✔
1829
                        const renderer = getCellRenderer(cell);
88✔
1830

88✔
1831
                        if (renderer?.onSelect !== undefined) {
88✔
1832
                            let prevented = false;
7✔
1833
                            renderer.onSelect({
7✔
1834
                                ...args,
7✔
1835
                                cell,
7✔
1836
                                posX: args.localEventX,
7✔
1837
                                posY: args.localEventY,
7✔
1838
                                bounds: args.bounds,
7✔
1839
                                preventDefault: () => (prevented = true),
7✔
1840
                                theme: themeForCell(cell, args.location),
7✔
1841
                            });
7✔
1842
                            if (prevented) {
7✔
1843
                                return;
4✔
1844
                            }
4✔
1845
                        }
7✔
1846

84✔
1847
                        if (rowGroupingNavBehavior === "block" && mapper(row).isGroupHeader) {
88!
1848
                            return;
×
1849
                        }
✔
1850

84✔
1851
                        const isLastStickyRow = lastRowSticky && row === rows;
84✔
1852

88✔
1853
                        const startedFromLastSticky =
88✔
1854
                            lastRowSticky && gridSelection !== undefined && gridSelection.current?.cell[1] === rows;
88✔
1855

88✔
1856
                        if (
88✔
1857
                            (args.shiftKey || args.isLongTouch === true) &&
88✔
1858
                            cellCol !== undefined &&
6✔
1859
                            cellRow !== undefined &&
6✔
1860
                            gridSelection.current !== undefined &&
6✔
1861
                            !startedFromLastSticky
6✔
1862
                        ) {
88✔
1863
                            if (isLastStickyRow) {
6!
1864
                                // If we're making a selection and shift click in to the last sticky row,
×
1865
                                // just drop the event. Don't kill the selection.
×
1866
                                return;
×
1867
                            }
×
1868

6✔
1869
                            const left = Math.min(col, cellCol);
6✔
1870
                            const right = Math.max(col, cellCol);
6✔
1871
                            const top = Math.min(row, cellRow);
6✔
1872
                            const bottom = Math.max(row, cellRow);
6✔
1873
                            setCurrent(
6✔
1874
                                {
6✔
1875
                                    ...gridSelection.current,
6✔
1876
                                    range: {
6✔
1877
                                        x: left,
6✔
1878
                                        y: top,
6✔
1879
                                        width: right - left + 1,
6✔
1880
                                        height: bottom - top + 1,
6✔
1881
                                    },
6✔
1882
                                },
6✔
1883
                                true,
6✔
1884
                                isMultiKey,
6✔
1885
                                "click"
6✔
1886
                            );
6✔
1887
                            lastSelectedRowRef.current = undefined;
6✔
1888
                            focus();
6✔
1889
                        } else {
88✔
1890
                            setCurrent(
78✔
1891
                                {
78✔
1892
                                    cell: [col, row],
78✔
1893
                                    range: { x: col, y: row, width: 1, height: 1 },
78✔
1894
                                },
78✔
1895
                                true,
78✔
1896
                                isMultiKey,
78✔
1897
                                "click"
78✔
1898
                            );
78✔
1899
                            lastSelectedRowRef.current = undefined;
78✔
1900
                            setOverlay(undefined);
78✔
1901
                            focus();
78✔
1902
                        }
78✔
1903
                    }
88✔
1904
                }
94✔
1905
            } else if (args.kind === "header") {
126✔
1906
                lastMouseSelectLocation.current = [col, row];
12✔
1907
                setOverlay(undefined);
12✔
1908
                if (hasRowMarkers && col === 0) {
12✔
1909
                    lastSelectedRowRef.current = undefined;
4✔
1910
                    lastSelectedColRef.current = undefined;
4✔
1911
                    if (rowSelect === "multi") {
4✔
1912
                        if (selectedRows.length !== rows) {
4✔
1913
                            setSelectedRows(CompactSelection.fromSingleSelection([0, rows]), undefined, isMultiKey);
3✔
1914
                        } else {
4✔
1915
                            setSelectedRows(CompactSelection.empty(), undefined, isMultiKey);
1✔
1916
                        }
1✔
1917
                        focus();
4✔
1918
                    }
4✔
1919
                } else {
12✔
1920
                    const lastCol = lastSelectedColRef.current;
8✔
1921
                    if (
8✔
1922
                        columnSelect === "multi" &&
8✔
1923
                        (args.shiftKey || args.isLongTouch === true) &&
7!
1924
                        lastCol !== undefined &&
×
1925
                        selectedColumns.hasIndex(lastCol)
×
1926
                    ) {
8!
1927
                        const newSlice: Slice = [Math.min(lastCol, col), Math.max(lastCol, col) + 1];
×
1928

×
1929
                        if (isMultiCol) {
×
1930
                            setSelectedColumns(undefined, newSlice, isMultiKey);
×
1931
                        } else {
×
1932
                            setSelectedColumns(CompactSelection.fromSingleSelection(newSlice), undefined, isMultiKey);
×
1933
                        }
×
1934
                    } else if (isMultiCol) {
8✔
1935
                        if (selectedColumns.hasIndex(col)) {
1!
NEW
1936
                            // If the column is already selected, deselect that column:
×
UNCOV
1937
                            setSelectedColumns(selectedColumns.remove(col), undefined, isMultiKey);
×
1938
                        } else {
1✔
1939
                            setSelectedColumns(undefined, col, isMultiKey);
1✔
1940
                        }
1✔
1941
                        lastSelectedColRef.current = col;
1✔
1942
                    } else if (columnSelect !== "none") {
8✔
1943
                        if (selectedColumns.hasIndex(col)) {
7!
NEW
1944
                            setSelectedColumns(selectedColumns.remove(col), undefined, isMultiKey);
×
1945
                        } else {
7✔
1946
                            setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, isMultiKey);
7✔
1947
                        }
7✔
1948
                        lastSelectedColRef.current = col;
7✔
1949
                    }
7✔
1950
                    lastSelectedRowRef.current = undefined;
8✔
1951
                    focus();
8✔
1952
                }
8✔
1953
            } else if (args.kind === groupHeaderKind) {
16✔
1954
                lastMouseSelectLocation.current = [col, row];
3✔
1955
            } else if (args.kind === outOfBoundsKind && !args.isMaybeScrollbar) {
4✔
1956
                setGridSelection(emptyGridSelection, false);
1✔
1957
                setOverlay(undefined);
1✔
1958
                focus();
1✔
1959
                onSelectionCleared?.();
1!
1960
                lastSelectedRowRef.current = undefined;
1✔
1961
                lastSelectedColRef.current = undefined;
1✔
1962
            }
1✔
1963
        },
126✔
1964
        [
728✔
1965
            rowSelect,
728✔
1966
            columnSelect,
728✔
1967
            gridSelection,
728✔
1968
            hasRowMarkers,
728✔
1969
            rowMarkerOffset,
728✔
1970
            showTrailingBlankRow,
728✔
1971
            rows,
728✔
1972
            rowMarkers,
728✔
1973
            getMangledCellContent,
728✔
1974
            onRowMoved,
728✔
1975
            focus,
728✔
1976
            rowSelectionMode,
728✔
1977
            getCellRenderer,
728✔
1978
            themeForCell,
728✔
1979
            setSelectedRows,
728✔
1980
            getCustomNewRowTargetColumn,
728✔
1981
            appendRow,
728✔
1982
            rowGroupingNavBehavior,
728✔
1983
            mapper,
728✔
1984
            lastRowSticky,
728✔
1985
            setCurrent,
728✔
1986
            setSelectedColumns,
728✔
1987
            setGridSelection,
728✔
1988
            onSelectionCleared,
728✔
1989
        ]
728✔
1990
    );
728✔
1991
    const isActivelyDraggingHeader = React.useRef(false);
728✔
1992
    const lastMouseSelectLocation = React.useRef<readonly [number, number]>();
728✔
1993
    const touchDownArgs = React.useRef(visibleRegion);
728✔
1994
    const mouseDownData = React.useRef<{
728✔
1995
        time: number;
728✔
1996
        button: number;
728✔
1997
        location: Item;
728✔
1998
    }>();
728✔
1999
    const onMouseDown = React.useCallback(
728✔
2000
        (args: GridMouseEventArgs) => {
728✔
2001
            isPrevented.current = false;
144✔
2002
            touchDownArgs.current = visibleRegionRef.current;
144✔
2003
            if (args.button !== 0 && args.button !== 1) {
144✔
2004
                mouseDownData.current = undefined;
1✔
2005
                return;
1✔
2006
            }
1✔
2007

143✔
2008
            const time = performance.now();
143✔
2009
            mouseDownData.current = {
143✔
2010
                button: args.button,
143✔
2011
                time,
143✔
2012
                location: args.location,
143✔
2013
            };
143✔
2014

143✔
2015
            if (args?.kind === "header") {
144✔
2016
                isActivelyDraggingHeader.current = true;
18✔
2017
            }
18✔
2018

143✔
2019
            const fh = args.kind === "cell" && args.isFillHandle;
144✔
2020

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

136✔
2023
            setMouseState({
136✔
2024
                previousSelection: gridSelection,
136✔
2025
                fillHandle: fh,
136✔
2026
            });
136✔
2027
            lastMouseSelectLocation.current = undefined;
136✔
2028

136✔
2029
            if (!args.isTouch && args.button === 0 && !fh) {
144✔
2030
                handleSelect(args);
123✔
2031
            } else if (!args.isTouch && args.button === 1) {
137✔
2032
                lastMouseSelectLocation.current = args.location;
4✔
2033
            }
4✔
2034
        },
144✔
2035
        [gridSelection, handleSelect]
728✔
2036
    );
728✔
2037

728✔
2038
    const [renameGroup, setRenameGroup] = React.useState<{
728✔
2039
        group: string;
728✔
2040
        bounds: Rectangle;
728✔
2041
    }>();
728✔
2042

728✔
2043
    const handleGroupHeaderSelection = React.useCallback(
728✔
2044
        (args: GridMouseEventArgs) => {
728✔
2045
            if (args.kind !== groupHeaderKind || columnSelect !== "multi") {
3!
2046
                return;
×
2047
            }
×
2048
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
3!
2049
            const [col] = args.location;
3✔
2050
            const selectedColumns = gridSelection.columns;
3✔
2051

3✔
2052
            if (col < rowMarkerOffset) return;
3!
2053

3✔
2054
            const needle = mangledCols[col];
3✔
2055
            let start = col;
3✔
2056
            let end = col;
3✔
2057
            for (let i = col - 1; i >= rowMarkerOffset; i--) {
3✔
2058
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
3!
2059
                start--;
3✔
2060
            }
3✔
2061

3✔
2062
            for (let i = col + 1; i < mangledCols.length; i++) {
3✔
2063
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
27!
2064
                end++;
27✔
2065
            }
27✔
2066

3✔
2067
            focus();
3✔
2068

3✔
2069
            if (isMultiKey) {
3✔
2070
                if (selectedColumns.hasAll([start, end + 1])) {
2✔
2071
                    let newVal = selectedColumns;
1✔
2072
                    for (let index = start; index <= end; index++) {
1✔
2073
                        newVal = newVal.remove(index);
11✔
2074
                    }
11✔
2075
                    setSelectedColumns(newVal, undefined, isMultiKey);
1✔
2076
                } else {
1✔
2077
                    setSelectedColumns(undefined, [start, end + 1], isMultiKey);
1✔
2078
                }
1✔
2079
            } else {
3✔
2080
                setSelectedColumns(CompactSelection.fromSingleSelection([start, end + 1]), undefined, isMultiKey);
1✔
2081
            }
1✔
2082
        },
3✔
2083
        [columnSelect, focus, gridSelection.columns, mangledCols, rowMarkerOffset, setSelectedColumns]
728✔
2084
    );
728✔
2085

728✔
2086
    const isPrevented = React.useRef(false);
728✔
2087

728✔
2088
    const normalSizeColumn = React.useCallback(
728✔
2089
        async (col: number): Promise<void> => {
728✔
2090
            if (getCellsForSelection !== undefined && onColumnResize !== undefined) {
2✔
2091
                const start = visibleRegionRef.current.y;
2✔
2092
                const end = visibleRegionRef.current.height;
2✔
2093
                let cells = getCellsForSelection(
2✔
2094
                    {
2✔
2095
                        x: col,
2✔
2096
                        y: start,
2✔
2097
                        width: 1,
2✔
2098
                        height: Math.min(end, rows - start),
2✔
2099
                    },
2✔
2100
                    abortControllerRef.current.signal
2✔
2101
                );
2✔
2102
                if (typeof cells !== "object") {
2!
2103
                    cells = await cells();
×
2104
                }
×
2105
                const inputCol = columns[col - rowMarkerOffset];
2✔
2106
                const offscreen = document.createElement("canvas");
2✔
2107
                const ctx = offscreen.getContext("2d", { alpha: false });
2✔
2108
                if (ctx !== null) {
2✔
2109
                    ctx.font = mergedTheme.baseFontFull;
2✔
2110
                    const newCol = measureColumn(
2✔
2111
                        ctx,
2✔
2112
                        mergedTheme,
2✔
2113
                        inputCol,
2✔
2114
                        0,
2✔
2115
                        cells,
2✔
2116
                        minColumnWidth,
2✔
2117
                        maxColumnWidth,
2✔
2118
                        false,
2✔
2119
                        getCellRenderer
2✔
2120
                    );
2✔
2121
                    onColumnResize?.(inputCol, newCol.width, col, newCol.width);
2✔
2122
                }
2✔
2123
            }
2✔
2124
        },
2✔
2125
        [
728✔
2126
            columns,
728✔
2127
            getCellsForSelection,
728✔
2128
            maxColumnWidth,
728✔
2129
            mergedTheme,
728✔
2130
            minColumnWidth,
728✔
2131
            onColumnResize,
728✔
2132
            rowMarkerOffset,
728✔
2133
            rows,
728✔
2134
            getCellRenderer,
728✔
2135
        ]
728✔
2136
    );
728✔
2137

728✔
2138
    const [scrollDir, setScrollDir] = React.useState<GridMouseEventArgs["scrollEdge"]>();
728✔
2139

728✔
2140
    const fillPattern = React.useCallback(
728✔
2141
        async (previousSelection: GridSelection, currentSelection: GridSelection) => {
728✔
2142
            const patternRange = previousSelection.current?.range;
7✔
2143

7✔
2144
            if (
7✔
2145
                patternRange === undefined ||
7✔
2146
                getCellsForSelection === undefined ||
7✔
2147
                currentSelection.current === undefined
7✔
2148
            ) {
7!
2149
                return;
×
2150
            }
×
2151
            const currentRange = currentSelection.current.range;
7✔
2152

7✔
2153
            if (onFillPattern !== undefined) {
7✔
2154
                let canceled = false;
1✔
2155
                onFillPattern({
1✔
2156
                    fillDestination: { ...currentRange, x: currentRange.x - rowMarkerOffset },
1✔
2157
                    patternSource: { ...patternRange, x: patternRange.x - rowMarkerOffset },
1✔
2158
                    preventDefault: () => (canceled = true),
1✔
2159
                });
1✔
2160
                if (canceled) return;
1!
2161
            }
1✔
2162

7✔
2163
            let cells = getCellsForSelection(patternRange, abortControllerRef.current.signal);
7✔
2164
            if (typeof cells !== "object") cells = await cells();
7!
2165

7✔
2166
            const pattern = cells;
7✔
2167

7✔
2168
            // loop through all cells in currentSelection.current.range
7✔
2169
            const editItemList: EditListItem[] = [];
7✔
2170
            for (let x = 0; x < currentRange.width; x++) {
7✔
2171
                for (let y = 0; y < currentRange.height; y++) {
9✔
2172
                    const cell: Item = [currentRange.x + x, currentRange.y + y];
41✔
2173
                    if (itemIsInRect(cell, patternRange)) continue;
41✔
2174
                    const patternCell = pattern[y % patternRange.height][x % patternRange.width];
29✔
2175
                    if (isInnerOnlyCell(patternCell) || !isReadWriteCell(patternCell)) continue;
41!
2176
                    editItemList.push({
29✔
2177
                        location: cell,
29✔
2178
                        value: { ...patternCell },
29✔
2179
                    });
29✔
2180
                }
29✔
2181
            }
9✔
2182
            mangledOnCellsEdited(editItemList);
7✔
2183

7✔
2184
            gridRef.current?.damage(
7✔
2185
                editItemList.map(c => ({
7✔
2186
                    cell: c.location,
29✔
2187
                }))
7✔
2188
            );
7✔
2189
        },
7✔
2190
        [getCellsForSelection, mangledOnCellsEdited, onFillPattern, rowMarkerOffset]
728✔
2191
    );
728✔
2192

728✔
2193
    const fillRight = React.useCallback(() => {
728✔
2194
        if (gridSelection.current === undefined || gridSelection.current.range.width <= 1) return;
1!
2195

1✔
2196
        const firstColSelection = {
1✔
2197
            ...gridSelection,
1✔
2198
            current: {
1✔
2199
                ...gridSelection.current,
1✔
2200
                range: {
1✔
2201
                    ...gridSelection.current.range,
1✔
2202
                    width: 1,
1✔
2203
                },
1✔
2204
            },
1✔
2205
        };
1✔
2206

1✔
2207
        void fillPattern(firstColSelection, gridSelection);
1✔
2208
    }, [fillPattern, gridSelection]);
728✔
2209

728✔
2210
    const fillDown = React.useCallback(() => {
728✔
2211
        if (gridSelection.current === undefined || gridSelection.current.range.height <= 1) return;
1!
2212

1✔
2213
        const firstRowSelection = {
1✔
2214
            ...gridSelection,
1✔
2215
            current: {
1✔
2216
                ...gridSelection.current,
1✔
2217
                range: {
1✔
2218
                    ...gridSelection.current.range,
1✔
2219
                    height: 1,
1✔
2220
                },
1✔
2221
            },
1✔
2222
        };
1✔
2223

1✔
2224
        void fillPattern(firstRowSelection, gridSelection);
1✔
2225
    }, [fillPattern, gridSelection]);
728✔
2226

728✔
2227
    const onMouseUp = React.useCallback(
728✔
2228
        (args: GridMouseEventArgs, isOutside: boolean) => {
728✔
2229
            const mouse = mouseState;
143✔
2230
            setMouseState(undefined);
143✔
2231
            setFillHighlightRegion(undefined);
143✔
2232
            setScrollDir(undefined);
143✔
2233
            isActivelyDraggingHeader.current = false;
143✔
2234

143✔
2235
            if (isOutside) return;
143✔
2236

142✔
2237
            if (
142✔
2238
                mouse?.fillHandle === true &&
143✔
2239
                gridSelection.current !== undefined &&
5✔
2240
                mouse.previousSelection?.current !== undefined
5✔
2241
            ) {
143✔
2242
                if (fillHighlightRegion === undefined) return;
5!
2243
                const newRange = {
5✔
2244
                    ...gridSelection,
5✔
2245
                    current: {
5✔
2246
                        ...gridSelection.current,
5✔
2247
                        range: combineRects(mouse.previousSelection.current.range, fillHighlightRegion),
5✔
2248
                    },
5✔
2249
                };
5✔
2250
                void fillPattern(mouse.previousSelection, newRange);
5✔
2251
                setGridSelection(newRange, true);
5✔
2252
                return;
5✔
2253
            }
5✔
2254

137✔
2255
            const [col, row] = args.location;
137✔
2256
            const [lastMouseDownCol, lastMouseDownRow] = lastMouseSelectLocation.current ?? [];
143✔
2257

143✔
2258
            const preventDefault = () => {
143✔
2259
                isPrevented.current = true;
×
2260
            };
×
2261

143✔
2262
            const handleMaybeClick = (a: GridMouseCellEventArgs): boolean => {
143✔
2263
                const isValidClick = a.isTouch || (lastMouseDownCol === col && lastMouseDownRow === row);
112✔
2264
                if (isValidClick) {
112✔
2265
                    onCellClicked?.([col - rowMarkerOffset, row], {
102✔
2266
                        ...a,
4✔
2267
                        preventDefault,
4✔
2268
                    });
4✔
2269
                }
102✔
2270
                if (a.button === 1) return !isPrevented.current;
112✔
2271
                if (!isPrevented.current) {
109✔
2272
                    const c = getMangledCellContent(args.location);
109✔
2273
                    const r = getCellRenderer(c);
109✔
2274
                    if (r !== undefined && r.onClick !== undefined && isValidClick) {
109✔
2275
                        const newVal = r.onClick({
21✔
2276
                            ...a,
21✔
2277
                            cell: c,
21✔
2278
                            posX: a.localEventX,
21✔
2279
                            posY: a.localEventY,
21✔
2280
                            bounds: a.bounds,
21✔
2281
                            theme: themeForCell(c, args.location),
21✔
2282
                            preventDefault,
21✔
2283
                        });
21✔
2284
                        if (newVal !== undefined && !isInnerOnlyCell(newVal) && isEditableGridCell(newVal)) {
21✔
2285
                            mangledOnCellsEdited([{ location: a.location, value: newVal }]);
4✔
2286
                            gridRef.current?.damage([
4✔
2287
                                {
4✔
2288
                                    cell: a.location,
4✔
2289
                                },
4✔
2290
                            ]);
4✔
2291
                        }
4✔
2292
                    }
21✔
2293
                    if (isPrevented.current || gridSelection.current === undefined) return false;
109✔
2294

94✔
2295
                    let shouldActivate = false;
94✔
2296
                    switch (c.activationBehaviorOverride ?? cellActivationBehavior) {
109✔
2297
                        case "double-click":
109✔
2298
                        case "second-click": {
109✔
2299
                            if (mouse?.previousSelection?.current?.cell === undefined) break;
93✔
2300
                            const [selectedCol, selectedRow] = gridSelection.current.cell;
21✔
2301
                            const [prevCol, prevRow] = mouse.previousSelection.current.cell;
21✔
2302
                            const isClickOnSelected =
21✔
2303
                                col === selectedCol && col === prevCol && row === selectedRow && row === prevRow;
93✔
2304
                            shouldActivate =
93✔
2305
                                isClickOnSelected &&
93✔
2306
                                (a.isDoubleClick === true || cellActivationBehavior === "second-click");
6✔
2307
                            break;
93✔
2308
                        }
93✔
2309
                        case "single-click": {
109✔
2310
                            shouldActivate = true;
1✔
2311
                            break;
1✔
2312
                        }
1✔
2313
                    }
109✔
2314
                    if (shouldActivate) {
109✔
2315
                        onCellActivated?.([col - rowMarkerOffset, row]);
6✔
2316
                        reselect(a.bounds, false);
6✔
2317
                        return true;
6✔
2318
                    }
6✔
2319
                }
109✔
2320
                return false;
88✔
2321
            };
112✔
2322

143✔
2323
            const clickLocation = args.location[0] - rowMarkerOffset;
143✔
2324
            if (args.isTouch) {
143✔
2325
                const vr = visibleRegionRef.current;
4✔
2326
                const touchVr = touchDownArgs.current;
4✔
2327
                if (vr.x !== touchVr.x || vr.y !== touchVr.y) {
4!
2328
                    // we scrolled, abort
×
2329
                    return;
×
2330
                }
×
2331
                // take care of context menus first if long pressed item is already selected
4✔
2332
                if (args.isLongTouch === true) {
4!
2333
                    if (args.kind === "cell" && itemsAreEqual(gridSelection.current?.cell, args.location)) {
×
2334
                        onCellContextMenu?.([clickLocation, args.location[1]], {
×
2335
                            ...args,
×
2336
                            preventDefault,
×
2337
                        });
×
2338
                        return;
×
2339
                    } else if (args.kind === "header" && gridSelection.columns.hasIndex(col)) {
×
2340
                        onHeaderContextMenu?.(clickLocation, { ...args, preventDefault });
×
2341
                        return;
×
2342
                    } else if (args.kind === groupHeaderKind) {
×
2343
                        if (clickLocation < 0) {
×
2344
                            return;
×
2345
                        }
×
2346

×
2347
                        onGroupHeaderContextMenu?.(clickLocation, { ...args, preventDefault });
×
2348
                        return;
×
2349
                    }
×
2350
                }
×
2351
                if (args.kind === "cell") {
4✔
2352
                    // click that cell
2✔
2353
                    if (!handleMaybeClick(args)) {
2✔
2354
                        handleSelect(args);
2✔
2355
                    }
2✔
2356
                } else if (args.kind === groupHeaderKind) {
2✔
2357
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
1✔
2358
                } else {
1✔
2359
                    if (args.kind === headerKind) {
1✔
2360
                        onHeaderClicked?.(clickLocation, {
1✔
2361
                            ...args,
1✔
2362
                            preventDefault,
1✔
2363
                        });
1✔
2364
                    }
1✔
2365
                    handleSelect(args);
1✔
2366
                }
1✔
2367
                return;
4✔
2368
            }
4✔
2369

133✔
2370
            if (args.kind === "header") {
143✔
2371
                if (clickLocation < 0) {
16✔
2372
                    return;
3✔
2373
                }
3✔
2374

13✔
2375
                if (args.isEdge) {
16✔
2376
                    if (args.isDoubleClick === true) {
2✔
2377
                        void normalSizeColumn(col);
1✔
2378
                    }
1✔
2379
                } else if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
16✔
2380
                    onHeaderClicked?.(clickLocation, { ...args, preventDefault });
5✔
2381
                }
5✔
2382
            }
16✔
2383

130✔
2384
            if (args.kind === groupHeaderKind) {
143✔
2385
                if (clickLocation < 0) {
3!
2386
                    return;
×
2387
                }
×
2388

3✔
2389
                if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
3✔
2390
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
3!
2391
                    if (!isPrevented.current) {
3✔
2392
                        handleGroupHeaderSelection(args);
3✔
2393
                    }
3✔
2394
                }
3✔
2395
            }
3✔
2396

130✔
2397
            if (args.kind === "cell" && (args.button === 0 || args.button === 1)) {
143✔
2398
                handleMaybeClick(args);
110✔
2399
            }
110✔
2400

130✔
2401
            lastMouseSelectLocation.current = undefined;
130✔
2402
        },
143✔
2403
        [
728✔
2404
            mouseState,
728✔
2405
            gridSelection,
728✔
2406
            rowMarkerOffset,
728✔
2407
            fillHighlightRegion,
728✔
2408
            fillPattern,
728✔
2409
            setGridSelection,
728✔
2410
            onCellClicked,
728✔
2411
            getMangledCellContent,
728✔
2412
            getCellRenderer,
728✔
2413
            cellActivationBehavior,
728✔
2414
            themeForCell,
728✔
2415
            mangledOnCellsEdited,
728✔
2416
            onCellActivated,
728✔
2417
            reselect,
728✔
2418
            onCellContextMenu,
728✔
2419
            onHeaderContextMenu,
728✔
2420
            onGroupHeaderContextMenu,
728✔
2421
            handleSelect,
728✔
2422
            onGroupHeaderClicked,
728✔
2423
            onHeaderClicked,
728✔
2424
            normalSizeColumn,
728✔
2425
            handleGroupHeaderSelection,
728✔
2426
        ]
728✔
2427
    );
728✔
2428

728✔
2429
    const onMouseMoveImpl = React.useCallback(
728✔
2430
        (args: GridMouseEventArgs) => {
728✔
2431
            const a: GridMouseEventArgs = {
39✔
2432
                ...args,
39✔
2433
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
39✔
2434
            };
39✔
2435
            onMouseMove?.(a);
39✔
2436

39✔
2437
            if (mouseState !== undefined && args.buttons === 0) {
39✔
2438
                setMouseState(undefined);
6✔
2439
                setFillHighlightRegion(undefined);
6✔
2440
                setScrollDir(undefined);
6✔
2441
                isActivelyDraggingHeader.current = false;
6✔
2442
            }
6✔
2443

39✔
2444
            setScrollDir(cv => {
39✔
2445
                if (isActivelyDraggingHeader.current) return [args.scrollEdge[0], 0];
39✔
2446
                if (args.scrollEdge[0] === cv?.[0] && args.scrollEdge[1] === cv[1]) return cv;
39✔
2447
                return mouseState === undefined || (mouseDownData.current?.location[0] ?? 0) < rowMarkerOffset
39!
2448
                    ? undefined
13✔
2449
                    : args.scrollEdge;
16✔
2450
            });
39✔
2451
        },
39✔
2452
        [mouseState, onMouseMove, rowMarkerOffset]
728✔
2453
    );
728✔
2454

728✔
2455
    const onHeaderMenuClickInner = React.useCallback(
728✔
2456
        (col: number, screenPosition: Rectangle) => {
728✔
2457
            onHeaderMenuClick?.(col - rowMarkerOffset, screenPosition);
1✔
2458
        },
1✔
2459
        [onHeaderMenuClick, rowMarkerOffset]
728✔
2460
    );
728✔
2461

728✔
2462
    const onHeaderIndicatorClickInner = React.useCallback(
728✔
2463
        (col: number, screenPosition: Rectangle) => {
728✔
2464
            onHeaderIndicatorClick?.(col - rowMarkerOffset, screenPosition);
×
2465
        },
×
2466
        [onHeaderIndicatorClick, rowMarkerOffset]
728✔
2467
    );
728✔
2468

728✔
2469
    const currentCell = gridSelection?.current?.cell;
728✔
2470
    const onVisibleRegionChangedImpl = React.useCallback(
728✔
2471
        (
728✔
2472
            region: Rectangle,
152✔
2473
            clientWidth: number,
152✔
2474
            clientHeight: number,
152✔
2475
            rightElWidth: number,
152✔
2476
            tx: number,
152✔
2477
            ty: number
152✔
2478
        ) => {
152✔
2479
            hasJustScrolled.current = false;
152✔
2480
            let selected = currentCell;
152✔
2481
            if (selected !== undefined) {
152✔
2482
                selected = [selected[0] - rowMarkerOffset, selected[1]];
10✔
2483
            }
10✔
2484

152✔
2485
            const freezeRegion =
152✔
2486
                freezeColumns === 0
152✔
2487
                    ? undefined
151✔
2488
                    : {
1✔
2489
                          x: 0,
1✔
2490
                          y: region.y,
1✔
2491
                          width: freezeColumns,
1✔
2492
                          height: region.height,
1✔
2493
                      };
1✔
2494

152✔
2495
            const freezeRegions: Rectangle[] = [];
152✔
2496
            if (freezeRegion !== undefined) freezeRegions.push(freezeRegion);
152✔
2497
            if (freezeTrailingRows > 0) {
152✔
2498
                freezeRegions.push({
1✔
2499
                    x: region.x - rowMarkerOffset,
1✔
2500
                    y: rows - freezeTrailingRows,
1✔
2501
                    width: region.width,
1✔
2502
                    height: freezeTrailingRows,
1✔
2503
                });
1✔
2504

1✔
2505
                if (freezeColumns > 0) {
1✔
2506
                    freezeRegions.push({
1✔
2507
                        x: 0,
1✔
2508
                        y: rows - freezeTrailingRows,
1✔
2509
                        width: freezeColumns,
1✔
2510
                        height: freezeTrailingRows,
1✔
2511
                    });
1✔
2512
                }
1✔
2513
            }
1✔
2514

152✔
2515
            const newRegion = {
152✔
2516
                x: region.x - rowMarkerOffset,
152✔
2517
                y: region.y,
152✔
2518
                width: region.width,
152✔
2519
                height: showTrailingBlankRow && region.y + region.height >= rows ? region.height - 1 : region.height,
152✔
2520
                tx,
152✔
2521
                ty,
152✔
2522
                extras: {
152✔
2523
                    selected,
152✔
2524
                    freezeRegion,
152✔
2525
                    freezeRegions,
152✔
2526
                },
152✔
2527
            };
152✔
2528
            visibleRegionRef.current = newRegion;
152✔
2529
            setVisibleRegion(newRegion);
152✔
2530
            setClientSize([clientWidth, clientHeight, rightElWidth]);
152✔
2531
            onVisibleRegionChanged?.(newRegion, newRegion.tx, newRegion.ty, newRegion.extras);
152✔
2532
        },
152✔
2533
        [
728✔
2534
            currentCell,
728✔
2535
            rowMarkerOffset,
728✔
2536
            showTrailingBlankRow,
728✔
2537
            rows,
728✔
2538
            freezeColumns,
728✔
2539
            freezeTrailingRows,
728✔
2540
            setVisibleRegion,
728✔
2541
            onVisibleRegionChanged,
728✔
2542
        ]
728✔
2543
    );
728✔
2544

728✔
2545
    const onColumnProposeMoveImpl = whenDefined(
728✔
2546
        onColumnProposeMove,
728✔
2547
        React.useCallback(
728✔
2548
            (startIndex: number, endIndex: number) => {
728✔
NEW
2549
                return onColumnProposeMove?.(startIndex - rowMarkerOffset, endIndex - rowMarkerOffset) !== false;
×
NEW
2550
            },
×
2551
            [onColumnProposeMove, rowMarkerOffset]
728✔
2552
        )
728✔
2553
    );
728✔
2554

728✔
2555
    const onColumnMovedImpl = whenDefined(
728✔
2556
        onColumnMoved,
728✔
2557
        React.useCallback(
728✔
2558
            (startIndex: number, endIndex: number) => {
728✔
2559
                onColumnMoved?.(startIndex - rowMarkerOffset, endIndex - rowMarkerOffset);
1✔
2560
                if (columnSelect !== "none") {
1✔
2561
                    setSelectedColumns(CompactSelection.fromSingleSelection(endIndex), undefined, true);
1✔
2562
                }
1✔
2563
            },
1✔
2564
            [columnSelect, onColumnMoved, rowMarkerOffset, setSelectedColumns]
728✔
2565
        )
728✔
2566
    );
728✔
2567

728✔
2568
    const isActivelyDragging = React.useRef(false);
728✔
2569
    const onDragStartImpl = React.useCallback(
728✔
2570
        (args: GridDragEventArgs) => {
728✔
2571
            if (args.location[0] === 0 && rowMarkerOffset > 0) {
1!
2572
                args.preventDefault();
×
2573
                return;
×
2574
            }
×
2575
            onDragStart?.({
1✔
2576
                ...args,
1✔
2577
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
1✔
2578
            });
1✔
2579

1✔
2580
            if (!args.defaultPrevented()) {
1✔
2581
                isActivelyDragging.current = true;
1✔
2582
            }
1✔
2583
            setMouseState(undefined);
1✔
2584
        },
1✔
2585
        [onDragStart, rowMarkerOffset]
728✔
2586
    );
728✔
2587

728✔
2588
    const onDragEnd = React.useCallback(() => {
728✔
2589
        isActivelyDragging.current = false;
×
2590
    }, []);
728✔
2591

728✔
2592
    const rowGroupingSelectionBehavior = rowGrouping?.selectionBehavior;
728!
2593

728✔
2594
    const getSelectionRowLimits = React.useCallback(
728✔
2595
        (selectedRow: number): readonly [number, number] | undefined => {
728✔
2596
            if (rowGroupingSelectionBehavior !== "block-spanning") return undefined;
16!
2597

×
2598
            const { isGroupHeader, path, groupRows } = mapper(selectedRow);
×
2599

×
2600
            if (isGroupHeader) {
×
2601
                return [selectedRow, selectedRow];
×
2602
            }
×
2603

×
2604
            const groupRowIndex = path[path.length - 1];
×
2605
            const lowerBounds = selectedRow - groupRowIndex;
×
2606
            const upperBounds = selectedRow + groupRows - groupRowIndex - 1;
×
2607

×
2608
            return [lowerBounds, upperBounds];
×
2609
        },
16✔
2610
        [mapper, rowGroupingSelectionBehavior]
728✔
2611
    );
728✔
2612

728✔
2613
    const hoveredRef = React.useRef<GridMouseEventArgs>();
728✔
2614
    const onItemHoveredImpl = React.useCallback(
728✔
2615
        (args: GridMouseEventArgs) => {
728✔
2616
            // make sure we still have a button down
29✔
2617
            if (mouseEventArgsAreEqual(args, hoveredRef.current)) return;
29!
2618
            hoveredRef.current = args;
29✔
2619
            if (mouseDownData?.current?.button !== undefined && mouseDownData.current.button >= 1) return;
29✔
2620
            if (
28✔
2621
                args.buttons !== 0 &&
28✔
2622
                mouseState !== undefined &&
14✔
2623
                mouseDownData.current?.location[0] === 0 &&
14✔
2624
                args.location[0] === 0 &&
1✔
2625
                rowMarkerOffset === 1 &&
1✔
2626
                rowSelect === "multi" &&
1✔
2627
                mouseState.previousSelection &&
1✔
2628
                !mouseState.previousSelection.rows.hasIndex(mouseDownData.current.location[1]) &&
1✔
2629
                gridSelection.rows.hasIndex(mouseDownData.current.location[1])
1✔
2630
            ) {
29✔
2631
                const start = Math.min(mouseDownData.current.location[1], args.location[1]);
1✔
2632
                const end = Math.max(mouseDownData.current.location[1], args.location[1]) + 1;
1✔
2633
                setSelectedRows(CompactSelection.fromSingleSelection([start, end]), undefined, false);
1✔
2634
            }
1✔
2635
            if (
28✔
2636
                args.buttons !== 0 &&
28✔
2637
                mouseState !== undefined &&
14✔
2638
                gridSelection.current !== undefined &&
14✔
2639
                !isActivelyDragging.current &&
12✔
2640
                !isActivelyDraggingHeader.current &&
12✔
2641
                (rangeSelect === "rect" || rangeSelect === "multi-rect")
12!
2642
            ) {
29✔
2643
                const [selectedCol, selectedRow] = gridSelection.current.cell;
12✔
2644
                // eslint-disable-next-line prefer-const
12✔
2645
                let [col, row] = args.location;
12✔
2646

12✔
2647
                if (row < 0) {
12✔
2648
                    row = visibleRegionRef.current.y;
1✔
2649
                }
1✔
2650

12✔
2651
                if (mouseState.fillHandle === true && mouseState.previousSelection?.current !== undefined) {
12✔
2652
                    const prevRange = mouseState.previousSelection.current.range;
6✔
2653
                    row = Math.min(row, showTrailingBlankRow ? rows - 1 : rows);
6!
2654
                    const rect = getClosestRect(prevRange, col, row, allowedFillDirections);
6✔
2655
                    setFillHighlightRegion(rect);
6✔
2656
                } else {
6✔
2657
                    const startedFromLastStickyRow = showTrailingBlankRow && selectedRow === rows;
6✔
2658
                    if (startedFromLastStickyRow) return;
6!
2659

6✔
2660
                    const landedOnLastStickyRow = showTrailingBlankRow && row === rows;
6✔
2661
                    if (landedOnLastStickyRow) {
6!
2662
                        if (args.kind === outOfBoundsKind) row--;
×
2663
                        else return;
×
2664
                    }
×
2665

6✔
2666
                    col = Math.max(col, rowMarkerOffset);
6✔
2667
                    const clampLimits = getSelectionRowLimits(selectedRow);
6✔
2668
                    row = clampLimits === undefined ? row : clamp(row, clampLimits[0], clampLimits[1]);
6!
2669

6✔
2670
                    // FIXME: Restrict row based on rowGrouping.selectionBehavior here
6✔
2671

6✔
2672
                    const deltaX = col - selectedCol;
6✔
2673
                    const deltaY = row - selectedRow;
6✔
2674

6✔
2675
                    const newRange: Rectangle = {
6✔
2676
                        x: deltaX >= 0 ? selectedCol : col,
6!
2677
                        y: deltaY >= 0 ? selectedRow : row,
6✔
2678
                        width: Math.abs(deltaX) + 1,
6✔
2679
                        height: Math.abs(deltaY) + 1,
6✔
2680
                    };
6✔
2681

6✔
2682
                    setCurrent(
6✔
2683
                        {
6✔
2684
                            ...gridSelection.current,
6✔
2685
                            range: newRange,
6✔
2686
                        },
6✔
2687
                        true,
6✔
2688
                        false,
6✔
2689
                        "drag"
6✔
2690
                    );
6✔
2691
                }
6✔
2692
            }
12✔
2693

28✔
2694
            onItemHovered?.({ ...args, location: [args.location[0] - rowMarkerOffset, args.location[1]] as any });
29✔
2695
        },
29✔
2696
        [
728✔
2697
            mouseState,
728✔
2698
            rowMarkerOffset,
728✔
2699
            rowSelect,
728✔
2700
            gridSelection,
728✔
2701
            rangeSelect,
728✔
2702
            onItemHovered,
728✔
2703
            setSelectedRows,
728✔
2704
            showTrailingBlankRow,
728✔
2705
            rows,
728✔
2706
            allowedFillDirections,
728✔
2707
            getSelectionRowLimits,
728✔
2708
            setCurrent,
728✔
2709
        ]
728✔
2710
    );
728✔
2711

728✔
2712
    const adjustSelectionOnScroll = React.useCallback(() => {
728✔
2713
        const args = hoveredRef.current;
×
2714
        if (args === undefined) return;
×
2715
        const [xDir, yDir] = args.scrollEdge;
×
2716
        let [col, row] = args.location;
×
2717
        const visible = visibleRegionRef.current;
×
2718
        if (xDir === -1) {
×
2719
            col = visible.extras?.freezeRegion?.x ?? visible.x;
×
2720
        } else if (xDir === 1) {
×
2721
            col = visible.x + visible.width;
×
2722
        }
×
2723
        if (yDir === -1) {
×
2724
            row = Math.max(0, visible.y);
×
2725
        } else if (yDir === 1) {
×
2726
            row = Math.min(rows - 1, visible.y + visible.height);
×
2727
        }
×
2728
        col = clamp(col, 0, mangledCols.length - 1);
×
2729
        row = clamp(row, 0, rows - 1);
×
2730
        onItemHoveredImpl({
×
2731
            ...args,
×
2732
            location: [col, row] as any,
×
2733
        });
×
2734
    }, [mangledCols.length, onItemHoveredImpl, rows]);
728✔
2735

728✔
2736
    useAutoscroll(scrollDir, scrollRef, adjustSelectionOnScroll);
728✔
2737

728✔
2738
    // 1 === move one
728✔
2739
    // 2 === move to end
728✔
2740
    const adjustSelection = React.useCallback(
728✔
2741
        (direction: [0 | 1 | -1 | 2 | -2, 0 | 1 | -1 | 2 | -2]) => {
728✔
2742
            if (gridSelection.current === undefined) return;
10!
2743

10✔
2744
            const [x, y] = direction;
10✔
2745
            const [col, row] = gridSelection.current.cell;
10✔
2746
            const old = gridSelection.current.range;
10✔
2747
            let left = old.x;
10✔
2748
            let right = old.x + old.width;
10✔
2749
            let top = old.y;
10✔
2750
            let bottom = old.y + old.height;
10✔
2751

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

10✔
2755
            // take care of vertical first in case new spans come in
10✔
2756
            if (y !== 0) {
10✔
2757
                switch (y) {
4✔
2758
                    case 2: {
4✔
2759
                        // go to end
2✔
2760
                        bottom = maxRow;
2✔
2761
                        top = row;
2✔
2762
                        scrollTo(0, bottom, "vertical");
2✔
2763

2✔
2764
                        break;
2✔
2765
                    }
2✔
2766
                    case -2: {
4✔
2767
                        // go to start
1✔
2768
                        top = minRow;
1✔
2769
                        bottom = row + 1;
1✔
2770
                        scrollTo(0, top, "vertical");
1✔
2771

1✔
2772
                        break;
1✔
2773
                    }
1✔
2774
                    case 1: {
4✔
2775
                        // motion down
1✔
2776
                        if (top < row) {
1!
2777
                            top++;
×
2778
                            scrollTo(0, top, "vertical");
×
2779
                        } else {
1✔
2780
                            bottom = Math.min(maxRow, bottom + 1);
1✔
2781
                            scrollTo(0, bottom, "vertical");
1✔
2782
                        }
1✔
2783

1✔
2784
                        break;
1✔
2785
                    }
1✔
2786
                    case -1: {
4!
2787
                        // motion up
×
2788
                        if (bottom > row + 1) {
×
2789
                            bottom--;
×
2790
                            scrollTo(0, bottom, "vertical");
×
2791
                        } else {
×
2792
                            top = Math.max(minRow, top - 1);
×
2793
                            scrollTo(0, top, "vertical");
×
2794
                        }
×
2795

×
2796
                        break;
×
2797
                    }
×
2798
                    default: {
4!
2799
                        assertNever(y);
×
2800
                    }
×
2801
                }
4✔
2802
            }
4✔
2803

10✔
2804
            if (x !== 0) {
10✔
2805
                if (x === 2) {
8✔
2806
                    right = mangledCols.length;
2✔
2807
                    left = col;
2✔
2808
                    scrollTo(right - 1 - rowMarkerOffset, 0, "horizontal");
2✔
2809
                } else if (x === -2) {
8✔
2810
                    left = rowMarkerOffset;
1✔
2811
                    right = col + 1;
1✔
2812
                    scrollTo(left - rowMarkerOffset, 0, "horizontal");
1✔
2813
                } else {
6✔
2814
                    let disallowed: number[] = [];
5✔
2815
                    if (getCellsForSelection !== undefined) {
5✔
2816
                        const cells = getCellsForSelection(
5✔
2817
                            {
5✔
2818
                                x: left,
5✔
2819
                                y: top,
5✔
2820
                                width: right - left - rowMarkerOffset,
5✔
2821
                                height: bottom - top,
5✔
2822
                            },
5✔
2823
                            abortControllerRef.current.signal
5✔
2824
                        );
5✔
2825

5✔
2826
                        if (typeof cells === "object") {
5✔
2827
                            disallowed = getSpanStops(cells);
5✔
2828
                        }
5✔
2829
                    }
5✔
2830
                    if (x === 1) {
5✔
2831
                        // motion right
4✔
2832
                        let done = false;
4✔
2833
                        if (left < col) {
4!
2834
                            if (disallowed.length > 0) {
×
2835
                                const target = range(left + 1, col + 1).find(
×
2836
                                    n => !disallowed.includes(n - rowMarkerOffset)
×
2837
                                );
×
2838
                                if (target !== undefined) {
×
2839
                                    left = target;
×
2840
                                    done = true;
×
2841
                                }
×
2842
                            } else {
×
2843
                                left++;
×
2844
                                done = true;
×
2845
                            }
×
2846
                            if (done) scrollTo(left, 0, "horizontal");
×
2847
                        }
×
2848
                        if (!done) {
4✔
2849
                            right = Math.min(mangledCols.length, right + 1);
4✔
2850
                            scrollTo(right - 1 - rowMarkerOffset, 0, "horizontal");
4✔
2851
                        }
4✔
2852
                    } else if (x === -1) {
5✔
2853
                        // motion left
1✔
2854
                        let done = false;
1✔
2855
                        if (right > col + 1) {
1!
2856
                            if (disallowed.length > 0) {
×
2857
                                const target = range(right - 1, col, -1).find(
×
2858
                                    n => !disallowed.includes(n - rowMarkerOffset)
×
2859
                                );
×
2860
                                if (target !== undefined) {
×
2861
                                    right = target;
×
2862
                                    done = true;
×
2863
                                }
×
2864
                            } else {
×
2865
                                right--;
×
2866
                                done = true;
×
2867
                            }
×
2868
                            if (done) scrollTo(right - rowMarkerOffset, 0, "horizontal");
×
2869
                        }
×
2870
                        if (!done) {
1✔
2871
                            left = Math.max(rowMarkerOffset, left - 1);
1✔
2872
                            scrollTo(left - rowMarkerOffset, 0, "horizontal");
1✔
2873
                        }
1✔
2874
                    } else {
1!
2875
                        assertNever(x);
×
2876
                    }
×
2877
                }
5✔
2878
            }
8✔
2879

10✔
2880
            setCurrent(
10✔
2881
                {
10✔
2882
                    cell: gridSelection.current.cell,
10✔
2883
                    range: {
10✔
2884
                        x: left,
10✔
2885
                        y: top,
10✔
2886
                        width: right - left,
10✔
2887
                        height: bottom - top,
10✔
2888
                    },
10✔
2889
                },
10✔
2890
                true,
10✔
2891
                false,
10✔
2892
                "keyboard-select"
10✔
2893
            );
10✔
2894
        },
10✔
2895
        [
728✔
2896
            getCellsForSelection,
728✔
2897
            getSelectionRowLimits,
728✔
2898
            gridSelection,
728✔
2899
            mangledCols.length,
728✔
2900
            rowMarkerOffset,
728✔
2901
            rows,
728✔
2902
            scrollTo,
728✔
2903
            setCurrent,
728✔
2904
        ]
728✔
2905
    );
728✔
2906

728✔
2907
    const scrollToActiveCellRef = React.useRef(scrollToActiveCell);
728✔
2908
    scrollToActiveCellRef.current = scrollToActiveCell;
728✔
2909

728✔
2910
    const updateSelectedCell = React.useCallback(
728✔
2911
        (col: number, row: number, fromEditingTrailingRow: boolean, freeMove: boolean): boolean => {
728✔
2912
            const rowMax = mangledRows - (fromEditingTrailingRow ? 0 : 1);
67!
2913
            col = clamp(col, rowMarkerOffset, columns.length - 1 + rowMarkerOffset);
67✔
2914
            row = clamp(row, 0, rowMax);
67✔
2915

67✔
2916
            const curCol = currentCell?.[0];
67✔
2917
            const curRow = currentCell?.[1];
67✔
2918

67✔
2919
            if (col === curCol && row === curRow) return false;
67✔
2920
            if (freeMove && gridSelection.current !== undefined) {
67✔
2921
                const newStack = [...gridSelection.current.rangeStack];
1✔
2922
                if (gridSelection.current.range.width > 1 || gridSelection.current.range.height > 1) {
1!
2923
                    newStack.push(gridSelection.current.range);
1✔
2924
                }
1✔
2925
                setGridSelection(
1✔
2926
                    {
1✔
2927
                        ...gridSelection,
1✔
2928
                        current: {
1✔
2929
                            cell: [col, row],
1✔
2930
                            range: { x: col, y: row, width: 1, height: 1 },
1✔
2931
                            rangeStack: newStack,
1✔
2932
                        },
1✔
2933
                    },
1✔
2934
                    true
1✔
2935
                );
1✔
2936
            } else {
67✔
2937
                setCurrent(
29✔
2938
                    {
29✔
2939
                        cell: [col, row],
29✔
2940
                        range: { x: col, y: row, width: 1, height: 1 },
29✔
2941
                    },
29✔
2942
                    true,
29✔
2943
                    false,
29✔
2944
                    "keyboard-nav"
29✔
2945
                );
29✔
2946
            }
29✔
2947

30✔
2948
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
67✔
2949
                lastSent.current = undefined;
2✔
2950
            }
2✔
2951

30✔
2952
            if (scrollToActiveCellRef.current) {
30✔
2953
                scrollTo(col - rowMarkerOffset, row);
30✔
2954
            }
30✔
2955

30✔
2956
            return true;
30✔
2957
        },
67✔
2958
        [
728✔
2959
            mangledRows,
728✔
2960
            rowMarkerOffset,
728✔
2961
            columns.length,
728✔
2962
            currentCell,
728✔
2963
            gridSelection,
728✔
2964
            scrollTo,
728✔
2965
            setGridSelection,
728✔
2966
            setCurrent,
728✔
2967
        ]
728✔
2968
    );
728✔
2969

728✔
2970
    const onFinishEditing = React.useCallback(
728✔
2971
        (newValue: GridCell | undefined, movement: readonly [-1 | 0 | 1, -1 | 0 | 1]) => {
728✔
2972
            if (overlay?.cell !== undefined && newValue !== undefined && isEditableGridCell(newValue)) {
12✔
2973
                mangledOnCellsEdited([{ location: overlay.cell, value: newValue }]);
4✔
2974
                window.requestAnimationFrame(() => {
4✔
2975
                    gridRef.current?.damage([
4✔
2976
                        {
4✔
2977
                            cell: overlay.cell,
4✔
2978
                        },
4✔
2979
                    ]);
4✔
2980
                });
4✔
2981
            }
4✔
2982
            focus(true);
12✔
2983
            setOverlay(undefined);
12✔
2984

12✔
2985
            const [movX, movY] = movement;
12✔
2986
            if (gridSelection.current !== undefined && (movX !== 0 || movY !== 0)) {
12✔
2987
                const isEditingTrailingRow =
3✔
2988
                    gridSelection.current.cell[1] === mangledRows - 1 && newValue !== undefined;
3!
2989
                updateSelectedCell(
3✔
2990
                    clamp(gridSelection.current.cell[0] + movX, 0, mangledCols.length - 1),
3✔
2991
                    clamp(gridSelection.current.cell[1] + movY, 0, mangledRows - 1),
3✔
2992
                    isEditingTrailingRow,
3✔
2993
                    false
3✔
2994
                );
3✔
2995
            }
3✔
2996
            onFinishedEditing?.(newValue, movement);
12✔
2997
        },
12✔
2998
        [
728✔
2999
            overlay?.cell,
728✔
3000
            focus,
728✔
3001
            gridSelection,
728✔
3002
            onFinishedEditing,
728✔
3003
            mangledOnCellsEdited,
728✔
3004
            mangledRows,
728✔
3005
            updateSelectedCell,
728✔
3006
            mangledCols.length,
728✔
3007
        ]
728✔
3008
    );
728✔
3009

728✔
3010
    const overlayID = React.useMemo(() => {
728✔
3011
        return `gdg-overlay-${idCounter++}`;
148✔
3012
    }, []);
728✔
3013

728✔
3014
    const deleteRange = React.useCallback(
728✔
3015
        (r: Rectangle) => {
728✔
3016
            focus();
8✔
3017
            const editList: EditListItem[] = [];
8✔
3018
            for (let x = r.x; x < r.x + r.width; x++) {
8✔
3019
                for (let y = r.y; y < r.y + r.height; y++) {
23✔
3020
                    const cellValue = getCellContent([x - rowMarkerOffset, y]);
1,066✔
3021
                    if (!cellValue.allowOverlay && cellValue.kind !== GridCellKind.Boolean) continue;
1,066✔
3022
                    let newVal: InnerGridCell | undefined = undefined;
1,042✔
3023
                    if (cellValue.kind === GridCellKind.Custom) {
1,066✔
3024
                        const toDelete = getCellRenderer(cellValue);
1✔
3025
                        const editor = toDelete?.provideEditor?.(cellValue);
1!
3026
                        if (toDelete?.onDelete !== undefined) {
1✔
3027
                            newVal = toDelete.onDelete(cellValue);
1✔
3028
                        } else if (isObjectEditorCallbackResult(editor)) {
1!
3029
                            newVal = editor?.deletedValue?.(cellValue);
×
3030
                        }
×
3031
                    } else if (
1✔
3032
                        (isEditableGridCell(cellValue) && cellValue.allowOverlay) ||
1,041✔
3033
                        cellValue.kind === GridCellKind.Boolean
1✔
3034
                    ) {
1,041✔
3035
                        const toDelete = getCellRenderer(cellValue);
1,041✔
3036
                        newVal = toDelete?.onDelete?.(cellValue);
1,041✔
3037
                    }
1,041✔
3038
                    if (newVal !== undefined && !isInnerOnlyCell(newVal) && isEditableGridCell(newVal)) {
1,066✔
3039
                        editList.push({ location: [x, y], value: newVal });
1,041✔
3040
                    }
1,041✔
3041
                }
1,066✔
3042
            }
23✔
3043
            mangledOnCellsEdited(editList);
8✔
3044
            gridRef.current?.damage(editList.map(x => ({ cell: x.location })));
8✔
3045
        },
8✔
3046
        [focus, getCellContent, getCellRenderer, mangledOnCellsEdited, rowMarkerOffset]
728✔
3047
    );
728✔
3048

728✔
3049
    const overlayOpen = overlay !== undefined;
728✔
3050

728✔
3051
    const handleFixedKeybindings = React.useCallback(
728✔
3052
        (event: GridKeyEventArgs): boolean => {
728✔
3053
            const cancel = () => {
73✔
3054
                event.stopPropagation();
50✔
3055
                event.preventDefault();
50✔
3056
            };
50✔
3057

73✔
3058
            const details = {
73✔
3059
                didMatch: false,
73✔
3060
            };
73✔
3061

73✔
3062
            const { bounds } = event;
73✔
3063
            const selectedColumns = gridSelection.columns;
73✔
3064
            const selectedRows = gridSelection.rows;
73✔
3065

73✔
3066
            const keys = keybindings;
73✔
3067

73✔
3068
            if (!overlayOpen && isHotkey(keys.clear, event, details)) {
73✔
3069
                setGridSelection(emptyGridSelection, false);
2✔
3070
                onSelectionCleared?.();
2!
3071
            } else if (!overlayOpen && isHotkey(keys.selectAll, event, details)) {
73✔
3072
                setGridSelection(
1✔
3073
                    {
1✔
3074
                        columns: CompactSelection.empty(),
1✔
3075
                        rows: CompactSelection.empty(),
1✔
3076
                        current: {
1✔
3077
                            cell: gridSelection.current?.cell ?? [rowMarkerOffset, 0],
1!
3078
                            range: {
1✔
3079
                                x: rowMarkerOffset,
1✔
3080
                                y: 0,
1✔
3081
                                width: columnsIn.length,
1✔
3082
                                height: rows,
1✔
3083
                            },
1✔
3084
                            rangeStack: [],
1✔
3085
                        },
1✔
3086
                    },
1✔
3087
                    false
1✔
3088
                );
1✔
3089
            } else if (isHotkey(keys.search, event, details)) {
71!
3090
                searchInputRef?.current?.focus({ preventScroll: true });
×
3091
                setShowSearchInner(true);
×
3092
            } else if (isHotkey(keys.delete, event, details)) {
70✔
3093
                const callbackResult = onDelete?.(gridSelection) ?? true;
8✔
3094
                if (callbackResult !== false) {
8✔
3095
                    const toDelete = callbackResult === true ? gridSelection : callbackResult;
8✔
3096

8✔
3097
                    // delete order:
8✔
3098
                    // 1) primary range
8✔
3099
                    // 2) secondary ranges
8✔
3100
                    // 3) columns
8✔
3101
                    // 4) rows
8✔
3102

8✔
3103
                    if (toDelete.current !== undefined) {
8✔
3104
                        deleteRange(toDelete.current.range);
5✔
3105
                        for (const r of toDelete.current.rangeStack) {
5!
3106
                            deleteRange(r);
×
3107
                        }
×
3108
                    }
5✔
3109

8✔
3110
                    for (const r of toDelete.rows) {
8✔
3111
                        deleteRange({
1✔
3112
                            x: rowMarkerOffset,
1✔
3113
                            y: r,
1✔
3114
                            width: columnsIn.length,
1✔
3115
                            height: 1,
1✔
3116
                        });
1✔
3117
                    }
1✔
3118

8✔
3119
                    for (const col of toDelete.columns) {
8✔
3120
                        deleteRange({
1✔
3121
                            x: col,
1✔
3122
                            y: 0,
1✔
3123
                            width: 1,
1✔
3124
                            height: rows,
1✔
3125
                        });
1✔
3126
                    }
1✔
3127
                }
8✔
3128
            }
8✔
3129

73✔
3130
            if (details.didMatch) {
73✔
3131
                cancel();
11✔
3132
                return true;
11✔
3133
            }
11✔
3134

62✔
3135
            if (gridSelection.current === undefined) return false;
73✔
3136
            let [col, row] = gridSelection.current.cell;
59✔
3137
            const [, startRow] = gridSelection.current.cell;
59✔
3138
            let freeMove = false;
59✔
3139
            let cancelOnlyOnMove = false;
59✔
3140

59✔
3141
            if (isHotkey(keys.scrollToSelectedCell, event, details)) {
73!
3142
                scrollToRef.current(col - rowMarkerOffset, row);
×
3143
            } else if (columnSelect !== "none" && isHotkey(keys.selectColumn, event, details)) {
73✔
3144
                if (selectedColumns.hasIndex(col)) {
2!
3145
                    setSelectedColumns(selectedColumns.remove(col), undefined, true);
×
3146
                } else {
2✔
3147
                    if (columnSelect === "single") {
2!
3148
                        setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, true);
×
3149
                    } else {
2✔
3150
                        setSelectedColumns(undefined, col, true);
2✔
3151
                    }
2✔
3152
                }
2✔
3153
            } else if (rowSelect !== "none" && isHotkey(keys.selectRow, event, details)) {
59✔
3154
                if (selectedRows.hasIndex(row)) {
2!
3155
                    setSelectedRows(selectedRows.remove(row), undefined, true);
×
3156
                } else {
2✔
3157
                    if (rowSelect === "single") {
2!
3158
                        setSelectedRows(CompactSelection.fromSingleSelection(row), undefined, true);
×
3159
                    } else {
2✔
3160
                        setSelectedRows(undefined, row, true);
2✔
3161
                    }
2✔
3162
                }
2✔
3163
            } else if (!overlayOpen && bounds !== undefined && isHotkey(keys.activateCell, event, details)) {
57✔
3164
                if (row === rows && showTrailingBlankRow) {
7!
3165
                    window.setTimeout(() => {
×
3166
                        const customTargetColumn = getCustomNewRowTargetColumn(col);
×
3167
                        void appendRow(customTargetColumn ?? col);
×
3168
                    }, 0);
×
3169
                } else {
7✔
3170
                    onCellActivated?.([col - rowMarkerOffset, row]);
7✔
3171
                    reselect(bounds, true);
7✔
3172
                }
7✔
3173
            } else if (gridSelection.current.range.height > 1 && isHotkey(keys.downFill, event, details)) {
55✔
3174
                fillDown();
1✔
3175
            } else if (gridSelection.current.range.width > 1 && isHotkey(keys.rightFill, event, details)) {
48✔
3176
                fillRight();
1✔
3177
            } else if (isHotkey(keys.goToNextPage, event, details)) {
47✔
3178
                row += Math.max(1, visibleRegionRef.current.height - 4); // partial cell accounting
1✔
3179
            } else if (isHotkey(keys.goToPreviousPage, event, details)) {
46✔
3180
                row -= Math.max(1, visibleRegionRef.current.height - 4); // partial cell accounting
1✔
3181
            } else if (isHotkey(keys.goToFirstCell, event, details)) {
45✔
3182
                setOverlay(undefined);
1✔
3183
                row = 0;
1✔
3184
                col = 0;
1✔
3185
            } else if (isHotkey(keys.goToLastCell, event, details)) {
44✔
3186
                setOverlay(undefined);
1✔
3187
                row = Number.MAX_SAFE_INTEGER;
1✔
3188
                col = Number.MAX_SAFE_INTEGER;
1✔
3189
            } else if (isHotkey(keys.selectToFirstCell, event, details)) {
43✔
3190
                setOverlay(undefined);
1✔
3191
                adjustSelection([-2, -2]);
1✔
3192
            } else if (isHotkey(keys.selectToLastCell, event, details)) {
42✔
3193
                setOverlay(undefined);
1✔
3194
                adjustSelection([2, 2]);
1✔
3195
            } else if (!overlayOpen) {
41✔
3196
                if (isHotkey(keys.goDownCell, event, details)) {
36✔
3197
                    row += 1;
5✔
3198
                } else if (isHotkey(keys.goUpCell, event, details)) {
36✔
3199
                    row -= 1;
1✔
3200
                } else if (isHotkey(keys.goRightCell, event, details)) {
31✔
3201
                    col += 1;
2✔
3202
                } else if (isHotkey(keys.goLeftCell, event, details)) {
30✔
3203
                    col -= 1;
2✔
3204
                } else if (isHotkey(keys.goDownCellRetainSelection, event, details)) {
28!
3205
                    row += 1;
×
3206
                    freeMove = true;
×
3207
                } else if (isHotkey(keys.goUpCellRetainSelection, event, details)) {
26!
3208
                    row -= 1;
×
3209
                    freeMove = true;
×
3210
                } else if (isHotkey(keys.goRightCellRetainSelection, event, details)) {
26!
3211
                    col += 1;
×
3212
                    freeMove = true;
×
3213
                } else if (isHotkey(keys.goLeftCellRetainSelection, event, details)) {
26✔
3214
                    col -= 1;
1✔
3215
                    freeMove = true;
1✔
3216
                } else if (isHotkey(keys.goToLastRow, event, details)) {
26✔
3217
                    row = rows - 1;
1✔
3218
                } else if (isHotkey(keys.goToFirstRow, event, details)) {
25✔
3219
                    row = Number.MIN_SAFE_INTEGER;
1✔
3220
                } else if (isHotkey(keys.goToLastColumn, event, details)) {
24✔
3221
                    col = Number.MAX_SAFE_INTEGER;
2✔
3222
                } else if (isHotkey(keys.goToFirstColumn, event, details)) {
23✔
3223
                    col = Number.MIN_SAFE_INTEGER;
1✔
3224
                } else if (rangeSelect === "rect" || rangeSelect === "multi-rect") {
21!
3225
                    if (isHotkey(keys.selectGrowDown, event, details)) {
20✔
3226
                        adjustSelection([0, 1]);
1✔
3227
                    } else if (isHotkey(keys.selectGrowUp, event, details)) {
20!
3228
                        adjustSelection([0, -1]);
×
3229
                    } else if (isHotkey(keys.selectGrowRight, event, details)) {
19✔
3230
                        adjustSelection([1, 0]);
4✔
3231
                    } else if (isHotkey(keys.selectGrowLeft, event, details)) {
19✔
3232
                        adjustSelection([-1, 0]);
1✔
3233
                    } else if (isHotkey(keys.selectToLastRow, event, details)) {
15✔
3234
                        adjustSelection([0, 2]);
1✔
3235
                    } else if (isHotkey(keys.selectToFirstRow, event, details)) {
14!
3236
                        adjustSelection([0, -2]);
×
3237
                    } else if (isHotkey(keys.selectToLastColumn, event, details)) {
13✔
3238
                        adjustSelection([2, 0]);
1✔
3239
                    } else if (isHotkey(keys.selectToFirstColumn, event, details)) {
13!
3240
                        adjustSelection([-2, 0]);
×
3241
                    }
×
3242
                }
20✔
3243
                cancelOnlyOnMove = details.didMatch;
36✔
3244
            } else {
40✔
3245
                if (isHotkey(keys.closeOverlay, event, details)) {
4✔
3246
                    setOverlay(undefined);
2✔
3247
                }
2✔
3248

4✔
3249
                if (isHotkey(keys.acceptOverlayDown, event, details)) {
4✔
3250
                    setOverlay(undefined);
2✔
3251
                    row++;
2✔
3252
                }
2✔
3253

4✔
3254
                if (isHotkey(keys.acceptOverlayUp, event, details)) {
4!
3255
                    setOverlay(undefined);
×
3256
                    row--;
×
3257
                }
×
3258

4✔
3259
                if (isHotkey(keys.acceptOverlayLeft, event, details)) {
4!
3260
                    setOverlay(undefined);
×
3261
                    col--;
×
3262
                }
×
3263

4✔
3264
                if (isHotkey(keys.acceptOverlayRight, event, details)) {
4!
3265
                    setOverlay(undefined);
×
3266
                    col++;
×
3267
                }
×
3268
            }
4✔
3269
            // #endregion
59✔
3270

59✔
3271
            const mustRestrictRow = rowGroupingNavBehavior !== undefined && rowGroupingNavBehavior !== "normal";
73!
3272

73✔
3273
            if (mustRestrictRow && row !== startRow) {
73!
3274
                const skipUp =
×
3275
                    rowGroupingNavBehavior === "skip-up" ||
×
3276
                    rowGroupingNavBehavior === "skip" ||
×
3277
                    rowGroupingNavBehavior === "block";
×
3278
                const skipDown =
×
3279
                    rowGroupingNavBehavior === "skip-down" ||
×
3280
                    rowGroupingNavBehavior === "skip" ||
×
3281
                    rowGroupingNavBehavior === "block";
×
3282
                const didMoveUp = row < startRow;
×
3283
                if (didMoveUp && skipUp) {
×
3284
                    while (row >= 0 && mapper(row).isGroupHeader) {
×
3285
                        row--;
×
3286
                    }
×
3287

×
3288
                    if (row < 0) {
×
3289
                        row = startRow;
×
3290
                    }
×
3291
                } else if (!didMoveUp && skipDown) {
×
3292
                    while (row < rows && mapper(row).isGroupHeader) {
×
3293
                        row++;
×
3294
                    }
×
3295

×
3296
                    if (row >= rows) {
×
3297
                        row = startRow;
×
3298
                    }
×
3299
                }
×
3300
            }
✔
3301

59✔
3302
            const moved = updateSelectedCell(col, row, false, freeMove);
59✔
3303

59✔
3304
            const didMatch = details.didMatch;
59✔
3305

59✔
3306
            if (didMatch && (moved || !cancelOnlyOnMove || trapFocus)) {
73✔
3307
                cancel();
39✔
3308
            }
39✔
3309

59✔
3310
            return didMatch;
59✔
3311
        },
73✔
3312
        [
728✔
3313
            rowGroupingNavBehavior,
728✔
3314
            overlayOpen,
728✔
3315
            gridSelection,
728✔
3316
            keybindings,
728✔
3317
            columnSelect,
728✔
3318
            rowSelect,
728✔
3319
            rangeSelect,
728✔
3320
            rowMarkerOffset,
728✔
3321
            mapper,
728✔
3322
            rows,
728✔
3323
            updateSelectedCell,
728✔
3324
            setGridSelection,
728✔
3325
            onSelectionCleared,
728✔
3326
            columnsIn.length,
728✔
3327
            onDelete,
728✔
3328
            trapFocus,
728✔
3329
            deleteRange,
728✔
3330
            setSelectedColumns,
728✔
3331
            setSelectedRows,
728✔
3332
            showTrailingBlankRow,
728✔
3333
            getCustomNewRowTargetColumn,
728✔
3334
            appendRow,
728✔
3335
            onCellActivated,
728✔
3336
            reselect,
728✔
3337
            fillDown,
728✔
3338
            fillRight,
728✔
3339
            adjustSelection,
728✔
3340
        ]
728✔
3341
    );
728✔
3342

728✔
3343
    const onKeyDown = React.useCallback(
728✔
3344
        (event: GridKeyEventArgs) => {
728✔
3345
            let cancelled = false;
73✔
3346
            if (onKeyDownIn !== undefined) {
73✔
3347
                onKeyDownIn({
1✔
3348
                    ...event,
1✔
3349
                    ...(event.location && {
1✔
3350
                        location: [event.location[0] - rowMarkerOffset, event.location[1]] as any,
1✔
3351
                    }),
1✔
3352
                    cancel: () => {
1✔
3353
                        cancelled = true;
×
3354
                    },
×
3355
                });
1✔
3356
            }
1✔
3357

73✔
3358
            if (cancelled) return;
73!
3359

73✔
3360
            if (handleFixedKeybindings(event)) return;
73✔
3361

15✔
3362
            if (gridSelection.current === undefined) return;
15✔
3363
            const [col, row] = gridSelection.current.cell;
12✔
3364
            const vr = visibleRegionRef.current;
12✔
3365

12✔
3366
            if (
12✔
3367
                editOnType &&
12✔
3368
                !event.metaKey &&
12✔
3369
                !event.ctrlKey &&
12✔
3370
                gridSelection.current !== undefined &&
12✔
3371
                event.key.length === 1 &&
12✔
3372
                /[\p{L}\p{M}\p{N}\p{S}\p{P}]/u.test(event.key) &&
12✔
3373
                event.bounds !== undefined &&
12✔
3374
                isReadWriteCell(getCellContent([col - rowMarkerOffset, Math.max(0, Math.min(row, rows - 1))]))
12✔
3375
            ) {
73✔
3376
                if (
12✔
3377
                    (!showTrailingBlankRow || row !== rows) &&
12✔
3378
                    (vr.y > row || row > vr.y + vr.height || vr.x > col || col > vr.x + vr.width)
12✔
3379
                ) {
12!
3380
                    return;
×
3381
                }
×
3382
                reselect(event.bounds, true, event.key);
12✔
3383
                event.stopPropagation();
12✔
3384
                event.preventDefault();
12✔
3385
            }
12✔
3386
        },
73✔
3387
        [
728✔
3388
            editOnType,
728✔
3389
            onKeyDownIn,
728✔
3390
            handleFixedKeybindings,
728✔
3391
            gridSelection,
728✔
3392
            getCellContent,
728✔
3393
            rowMarkerOffset,
728✔
3394
            rows,
728✔
3395
            showTrailingBlankRow,
728✔
3396
            reselect,
728✔
3397
        ]
728✔
3398
    );
728✔
3399

728✔
3400
    const onContextMenu = React.useCallback(
728✔
3401
        (args: GridMouseEventArgs, preventDefault: () => void) => {
728✔
3402
            const adjustedCol = args.location[0] - rowMarkerOffset;
7✔
3403
            if (args.kind === "header") {
7!
3404
                onHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
3405
            }
×
3406

7✔
3407
            if (args.kind === groupHeaderKind) {
7!
3408
                if (adjustedCol < 0) {
×
3409
                    return;
×
3410
                }
×
3411
                onGroupHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
3412
            }
×
3413

7✔
3414
            if (args.kind === "cell") {
7✔
3415
                const [col, row] = args.location;
7✔
3416
                onCellContextMenu?.([adjustedCol, row], {
7✔
3417
                    ...args,
7✔
3418
                    preventDefault,
7✔
3419
                });
7✔
3420

7✔
3421
                if (!gridSelectionHasItem(gridSelection, args.location)) {
7✔
3422
                    updateSelectedCell(col, row, false, false);
3✔
3423
                }
3✔
3424
            }
7✔
3425
        },
7✔
3426
        [
728✔
3427
            gridSelection,
728✔
3428
            onCellContextMenu,
728✔
3429
            onGroupHeaderContextMenu,
728✔
3430
            onHeaderContextMenu,
728✔
3431
            rowMarkerOffset,
728✔
3432
            updateSelectedCell,
728✔
3433
        ]
728✔
3434
    );
728✔
3435

728✔
3436
    const onPasteInternal = React.useCallback(
728✔
3437
        async (e?: ClipboardEvent) => {
728✔
3438
            if (!keybindings.paste) return;
6!
3439
            function pasteToCell(
6✔
3440
                inner: InnerGridCell,
51✔
3441
                target: Item,
51✔
3442
                rawValue: string | boolean | string[] | number | boolean | BooleanEmpty | BooleanIndeterminate,
51✔
3443
                formatted?: string | string[]
51✔
3444
            ): EditListItem | undefined {
51✔
3445
                const stringifiedRawValue =
51✔
3446
                    typeof rawValue === "object" ? rawValue?.join("\n") ?? "" : rawValue?.toString() ?? "";
51!
3447

51✔
3448
                if (!isInnerOnlyCell(inner) && isReadWriteCell(inner) && inner.readonly !== true) {
51✔
3449
                    const coerced = coercePasteValue?.(stringifiedRawValue, inner);
51!
3450
                    if (coerced !== undefined && isEditableGridCell(coerced)) {
51!
3451
                        if (process.env.NODE_ENV !== "production" && coerced.kind !== inner.kind) {
×
3452
                            // eslint-disable-next-line no-console
×
3453
                            console.warn("Coercion should not change cell kind.");
×
3454
                        }
×
3455
                        return {
×
3456
                            location: target,
×
3457
                            value: coerced,
×
3458
                        };
×
3459
                    }
×
3460
                    const r = getCellRenderer(inner);
51✔
3461
                    if (r === undefined) return undefined;
51!
3462
                    if (r.kind === GridCellKind.Custom) {
51✔
3463
                        assert(inner.kind === GridCellKind.Custom);
1✔
3464
                        const newVal = (r as unknown as CustomRenderer<CustomCell<any>>).onPaste?.(
1✔
3465
                            stringifiedRawValue,
1✔
3466
                            inner.data
1✔
3467
                        );
1✔
3468
                        if (newVal === undefined) return undefined;
1!
3469
                        return {
×
3470
                            location: target,
×
3471
                            value: {
×
3472
                                ...inner,
×
3473
                                data: newVal,
×
3474
                            },
×
3475
                        };
×
3476
                    } else {
51✔
3477
                        const newVal = r.onPaste?.(stringifiedRawValue, inner, {
50✔
3478
                            formatted,
50✔
3479
                            formattedString: typeof formatted === "string" ? formatted : formatted?.join("\n"),
50!
3480
                            rawValue,
50✔
3481
                        });
50✔
3482
                        if (newVal === undefined) return undefined;
50✔
3483
                        assert(newVal.kind === inner.kind);
36✔
3484
                        return {
36✔
3485
                            location: target,
36✔
3486
                            value: newVal,
36✔
3487
                        };
36✔
3488
                    }
36✔
3489
                }
51!
3490
                return undefined;
×
3491
            }
51✔
3492

6✔
3493
            const selectedColumns = gridSelection.columns;
6✔
3494
            const selectedRows = gridSelection.rows;
6✔
3495
            const focused =
6✔
3496
                scrollRef.current?.contains(document.activeElement) === true ||
6✔
3497
                canvasRef.current?.contains(document.activeElement) === true;
6✔
3498

6✔
3499
            let target: Item | undefined;
6✔
3500

6✔
3501
            if (gridSelection.current !== undefined) {
6✔
3502
                target = [gridSelection.current.range.x, gridSelection.current.range.y];
5✔
3503
            } else if (selectedColumns.length === 1) {
6!
3504
                target = [selectedColumns.first() ?? 0, 0];
×
3505
            } else if (selectedRows.length === 1) {
1!
3506
                target = [rowMarkerOffset, selectedRows.first() ?? 0];
×
3507
            }
×
3508

6✔
3509
            if (focused && target !== undefined) {
6✔
3510
                let data: CopyBuffer | undefined;
5✔
3511
                let text: string | undefined;
5✔
3512

5✔
3513
                const textPlain = "text/plain";
5✔
3514
                const textHtml = "text/html";
5✔
3515

5✔
3516
                if (navigator.clipboard.read !== undefined) {
5!
3517
                    const clipboardContent = await navigator.clipboard.read();
×
3518

×
3519
                    for (const item of clipboardContent) {
×
3520
                        if (item.types.includes(textHtml)) {
×
3521
                            const htmlBlob = await item.getType(textHtml);
×
3522
                            const html = await htmlBlob.text();
×
3523
                            const decoded = decodeHTML(html);
×
3524
                            if (decoded !== undefined) {
×
3525
                                data = decoded;
×
3526
                                break;
×
3527
                            }
×
3528
                        }
×
3529
                        if (item.types.includes(textPlain)) {
×
3530
                            // eslint-disable-next-line unicorn/no-await-expression-member
×
3531
                            text = await (await item.getType(textPlain)).text();
×
3532
                        }
×
3533
                    }
×
3534
                } else if (navigator.clipboard.readText !== undefined) {
5✔
3535
                    text = await navigator.clipboard.readText();
5✔
3536
                } else if (e !== undefined && e?.clipboardData !== null) {
5!
3537
                    if (e.clipboardData.types.includes(textHtml)) {
×
3538
                        const html = e.clipboardData.getData(textHtml);
×
3539
                        data = decodeHTML(html);
×
3540
                    }
×
3541
                    if (data === undefined && e.clipboardData.types.includes(textPlain)) {
×
3542
                        text = e.clipboardData.getData(textPlain);
×
3543
                    }
×
3544
                } else {
×
3545
                    return; // I didn't want to read that paste value anyway
×
3546
                }
×
3547

5✔
3548
                const [targetCol, targetRow] = target;
5✔
3549

5✔
3550
                const editList: EditListItem[] = [];
5✔
3551
                do {
5✔
3552
                    if (onPaste === undefined) {
5✔
3553
                        const cellData = getMangledCellContent(target);
2✔
3554
                        const rawValue = text ?? data?.map(r => r.map(cb => cb.rawValue).join("\t")).join("\t") ?? "";
2!
3555
                        const newVal = pasteToCell(cellData, target, rawValue, undefined);
2✔
3556
                        if (newVal !== undefined) {
2✔
3557
                            editList.push(newVal);
1✔
3558
                        }
1✔
3559
                        break;
2✔
3560
                    }
2✔
3561

3✔
3562
                    if (data === undefined) {
3✔
3563
                        if (text === undefined) return;
3!
3564
                        data = unquote(text);
3✔
3565
                    }
3✔
3566

3✔
3567
                    if (
3✔
3568
                        onPaste === false ||
3✔
3569
                        (typeof onPaste === "function" &&
3✔
3570
                            onPaste?.(
2✔
3571
                                [target[0] - rowMarkerOffset, target[1]],
2✔
3572
                                data.map(r => r.map(cb => cb.rawValue?.toString() ?? ""))
2!
3573
                            ) !== true)
2✔
3574
                    ) {
5!
3575
                        return;
×
3576
                    }
✔
3577

3✔
3578
                    for (const [row, dataRow] of data.entries()) {
5✔
3579
                        if (row + targetRow >= rows) break;
21!
3580
                        for (const [col, dataItem] of dataRow.entries()) {
21✔
3581
                            const index = [col + targetCol, row + targetRow] as const;
63✔
3582
                            const [writeCol, writeRow] = index;
63✔
3583
                            if (writeCol >= mangledCols.length) continue;
63✔
3584
                            if (writeRow >= mangledRows) continue;
49!
3585
                            const cellData = getMangledCellContent(index);
49✔
3586
                            const newVal = pasteToCell(cellData, index, dataItem.rawValue, dataItem.formatted);
49✔
3587
                            if (newVal !== undefined) {
63✔
3588
                                editList.push(newVal);
35✔
3589
                            }
35✔
3590
                        }
63✔
3591
                    }
21✔
3592
                    // eslint-disable-next-line no-constant-condition
3✔
3593
                } while (false);
5✔
3594

5✔
3595
                mangledOnCellsEdited(editList);
5✔
3596

5✔
3597
                gridRef.current?.damage(
5✔
3598
                    editList.map(c => ({
5✔
3599
                        cell: c.location,
36✔
3600
                    }))
5✔
3601
                );
5✔
3602
            }
5✔
3603
        },
6✔
3604
        [
728✔
3605
            coercePasteValue,
728✔
3606
            getCellRenderer,
728✔
3607
            getMangledCellContent,
728✔
3608
            gridSelection,
728✔
3609
            keybindings.paste,
728✔
3610
            scrollRef,
728✔
3611
            mangledCols.length,
728✔
3612
            mangledOnCellsEdited,
728✔
3613
            mangledRows,
728✔
3614
            onPaste,
728✔
3615
            rowMarkerOffset,
728✔
3616
            rows,
728✔
3617
        ]
728✔
3618
    );
728✔
3619

728✔
3620
    useEventListener("paste", onPasteInternal, safeWindow, false, true);
728✔
3621

728✔
3622
    // While this function is async, we deeply prefer not to await if we don't have to. This will lead to unpacking
728✔
3623
    // promises in rather awkward ways when possible to avoid awaiting. We have to use fallback copy mechanisms when
728✔
3624
    // an await has happened.
728✔
3625
    const onCopy = React.useCallback(
728✔
3626
        async (e?: ClipboardEvent, ignoreFocus?: boolean) => {
728✔
3627
            if (!keybindings.copy) return;
6!
3628
            const focused =
6✔
3629
                ignoreFocus === true ||
6✔
3630
                scrollRef.current?.contains(document.activeElement) === true ||
5✔
3631
                canvasRef.current?.contains(document.activeElement) === true;
5✔
3632

6✔
3633
            const selectedColumns = gridSelection.columns;
6✔
3634
            const selectedRows = gridSelection.rows;
6✔
3635

6✔
3636
            const copyToClipboardWithHeaders = (
6✔
3637
                cells: readonly (readonly GridCell[])[],
5✔
3638
                columnIndexes: readonly number[]
5✔
3639
            ) => {
5✔
3640
                if (!copyHeaders) {
5✔
3641
                    copyToClipboard(cells, columnIndexes, e);
5✔
3642
                } else {
5!
3643
                    const headers = columnIndexes.map(index => ({
×
3644
                        kind: GridCellKind.Text,
×
3645
                        data: columnsIn[index].title,
×
3646
                        displayData: columnsIn[index].title,
×
3647
                        allowOverlay: false,
×
3648
                    })) as GridCell[];
×
3649
                    copyToClipboard([headers, ...cells], columnIndexes, e);
×
3650
                }
×
3651
            };
5✔
3652

6✔
3653
            if (focused && getCellsForSelection !== undefined) {
6✔
3654
                if (gridSelection.current !== undefined) {
6✔
3655
                    let thunk = getCellsForSelection(gridSelection.current.range, abortControllerRef.current.signal);
3✔
3656
                    if (typeof thunk !== "object") {
3!
3657
                        thunk = await thunk();
×
3658
                    }
×
3659
                    copyToClipboardWithHeaders(
3✔
3660
                        thunk,
3✔
3661
                        range(
3✔
3662
                            gridSelection.current.range.x - rowMarkerOffset,
3✔
3663
                            gridSelection.current.range.x + gridSelection.current.range.width - rowMarkerOffset
3✔
3664
                        )
3✔
3665
                    );
3✔
3666
                } else if (selectedRows !== undefined && selectedRows.length > 0) {
3✔
3667
                    const toCopy = [...selectedRows];
1✔
3668
                    const cells = toCopy.map(rowIndex => {
1✔
3669
                        const thunk = getCellsForSelection(
1✔
3670
                            {
1✔
3671
                                x: rowMarkerOffset,
1✔
3672
                                y: rowIndex,
1✔
3673
                                width: columnsIn.length,
1✔
3674
                                height: 1,
1✔
3675
                            },
1✔
3676
                            abortControllerRef.current.signal
1✔
3677
                        );
1✔
3678
                        if (typeof thunk === "object") {
1✔
3679
                            return thunk[0];
1✔
3680
                        }
1!
3681
                        return thunk().then(v => v[0]);
×
3682
                    });
1✔
3683
                    if (cells.some(x => x instanceof Promise)) {
1!
3684
                        const settled = await Promise.all(cells);
×
3685
                        copyToClipboardWithHeaders(settled, range(columnsIn.length));
×
3686
                    } else {
1✔
3687
                        copyToClipboardWithHeaders(cells as (readonly GridCell[])[], range(columnsIn.length));
1✔
3688
                    }
1✔
3689
                } else if (selectedColumns.length > 0) {
3✔
3690
                    const results: (readonly (readonly GridCell[])[])[] = [];
1✔
3691
                    const cols: number[] = [];
1✔
3692
                    for (const col of selectedColumns) {
1✔
3693
                        let thunk = getCellsForSelection(
3✔
3694
                            {
3✔
3695
                                x: col,
3✔
3696
                                y: 0,
3✔
3697
                                width: 1,
3✔
3698
                                height: rows,
3✔
3699
                            },
3✔
3700
                            abortControllerRef.current.signal
3✔
3701
                        );
3✔
3702
                        if (typeof thunk !== "object") {
3!
3703
                            thunk = await thunk();
×
3704
                        }
×
3705
                        results.push(thunk);
3✔
3706
                        cols.push(col - rowMarkerOffset);
3✔
3707
                    }
3✔
3708
                    if (results.length === 1) {
1!
3709
                        copyToClipboardWithHeaders(results[0], cols);
×
3710
                    } else {
1✔
3711
                        // FIXME: this is dumb
1✔
3712
                        const toCopy = results.reduce((pv, cv) => pv.map((row, index) => [...row, ...cv[index]]));
1✔
3713
                        copyToClipboardWithHeaders(toCopy, cols);
1✔
3714
                    }
1✔
3715
                }
1✔
3716
            }
6✔
3717
        },
6✔
3718
        [
728✔
3719
            columnsIn,
728✔
3720
            getCellsForSelection,
728✔
3721
            gridSelection,
728✔
3722
            keybindings.copy,
728✔
3723
            rowMarkerOffset,
728✔
3724
            scrollRef,
728✔
3725
            rows,
728✔
3726
            copyHeaders,
728✔
3727
        ]
728✔
3728
    );
728✔
3729

728✔
3730
    useEventListener("copy", onCopy, safeWindow, false, false);
728✔
3731

728✔
3732
    const onCut = React.useCallback(
728✔
3733
        async (e?: ClipboardEvent) => {
728✔
3734
            if (!keybindings.cut) return;
1!
3735
            const focused =
1✔
3736
                scrollRef.current?.contains(document.activeElement) === true ||
1✔
3737
                canvasRef.current?.contains(document.activeElement) === true;
1✔
3738

1✔
3739
            if (!focused) return;
1!
3740
            await onCopy(e);
1✔
3741
            if (gridSelection.current !== undefined) {
1✔
3742
                let effectiveSelection: GridSelection = {
1✔
3743
                    current: {
1✔
3744
                        cell: gridSelection.current.cell,
1✔
3745
                        range: gridSelection.current.range,
1✔
3746
                        rangeStack: [],
1✔
3747
                    },
1✔
3748
                    rows: CompactSelection.empty(),
1✔
3749
                    columns: CompactSelection.empty(),
1✔
3750
                };
1✔
3751
                const onDeleteResult = onDelete?.(effectiveSelection);
1✔
3752
                if (onDeleteResult === false) return;
1!
3753
                effectiveSelection = onDeleteResult === true ? effectiveSelection : onDeleteResult;
1!
3754
                if (effectiveSelection.current === undefined) return;
1!
3755
                deleteRange(effectiveSelection.current.range);
1✔
3756
            }
1✔
3757
        },
1✔
3758
        [deleteRange, gridSelection, keybindings.cut, onCopy, scrollRef, onDelete]
728✔
3759
    );
728✔
3760

728✔
3761
    useEventListener("cut", onCut, safeWindow, false, false);
728✔
3762

728✔
3763
    const onSearchResultsChanged = React.useCallback(
728✔
3764
        (results: readonly Item[], navIndex: number) => {
728✔
3765
            if (onSearchResultsChangedIn !== undefined) {
7!
3766
                if (rowMarkerOffset !== 0) {
×
3767
                    results = results.map(item => [item[0] - rowMarkerOffset, item[1]]);
×
3768
                }
×
3769
                onSearchResultsChangedIn(results, navIndex);
×
3770
                return;
×
3771
            }
×
3772
            if (results.length === 0 || navIndex === -1) return;
7✔
3773

2✔
3774
            const [col, row] = results[navIndex];
2✔
3775
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
7!
3776
                return;
×
3777
            }
✔
3778
            lastSent.current = [col, row];
2✔
3779
            updateSelectedCell(col, row, false, false);
2✔
3780
        },
7✔
3781
        [onSearchResultsChangedIn, rowMarkerOffset, updateSelectedCell]
728✔
3782
    );
728✔
3783

728✔
3784
    // this effects purpose in life is to scroll the newly selected cell into view when and ONLY when that cell
728✔
3785
    // is from an external gridSelection change. Also note we want the unmangled out selection because scrollTo
728✔
3786
    // expects unmangled indexes
728✔
3787
    const [outCol, outRow] = gridSelectionOuter?.current?.cell ?? [];
728✔
3788
    const scrollToRef = React.useRef(scrollTo);
728✔
3789
    scrollToRef.current = scrollTo;
728✔
3790
    React.useLayoutEffect(() => {
728✔
3791
        if (
232✔
3792
            scrollToActiveCellRef.current &&
232✔
3793
            !hasJustScrolled.current &&
232✔
3794
            outCol !== undefined &&
232✔
3795
            outRow !== undefined &&
88✔
3796
            (outCol !== expectedExternalGridSelection.current?.current?.cell[0] ||
88✔
3797
                outRow !== expectedExternalGridSelection.current?.current?.cell[1])
88✔
3798
        ) {
232!
3799
            scrollToRef.current(outCol, outRow);
×
3800
        }
×
3801
        hasJustScrolled.current = false; //only allow skipping a single scroll
232✔
3802
    }, [outCol, outRow]);
728✔
3803

728✔
3804
    const selectionOutOfBounds =
728✔
3805
        gridSelection.current !== undefined &&
728✔
3806
        (gridSelection.current.cell[0] >= mangledCols.length || gridSelection.current.cell[1] >= mangledRows);
360✔
3807
    React.useLayoutEffect(() => {
728✔
3808
        if (selectionOutOfBounds) {
154✔
3809
            setGridSelection(emptyGridSelection, false);
1✔
3810
        }
1✔
3811
    }, [selectionOutOfBounds, setGridSelection]);
728✔
3812

728✔
3813
    const disabledRows = React.useMemo(() => {
728✔
3814
        if (showTrailingBlankRow === true && trailingRowOptions?.tint === true) {
150✔
3815
            return CompactSelection.fromSingleSelection(mangledRows - 1);
147✔
3816
        }
147✔
3817
        return CompactSelection.empty();
3✔
3818
    }, [mangledRows, showTrailingBlankRow, trailingRowOptions?.tint]);
728✔
3819

728✔
3820
    const mangledVerticalBorder = React.useCallback(
728✔
3821
        (col: number) => {
728✔
3822
            return typeof verticalBorder === "boolean"
7,922!
3823
                ? verticalBorder
×
3824
                : verticalBorder?.(col - rowMarkerOffset) ?? true;
7,922!
3825
        },
7,922✔
3826
        [rowMarkerOffset, verticalBorder]
728✔
3827
    );
728✔
3828

728✔
3829
    const renameGroupNode = React.useMemo(() => {
728✔
3830
        if (renameGroup === undefined || canvasRef.current === null) return null;
151✔
3831
        const { bounds, group } = renameGroup;
2✔
3832
        const canvasBounds = canvasRef.current.getBoundingClientRect();
2✔
3833
        return (
2✔
3834
            <GroupRename
2✔
3835
                bounds={bounds}
2✔
3836
                group={group}
2✔
3837
                canvasBounds={canvasBounds}
2✔
3838
                onClose={() => setRenameGroup(undefined)}
2✔
3839
                onFinish={newVal => {
2✔
3840
                    setRenameGroup(undefined);
1✔
3841
                    onGroupHeaderRenamed?.(group, newVal);
1✔
3842
                }}
1✔
3843
            />
2✔
3844
        );
151✔
3845
    }, [onGroupHeaderRenamed, renameGroup]);
728✔
3846

728✔
3847
    const mangledFreezeColumns = Math.min(mangledCols.length, freezeColumns + (hasRowMarkers ? 1 : 0));
728✔
3848

728✔
3849
    React.useImperativeHandle(
728✔
3850
        forwardedRef,
728✔
3851
        () => ({
728✔
3852
            appendRow: (col: number, openOverlay?: boolean) => appendRow(col + rowMarkerOffset, openOverlay),
24✔
3853
            updateCells: damageList => {
24✔
3854
                if (rowMarkerOffset !== 0) {
2✔
3855
                    damageList = damageList.map(x => ({ cell: [x.cell[0] + rowMarkerOffset, x.cell[1]] }));
1✔
3856
                }
1✔
3857
                return gridRef.current?.damage(damageList);
2✔
3858
            },
2✔
3859
            getBounds: (col, row) => {
24✔
3860
                if (canvasRef?.current === null || scrollRef?.current === null) {
2!
3861
                    return undefined;
×
3862
                }
×
3863

2✔
3864
                if (col === undefined && row === undefined) {
2✔
3865
                    // Return the bounds of the entire scroll area:
1✔
3866
                    const rect = canvasRef.current.getBoundingClientRect();
1✔
3867
                    const scale = rect.width / scrollRef.current.clientWidth;
1✔
3868
                    return {
1✔
3869
                        x: rect.x - scrollRef.current.scrollLeft * scale,
1✔
3870
                        y: rect.y - scrollRef.current.scrollTop * scale,
1✔
3871
                        width: scrollRef.current.scrollWidth * scale,
1✔
3872
                        height: scrollRef.current.scrollHeight * scale,
1✔
3873
                    };
1✔
3874
                }
1✔
3875
                return gridRef.current?.getBounds((col ?? 0) + rowMarkerOffset, row);
2!
3876
            },
2✔
3877
            focus: () => gridRef.current?.focus(),
24✔
3878
            emit: async e => {
24✔
3879
                switch (e) {
5✔
3880
                    case "delete":
5✔
3881
                        onKeyDown({
1✔
3882
                            bounds: undefined,
1✔
3883
                            cancel: () => undefined,
1✔
3884
                            stopPropagation: () => undefined,
1✔
3885
                            preventDefault: () => undefined,
1✔
3886
                            ctrlKey: false,
1✔
3887
                            key: "Delete",
1✔
3888
                            keyCode: 46,
1✔
3889
                            metaKey: false,
1✔
3890
                            shiftKey: false,
1✔
3891
                            altKey: false,
1✔
3892
                            rawEvent: undefined,
1✔
3893
                            location: undefined,
1✔
3894
                        });
1✔
3895
                        break;
1✔
3896
                    case "fill-right":
5✔
3897
                        onKeyDown({
1✔
3898
                            bounds: undefined,
1✔
3899
                            cancel: () => undefined,
1✔
3900
                            stopPropagation: () => undefined,
1✔
3901
                            preventDefault: () => undefined,
1✔
3902
                            ctrlKey: true,
1✔
3903
                            key: "r",
1✔
3904
                            keyCode: 82,
1✔
3905
                            metaKey: false,
1✔
3906
                            shiftKey: false,
1✔
3907
                            altKey: false,
1✔
3908
                            rawEvent: undefined,
1✔
3909
                            location: undefined,
1✔
3910
                        });
1✔
3911
                        break;
1✔
3912
                    case "fill-down":
5✔
3913
                        onKeyDown({
1✔
3914
                            bounds: undefined,
1✔
3915
                            cancel: () => undefined,
1✔
3916
                            stopPropagation: () => undefined,
1✔
3917
                            preventDefault: () => undefined,
1✔
3918
                            ctrlKey: true,
1✔
3919
                            key: "d",
1✔
3920
                            keyCode: 68,
1✔
3921
                            metaKey: false,
1✔
3922
                            shiftKey: false,
1✔
3923
                            altKey: false,
1✔
3924
                            rawEvent: undefined,
1✔
3925
                            location: undefined,
1✔
3926
                        });
1✔
3927
                        break;
1✔
3928
                    case "copy":
5✔
3929
                        await onCopy(undefined, true);
1✔
3930
                        break;
1✔
3931
                    case "paste":
5✔
3932
                        await onPasteInternal();
1✔
3933
                        break;
1✔
3934
                }
5✔
3935
            },
5✔
3936
            scrollTo,
24✔
3937
            remeasureColumns: cols => {
24✔
3938
                for (const col of cols) {
1✔
3939
                    void normalSizeColumn(col + rowMarkerOffset);
1✔
3940
                }
1✔
3941
            },
1✔
3942
            getMouseArgsForPosition: (
24✔
NEW
3943
                posX: number,
×
NEW
3944
                posY: number,
×
NEW
3945
                ev?: MouseEvent | TouchEvent
×
NEW
3946
            ): GridMouseEventArgs | undefined => {
×
NEW
3947
                if (gridRef?.current === null) {
×
NEW
3948
                    return undefined;
×
NEW
3949
                }
×
NEW
3950

×
NEW
3951
                const args = gridRef.current.getMouseArgsForPosition(posX, posY, ev);
×
NEW
3952
                if (args === undefined) {
×
NEW
3953
                    return undefined;
×
NEW
3954
                }
×
NEW
3955

×
NEW
3956
                return {
×
NEW
3957
                    ...args,
×
NEW
3958
                    location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
×
NEW
3959
                };
×
NEW
3960
            },
×
3961
        }),
24✔
3962
        [appendRow, normalSizeColumn, scrollRef, onCopy, onKeyDown, onPasteInternal, rowMarkerOffset, scrollTo]
728✔
3963
    );
728✔
3964

728✔
3965
    const [selCol, selRow] = currentCell ?? [];
728✔
3966
    const onCellFocused = React.useCallback(
728✔
3967
        (cell: Item) => {
728✔
3968
            const [col, row] = cell;
29✔
3969

29✔
3970
            if (row === -1) {
29!
3971
                if (columnSelect !== "none") {
×
3972
                    setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, false);
×
3973
                    focus();
×
3974
                }
×
3975
                return;
×
3976
            }
×
3977

29✔
3978
            if (selCol === col && selRow === row) return;
29✔
3979
            setCurrent(
1✔
3980
                {
1✔
3981
                    cell,
1✔
3982
                    range: { x: col, y: row, width: 1, height: 1 },
1✔
3983
                },
1✔
3984
                true,
1✔
3985
                false,
1✔
3986
                "keyboard-nav"
1✔
3987
            );
1✔
3988
            scrollTo(col, row);
1✔
3989
        },
29✔
3990
        [columnSelect, focus, scrollTo, selCol, selRow, setCurrent, setSelectedColumns]
728✔
3991
    );
728✔
3992

728✔
3993
    const [isFocused, setIsFocused] = React.useState(false);
728✔
3994
    const setIsFocusedDebounced = React.useRef(
728✔
3995
        debounce((val: boolean) => {
728✔
3996
            setIsFocused(val);
56✔
3997
        }, 5)
728✔
3998
    );
728✔
3999

728✔
4000
    const onCanvasFocused = React.useCallback(() => {
728✔
4001
        setIsFocusedDebounced.current(true);
74✔
4002

74✔
4003
        // check for mouse state, don't do anything if the user is clicked to focus.
74✔
4004
        if (
74✔
4005
            gridSelection.current === undefined &&
74✔
4006
            gridSelection.columns.length === 0 &&
6✔
4007
            gridSelection.rows.length === 0 &&
5✔
4008
            mouseState === undefined
5✔
4009
        ) {
74✔
4010
            setCurrent(
5✔
4011
                {
5✔
4012
                    cell: [rowMarkerOffset, cellYOffset],
5✔
4013
                    range: {
5✔
4014
                        x: rowMarkerOffset,
5✔
4015
                        y: cellYOffset,
5✔
4016
                        width: 1,
5✔
4017
                        height: 1,
5✔
4018
                    },
5✔
4019
                },
5✔
4020
                true,
5✔
4021
                false,
5✔
4022
                "keyboard-select"
5✔
4023
            );
5✔
4024
        }
5✔
4025
    }, [cellYOffset, gridSelection, mouseState, rowMarkerOffset, setCurrent]);
728✔
4026

728✔
4027
    const onFocusOut = React.useCallback(() => {
728✔
4028
        setIsFocusedDebounced.current(false);
38✔
4029
    }, []);
728✔
4030

728✔
4031
    const [idealWidth, idealHeight] = React.useMemo(() => {
728✔
4032
        let h: number;
163✔
4033
        const scrollbarWidth = experimental?.scrollbarWidthOverride ?? getScrollBarWidth();
163✔
4034
        const rowsCountWithTrailingRow = rows + (showTrailingBlankRow ? 1 : 0);
163!
4035
        if (typeof rowHeight === "number") {
163✔
4036
            h = totalHeaderHeight + rowsCountWithTrailingRow * rowHeight;
162✔
4037
        } else {
163✔
4038
            let avg = 0;
1✔
4039
            const toAverage = Math.min(rowsCountWithTrailingRow, 10);
1✔
4040
            for (let i = 0; i < toAverage; i++) {
1✔
4041
                avg += rowHeight(i);
10✔
4042
            }
10✔
4043
            avg = Math.floor(avg / toAverage);
1✔
4044

1✔
4045
            h = totalHeaderHeight + rowsCountWithTrailingRow * avg;
1✔
4046
        }
1✔
4047
        h += scrollbarWidth;
163✔
4048

163✔
4049
        const w = mangledCols.reduce((acc, x) => x.width + acc, 0) + scrollbarWidth;
163✔
4050

163✔
4051
        // We need to set a reasonable cap here as some browsers will just ignore huge values
163✔
4052
        // rather than treat them as huge values.
163✔
4053
        return [`${Math.min(100_000, w)}px`, `${Math.min(100_000, h)}px`];
163✔
4054
    }, [mangledCols, experimental?.scrollbarWidthOverride, rowHeight, rows, showTrailingBlankRow, totalHeaderHeight]);
728✔
4055

728✔
4056
    const cssStyle = React.useMemo(() => {
728✔
4057
        return makeCSSStyle(mergedTheme);
148✔
4058
    }, [mergedTheme]);
728✔
4059

728✔
4060
    return (
728✔
4061
        <ThemeContext.Provider value={mergedTheme}>
728✔
4062
            <DataEditorContainer
728✔
4063
                style={cssStyle}
728✔
4064
                className={className}
728✔
4065
                inWidth={width ?? idealWidth}
728✔
4066
                inHeight={height ?? idealHeight}>
728✔
4067
                <DataGridSearch
728✔
4068
                    fillHandle={fillHandle}
728✔
4069
                    drawFocusRing={drawFocusRing}
728✔
4070
                    experimental={experimental}
728✔
4071
                    fixedShadowX={fixedShadowX}
728✔
4072
                    fixedShadowY={fixedShadowY}
728✔
4073
                    getRowThemeOverride={getRowThemeOverride}
728✔
4074
                    headerIcons={headerIcons}
728✔
4075
                    imageWindowLoader={imageWindowLoader}
728✔
4076
                    initialSize={initialSize}
728✔
4077
                    isDraggable={isDraggable}
728✔
4078
                    onDragLeave={onDragLeave}
728✔
4079
                    onRowMoved={onRowMoved}
728✔
4080
                    overscrollX={overscrollX}
728✔
4081
                    overscrollY={overscrollY}
728✔
4082
                    preventDiagonalScrolling={preventDiagonalScrolling}
728✔
4083
                    rightElement={rightElement}
728✔
4084
                    rightElementProps={rightElementProps}
728✔
4085
                    smoothScrollX={smoothScrollX}
728✔
4086
                    smoothScrollY={smoothScrollY}
728✔
4087
                    className={className}
728✔
4088
                    enableGroups={enableGroups}
728✔
4089
                    onCanvasFocused={onCanvasFocused}
728✔
4090
                    onCanvasBlur={onFocusOut}
728✔
4091
                    canvasRef={canvasRef}
728✔
4092
                    onContextMenu={onContextMenu}
728✔
4093
                    theme={mergedTheme}
728✔
4094
                    cellXOffset={cellXOffset}
728✔
4095
                    cellYOffset={cellYOffset}
728✔
4096
                    accessibilityHeight={visibleRegion.height}
728✔
4097
                    onDragEnd={onDragEnd}
728✔
4098
                    columns={mangledCols}
728✔
4099
                    nonGrowWidth={nonGrowWidth}
728✔
4100
                    drawHeader={drawHeader}
728✔
4101
                    onColumnProposeMove={onColumnProposeMoveImpl}
728✔
4102
                    drawCell={drawCell}
728✔
4103
                    disabledRows={disabledRows}
728✔
4104
                    freezeColumns={mangledFreezeColumns}
728✔
4105
                    lockColumns={rowMarkerOffset}
728✔
4106
                    firstColAccessible={rowMarkerOffset === 0}
728✔
4107
                    getCellContent={getMangledCellContent}
728✔
4108
                    minColumnWidth={minColumnWidth}
728✔
4109
                    maxColumnWidth={maxColumnWidth}
728✔
4110
                    searchInputRef={searchInputRef}
728✔
4111
                    showSearch={showSearch}
728✔
4112
                    onSearchClose={onSearchClose}
728✔
4113
                    highlightRegions={highlightRegions}
728✔
4114
                    getCellsForSelection={getCellsForSelection}
728✔
4115
                    getGroupDetails={mangledGetGroupDetails}
728✔
4116
                    headerHeight={headerHeight}
728✔
4117
                    isFocused={isFocused}
728✔
4118
                    groupHeaderHeight={enableGroups ? groupHeaderHeight : 0}
728✔
4119
                    freezeTrailingRows={
728✔
4120
                        freezeTrailingRows + (showTrailingBlankRow && trailingRowOptions?.sticky === true ? 1 : 0)
728!
4121
                    }
728✔
4122
                    hasAppendRow={showTrailingBlankRow}
728✔
4123
                    onColumnResize={onColumnResize}
728✔
4124
                    onColumnResizeEnd={onColumnResizeEnd}
728✔
4125
                    onColumnResizeStart={onColumnResizeStart}
728✔
4126
                    onCellFocused={onCellFocused}
728✔
4127
                    onColumnMoved={onColumnMovedImpl}
728✔
4128
                    onDragStart={onDragStartImpl}
728✔
4129
                    onHeaderMenuClick={onHeaderMenuClickInner}
728✔
4130
                    onHeaderIndicatorClick={onHeaderIndicatorClickInner}
728✔
4131
                    onItemHovered={onItemHoveredImpl}
728✔
4132
                    isFilling={mouseState?.fillHandle === true}
728✔
4133
                    onMouseMove={onMouseMoveImpl}
728✔
4134
                    onKeyDown={onKeyDown}
728✔
4135
                    onKeyUp={onKeyUpIn}
728✔
4136
                    onMouseDown={onMouseDown}
728✔
4137
                    onMouseUp={onMouseUp}
728✔
4138
                    onDragOverCell={onDragOverCell}
728✔
4139
                    onDrop={onDrop}
728✔
4140
                    onSearchResultsChanged={onSearchResultsChanged}
728✔
4141
                    onVisibleRegionChanged={onVisibleRegionChangedImpl}
728✔
4142
                    clientSize={clientSize}
728✔
4143
                    rowHeight={rowHeight}
728✔
4144
                    searchResults={searchResults}
728✔
4145
                    searchValue={searchValue}
728✔
4146
                    onSearchValueChange={onSearchValueChange}
728✔
4147
                    rows={mangledRows}
728✔
4148
                    scrollRef={scrollRef}
728✔
4149
                    selection={gridSelection}
728✔
4150
                    translateX={visibleRegion.tx}
728✔
4151
                    translateY={visibleRegion.ty}
728✔
4152
                    verticalBorder={mangledVerticalBorder}
728✔
4153
                    gridRef={gridRef}
728✔
4154
                    getCellRenderer={getCellRenderer}
728✔
4155
                    resizeIndicator={resizeIndicator}
728✔
4156
                />
728✔
4157
                {renameGroupNode}
728✔
4158
                {overlay !== undefined && (
728✔
4159
                    <React.Suspense fallback={null}>
35✔
4160
                        <DataGridOverlayEditor
35✔
4161
                            {...overlay}
35✔
4162
                            validateCell={validateCell}
35✔
4163
                            bloom={editorBloom}
35✔
4164
                            id={overlayID}
35✔
4165
                            getCellRenderer={getCellRenderer}
35✔
4166
                            className={experimental?.isSubGrid === true ? "click-outside-ignore" : undefined}
35!
4167
                            provideEditor={provideEditor}
35✔
4168
                            imageEditorOverride={imageEditorOverride}
35✔
4169
                            onFinishEditing={onFinishEditing}
35✔
4170
                            markdownDivCreateNode={markdownDivCreateNode}
35✔
4171
                            isOutsideClick={isOutsideClick}
35✔
4172
                            customEventTarget={experimental?.eventTarget}
35✔
4173
                        />
35✔
4174
                    </React.Suspense>
35✔
4175
                )}
728✔
4176
            </DataEditorContainer>
728✔
4177
        </ThemeContext.Provider>
728✔
4178
    );
728✔
4179
};
728✔
4180

1✔
4181
/**
1✔
4182
 * The primary component of Glide Data Grid.
1✔
4183
 * @category DataEditor
1✔
4184
 * @param {DataEditorProps} props
1✔
4185
 */
1✔
4186
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