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

glideapps / glide-data-grid / 15915234310

27 Jun 2025 12:23AM UTC coverage: 91.123% (-0.05%) from 91.171%
15915234310

Pull #1062

github

web-flow
Merge 3acddb101 into 3041b6f44
Pull Request #1062: feat: onRowAppended and onColumnAppended

2959 of 3656 branches covered (80.94%)

79 of 96 new or added lines in 2 files covered. (82.29%)

88 existing lines in 1 file now uncovered.

18026 of 19782 relevant lines covered (91.12%)

3148.41 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
747
const loadingCell: GridCell = {
1✔
748
    kind: GridCellKind.Loading,
1✔
749
    allowOverlay: false,
1✔
750
};
1✔
751

1✔
752
export const emptyGridSelection: GridSelection = {
1✔
753
    columns: CompactSelection.empty(),
1✔
754
    rows: CompactSelection.empty(),
1✔
755
    current: undefined,
1✔
756
};
1✔
757

1✔
758
const DataEditorImpl: React.ForwardRefRenderFunction<DataEditorRef, DataEditorProps> = (p, forwardedRef) => {
1✔
759
    const [gridSelectionInner, setGridSelectionInner] = React.useState<GridSelection>(emptyGridSelection);
742✔
760

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

742✔
775
    const safeWindow = typeof window === "undefined" ? null : window;
742!
776

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

742✔
891
    const drawFocusRing = drawFocusRingIn === "no-editor" ? overlay === undefined : drawFocusRingIn;
742!
892

742✔
893
    const rowMarkersObj = typeof p.rowMarkers === "string" ? undefined : p.rowMarkers;
742✔
894

742✔
895
    const rowMarkers = rowMarkersObj?.kind ?? (p.rowMarkers as RowMarkerOptions["kind"]) ?? "none";
742!
896
    const rowMarkerWidthRaw = rowMarkersObj?.width ?? p.rowMarkerWidth;
742!
897
    const rowMarkerStartIndex = rowMarkersObj?.startIndex ?? p.rowMarkerStartIndex ?? 1;
742!
898
    const rowMarkerTheme = rowMarkersObj?.theme ?? p.rowMarkerTheme;
742!
899
    const headerRowMarkerTheme = rowMarkersObj?.headerTheme;
742!
900
    const headerRowMarkerAlwaysVisible = rowMarkersObj?.headerAlwaysVisible;
742!
901
    const headerRowMarkerDisabled = rowSelect !== "multi" || rowMarkersObj?.headerDisabled === true;
742!
902
    const rowMarkerCheckboxStyle = rowMarkersObj?.checkboxStyle ?? "square";
742!
903

742✔
904
    const minColumnWidth = Math.max(minColumnWidthIn, 20);
742✔
905
    const maxColumnWidth = Math.max(maxColumnWidthIn, minColumnWidth);
742✔
906
    const maxColumnAutoWidth = Math.max(maxColumnAutoWidthIn ?? maxColumnWidth, minColumnWidth);
742✔
907

742✔
908
    const docStyle = React.useMemo(() => {
742✔
909
        if (typeof window === "undefined") return { fontSize: "16px" };
151!
910
        return window.getComputedStyle(document.documentElement);
151✔
911
    }, []);
742✔
912

742✔
913
    const {
742✔
914
        rows,
742✔
915
        rowNumberMapper,
742✔
916
        rowHeight: rowHeightPostGrouping,
742✔
917
        getRowThemeOverride,
742✔
918
    } = useRowGroupingInner(rowGrouping, rowsIn, rowHeightIn, getRowThemeOverrideIn);
742✔
919

742✔
920
    const remSize = React.useMemo(() => Number.parseFloat(docStyle.fontSize), [docStyle]);
742✔
921
    const { rowHeight, headerHeight, groupHeaderHeight, theme, overscrollX, overscrollY } = useRemAdjuster({
742✔
922
        groupHeaderHeight: groupHeaderHeightIn,
742✔
923
        headerHeight: headerHeightIn,
742✔
924
        overscrollX: overscrollXIn,
742✔
925
        overscrollY: overscrollYIn,
742✔
926
        remSize,
742✔
927
        rowHeight: rowHeightPostGrouping,
742✔
928
        scaleToRem,
742✔
929
        theme: themeIn,
742✔
930
    });
742✔
931

742✔
932
    const keybindings = useKeybindingsWithDefaults(keybindingsIn);
742✔
933

742✔
934
    const rowMarkerWidth = rowMarkerWidthRaw ?? (rowsIn > 10_000 ? 48 : rowsIn > 1000 ? 44 : rowsIn > 100 ? 36 : 32);
742!
935
    const hasRowMarkers = rowMarkers !== "none";
742✔
936
    const rowMarkerOffset = hasRowMarkers ? 1 : 0;
742✔
937
    const showTrailingBlankRow = trailingRowOptions !== undefined;
742✔
938
    const lastRowSticky = trailingRowOptions?.sticky === true;
742✔
939

742✔
940
    const [showSearchInner, setShowSearchInner] = React.useState(false);
742✔
941
    const showSearch = showSearchIn ?? showSearchInner;
742✔
942

742✔
943
    const onSearchClose = React.useCallback(() => {
742✔
944
        if (onSearchCloseIn !== undefined) {
2✔
945
            onSearchCloseIn();
2✔
946
        } else {
2!
947
            setShowSearchInner(false);
×
948
        }
×
949
    }, [onSearchCloseIn]);
742✔
950

742✔
951
    const gridSelectionOuterMangled: GridSelection | undefined = React.useMemo((): GridSelection | undefined => {
742✔
952
        return gridSelectionOuter === undefined ? undefined : shiftSelection(gridSelectionOuter, rowMarkerOffset);
291✔
953
    }, [gridSelectionOuter, rowMarkerOffset]);
742✔
954
    const gridSelection = gridSelectionOuterMangled ?? gridSelectionInner;
742✔
955

742✔
956
    const abortControllerRef = React.useRef() as React.MutableRefObject<AbortController>;
742✔
957
    if (abortControllerRef.current === undefined) abortControllerRef.current = new AbortController();
742✔
958

742✔
959
    React.useEffect(() => () => abortControllerRef?.current.abort(), []);
742✔
960

742✔
961
    const [getCellsForSelection, getCellsForSeletionDirect] = useCellsForSelection(
742✔
962
        getCellsForSelectionIn,
742✔
963
        getCellContent,
742✔
964
        rowMarkerOffset,
742✔
965
        abortControllerRef.current,
742✔
966
        rows
742✔
967
    );
742✔
968

742✔
969
    const validateCell = React.useCallback<NonNullable<typeof validateCellIn>>(
742✔
970
        (cell, newValue, prevValue) => {
742✔
971
            if (validateCellIn === undefined) return true;
17✔
972
            const item: Item = [cell[0] - rowMarkerOffset, cell[1]];
1✔
973
            return validateCellIn?.(item, newValue, prevValue);
1✔
974
        },
17✔
975
        [rowMarkerOffset, validateCellIn]
742✔
976
    );
742✔
977

742✔
978
    const expectedExternalGridSelection = React.useRef<GridSelection | undefined>(gridSelectionOuter);
742✔
979
    const setGridSelection = React.useCallback(
742✔
980
        (newVal: GridSelection, expand: boolean): void => {
742✔
981
            if (expand) {
185✔
982
                newVal = expandSelection(
142✔
983
                    newVal,
142✔
984
                    getCellsForSelection,
142✔
985
                    rowMarkerOffset,
142✔
986
                    spanRangeBehavior,
142✔
987
                    abortControllerRef.current
142✔
988
                );
142✔
989
            }
142✔
990
            if (onGridSelectionChange !== undefined) {
185✔
991
                expectedExternalGridSelection.current = shiftSelection(newVal, -rowMarkerOffset);
144✔
992
                onGridSelectionChange(expectedExternalGridSelection.current);
144✔
993
            } else {
185✔
994
                setGridSelectionInner(newVal);
41✔
995
            }
41✔
996
        },
185✔
997
        [onGridSelectionChange, getCellsForSelection, rowMarkerOffset, spanRangeBehavior]
742✔
998
    );
742✔
999

742✔
1000
    const onColumnResize = whenDefined(
742✔
1001
        onColumnResizeIn,
742✔
1002
        React.useCallback<NonNullable<typeof onColumnResizeIn>>(
742✔
1003
            (_, w, ind, wg) => {
742✔
1004
                onColumnResizeIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
11✔
1005
            },
11✔
1006
            [onColumnResizeIn, rowMarkerOffset, columnsIn]
742✔
1007
        )
742✔
1008
    );
742✔
1009

742✔
1010
    const onColumnResizeEnd = whenDefined(
742✔
1011
        onColumnResizeEndIn,
742✔
1012
        React.useCallback<NonNullable<typeof onColumnResizeEndIn>>(
742✔
1013
            (_, w, ind, wg) => {
742✔
1014
                onColumnResizeEndIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
2✔
1015
            },
2✔
1016
            [onColumnResizeEndIn, rowMarkerOffset, columnsIn]
742✔
1017
        )
742✔
1018
    );
742✔
1019

742✔
1020
    const onColumnResizeStart = whenDefined(
742✔
1021
        onColumnResizeStartIn,
742✔
1022
        React.useCallback<NonNullable<typeof onColumnResizeStartIn>>(
742✔
1023
            (_, w, ind, wg) => {
742✔
1024
                onColumnResizeStartIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
×
1025
            },
×
1026
            [onColumnResizeStartIn, rowMarkerOffset, columnsIn]
742✔
1027
        )
742✔
1028
    );
742✔
1029

742✔
1030
    const drawHeader = whenDefined(
742✔
1031
        drawHeaderIn,
742✔
1032
        React.useCallback<NonNullable<typeof drawHeaderIn>>(
742✔
1033
            (args, draw) => {
742✔
1034
                return drawHeaderIn?.({ ...args, columnIndex: args.columnIndex - rowMarkerOffset }, draw) ?? false;
×
1035
            },
×
1036
            [drawHeaderIn, rowMarkerOffset]
742✔
1037
        )
742✔
1038
    );
742✔
1039

742✔
1040
    const drawCell = whenDefined(
742✔
1041
        drawCellIn,
742✔
1042
        React.useCallback<NonNullable<typeof drawCellIn>>(
742✔
1043
            (args, draw) => {
742✔
1044
                return drawCellIn?.({ ...args, col: args.col - rowMarkerOffset }, draw) ?? false;
×
1045
            },
×
1046
            [drawCellIn, rowMarkerOffset]
742✔
1047
        )
742✔
1048
    );
742✔
1049

742✔
1050
    const onDelete = React.useCallback<NonNullable<DataEditorProps["onDelete"]>>(
742✔
1051
        sel => {
742✔
1052
            if (onDeleteIn !== undefined) {
9✔
1053
                const result = onDeleteIn(shiftSelection(sel, -rowMarkerOffset));
5✔
1054
                if (typeof result === "boolean") {
5!
1055
                    return result;
×
1056
                }
×
1057
                return shiftSelection(result, rowMarkerOffset);
5✔
1058
            }
5✔
1059
            return true;
4✔
1060
        },
9✔
1061
        [onDeleteIn, rowMarkerOffset]
742✔
1062
    );
742✔
1063

742✔
1064
    const [setCurrent, setSelectedRows, setSelectedColumns] = useSelectionBehavior(
742✔
1065
        gridSelection,
742✔
1066
        setGridSelection,
742✔
1067
        rangeSelectionBlending,
742✔
1068
        columnSelectionBlending,
742✔
1069
        rowSelectionBlending,
742✔
1070
        rangeSelect,
742✔
1071
        rangeSelectionColumnSpanning
742✔
1072
    );
742✔
1073

742✔
1074
    const mergedTheme = React.useMemo(() => {
742✔
1075
        return mergeAndRealizeTheme(getDataEditorTheme(), theme);
151✔
1076
    }, [theme]);
742✔
1077

742✔
1078
    const [clientSize, setClientSize] = React.useState<readonly [number, number, number]>([0, 0, 0]);
742✔
1079

742✔
1080
    const rendererMap = React.useMemo(() => {
742✔
1081
        if (renderers === undefined) return {};
151!
1082
        const result: Partial<Record<InnerGridCellKind | GridCellKind, InternalCellRenderer<InnerGridCell>>> = {};
151✔
1083
        for (const r of renderers) {
151✔
1084
            result[r.kind] = r;
1,964✔
1085
        }
1,964✔
1086
        return result;
151✔
1087
    }, [renderers]);
742✔
1088

742✔
1089
    const getCellRenderer: <T extends InnerGridCell>(cell: T) => CellRenderer<T> | undefined = React.useCallback(
742✔
1090
        <T extends InnerGridCell>(cell: T) => {
742✔
1091
            if (cell.kind !== GridCellKind.Custom) {
150,834✔
1092
                return rendererMap[cell.kind] as unknown as CellRenderer<T>;
147,104✔
1093
            }
147,104✔
1094
            return additionalRenderers?.find(x => x.isMatch(cell)) as CellRenderer<T>;
150,834✔
1095
        },
150,834✔
1096
        [additionalRenderers, rendererMap]
742✔
1097
    );
742✔
1098

742✔
1099
    // eslint-disable-next-line prefer-const
742✔
1100
    let { sizedColumns: columns, nonGrowWidth } = useColumnSizer(
742✔
1101
        columnsIn,
742✔
1102
        rows,
742✔
1103
        getCellsForSeletionDirect,
742✔
1104
        clientSize[0] - (rowMarkerOffset === 0 ? 0 : rowMarkerWidth) - clientSize[2],
742✔
1105
        minColumnWidth,
742✔
1106
        maxColumnAutoWidth,
742✔
1107
        mergedTheme,
742✔
1108
        getCellRenderer,
742✔
1109
        abortControllerRef.current
742✔
1110
    );
742✔
1111
    if (rowMarkers !== "none") nonGrowWidth += rowMarkerWidth;
742✔
1112

742✔
1113
    const enableGroups = React.useMemo(() => {
742✔
1114
        return columns.some(c => c.group !== undefined);
152✔
1115
    }, [columns]);
742✔
1116

742✔
1117
    const totalHeaderHeight = enableGroups ? headerHeight + groupHeaderHeight : headerHeight;
742✔
1118

742✔
1119
    const numSelectedRows = gridSelection.rows.length;
742✔
1120
    const rowMarkerChecked =
742✔
1121
        rowMarkers === "none" ? undefined : numSelectedRows === 0 ? false : numSelectedRows === rows ? true : undefined;
742✔
1122

742✔
1123
    const mangledCols = React.useMemo(() => {
742✔
1124
        if (rowMarkers === "none") return columns;
167✔
1125
        return [
47✔
1126
            {
47✔
1127
                title: "",
47✔
1128
                width: rowMarkerWidth,
47✔
1129
                icon: undefined,
47✔
1130
                hasMenu: false,
47✔
1131
                style: "normal" as const,
47✔
1132
                themeOverride: rowMarkerTheme,
47✔
1133
                rowMarker: rowMarkerCheckboxStyle,
47✔
1134
                rowMarkerChecked,
47✔
1135
                headerRowMarkerTheme,
47✔
1136
                headerRowMarkerAlwaysVisible,
47✔
1137
                headerRowMarkerDisabled,
47✔
1138
            },
47✔
1139
            ...columns,
47✔
1140
        ];
47✔
1141
    }, [
742✔
1142
        rowMarkers,
742✔
1143
        columns,
742✔
1144
        rowMarkerWidth,
742✔
1145
        rowMarkerTheme,
742✔
1146
        rowMarkerCheckboxStyle,
742✔
1147
        rowMarkerChecked,
742✔
1148
        headerRowMarkerTheme,
742✔
1149
        headerRowMarkerAlwaysVisible,
742✔
1150
        headerRowMarkerDisabled,
742✔
1151
    ]);
742✔
1152

742✔
1153
    const visibleRegionRef = React.useRef<VisibleRegion>({
742✔
1154
        height: 1,
742✔
1155
        width: 1,
742✔
1156
        x: 0,
742✔
1157
        y: 0,
742✔
1158
    });
742✔
1159

742✔
1160
    const hasJustScrolled = React.useRef(false);
742✔
1161

742✔
1162
    const { setVisibleRegion, visibleRegion, scrollRef } = useInitialScrollOffset(
742✔
1163
        scrollOffsetX,
742✔
1164
        scrollOffsetY,
742✔
1165
        rowHeight,
742✔
1166
        visibleRegionRef,
742✔
1167
        () => (hasJustScrolled.current = true)
742✔
1168
    );
742✔
1169

742✔
1170
    visibleRegionRef.current = visibleRegion;
742✔
1171

742✔
1172
    const cellXOffset = visibleRegion.x + rowMarkerOffset;
742✔
1173
    const cellYOffset = visibleRegion.y;
742✔
1174

742✔
1175
    const gridRef = React.useRef<DataGridRef | null>(null);
742✔
1176

742✔
1177
    const focus = React.useCallback((immediate?: boolean) => {
742✔
1178
        if (immediate === true) {
135✔
1179
            gridRef.current?.focus();
12✔
1180
        } else {
135✔
1181
            window.requestAnimationFrame(() => {
123✔
1182
                gridRef.current?.focus();
122✔
1183
            });
123✔
1184
        }
123✔
1185
    }, []);
742✔
1186

742✔
1187
    const mangledRows = showTrailingBlankRow ? rows + 1 : rows;
742✔
1188

742✔
1189
    const mangledOnCellsEdited = React.useCallback<NonNullable<typeof onCellsEdited>>(
742✔
1190
        (items: readonly EditListItem[]) => {
742✔
1191
            const mangledItems =
29✔
1192
                rowMarkerOffset === 0
29✔
1193
                    ? items
24✔
1194
                    : items.map(x => ({
5✔
1195
                          ...x,
29✔
1196
                          location: [x.location[0] - rowMarkerOffset, x.location[1]] as const,
29✔
1197
                      }));
5✔
1198
            const r = onCellsEdited?.(mangledItems);
29✔
1199

29✔
1200
            if (r !== true) {
29✔
1201
                for (const i of mangledItems) onCellEdited?.(i.location, i.value);
28✔
1202
            }
28✔
1203

29✔
1204
            return r;
29✔
1205
        },
29✔
1206
        [onCellEdited, onCellsEdited, rowMarkerOffset]
742✔
1207
    );
742✔
1208

742✔
1209
    const [fillHighlightRegion, setFillHighlightRegion] = React.useState<Rectangle | undefined>();
742✔
1210

742✔
1211
    // this will generally be undefined triggering the memo less often
742✔
1212
    const highlightRange =
742✔
1213
        gridSelection.current !== undefined &&
742✔
1214
        gridSelection.current.range.width * gridSelection.current.range.height > 1
366✔
1215
            ? gridSelection.current.range
44✔
1216
            : undefined;
698✔
1217

742✔
1218
    const highlightFocus = drawFocusRing ? gridSelection.current?.cell : undefined;
742!
1219
    const highlightFocusCol = highlightFocus?.[0];
742✔
1220
    const highlightFocusRow = highlightFocus?.[1];
742✔
1221

742✔
1222
    const highlightRegions = React.useMemo(() => {
742✔
1223
        if (
305✔
1224
            (highlightRegionsIn === undefined || highlightRegionsIn.length === 0) &&
305✔
1225
            (highlightRange ?? highlightFocusCol ?? highlightFocusRow ?? fillHighlightRegion) === undefined
304✔
1226
        )
305✔
1227
            return undefined;
305✔
1228

158✔
1229
        const regions: Highlight[] = [];
158✔
1230

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

158✔
1248
        if (fillHighlightRegion !== undefined) {
298✔
1249
            regions.push({
6✔
1250
                color: withAlpha(mergedTheme.accentColor, 0),
6✔
1251
                range: fillHighlightRegion,
6✔
1252
                style: "dashed",
6✔
1253
            });
6✔
1254
        }
6✔
1255

158✔
1256
        if (highlightRange !== undefined) {
298✔
1257
            regions.push({
30✔
1258
                color: withAlpha(mergedTheme.accentColor, 0.5),
30✔
1259
                range: highlightRange,
30✔
1260
                style: "solid-outline",
30✔
1261
            });
30✔
1262
        }
30✔
1263

158✔
1264
        if (highlightFocusCol !== undefined && highlightFocusRow !== undefined) {
305✔
1265
            regions.push({
157✔
1266
                color: mergedTheme.accentColor,
157✔
1267
                range: {
157✔
1268
                    x: highlightFocusCol,
157✔
1269
                    y: highlightFocusRow,
157✔
1270
                    width: 1,
157✔
1271
                    height: 1,
157✔
1272
                },
157✔
1273
                style: "solid-outline",
157✔
1274
            });
157✔
1275
        }
157✔
1276

158✔
1277
        return regions.length > 0 ? regions : undefined;
305!
1278
    }, [
742✔
1279
        fillHighlightRegion,
742✔
1280
        highlightRange,
742✔
1281
        highlightFocusCol,
742✔
1282
        highlightFocusRow,
742✔
1283
        highlightRegionsIn,
742✔
1284
        mangledCols.length,
742✔
1285
        mergedTheme.accentColor,
742✔
1286
        rowMarkerOffset,
742✔
1287
    ]);
742✔
1288

742✔
1289
    const mangledColsRef = React.useRef(mangledCols);
742✔
1290
    mangledColsRef.current = mangledCols;
742✔
1291
    const getMangledCellContent = React.useCallback(
742✔
1292
        ([col, row]: Item, forceStrict: boolean = false): InnerGridCell => {
742✔
1293
            const isTrailing = showTrailingBlankRow && row === mangledRows - 1;
151,960✔
1294
            const isRowMarkerCol = col === 0 && hasRowMarkers;
151,960✔
1295
            if (isRowMarkerCol) {
151,960✔
1296
                if (isTrailing) {
2,185✔
1297
                    return loadingCell;
67✔
1298
                }
67✔
1299
                const mappedRow = rowNumberMapper(row);
2,118✔
1300
                if (mappedRow === undefined) return loadingCell;
2,185!
1301
                return {
2,118✔
1302
                    kind: InnerGridCellKind.Marker,
2,118✔
1303
                    allowOverlay: false,
2,118✔
1304
                    checkboxStyle: rowMarkerCheckboxStyle,
2,118✔
1305
                    checked: gridSelection?.rows.hasIndex(row) === true,
2,185✔
1306
                    markerKind: rowMarkers === "clickable-number" ? "number" : rowMarkers,
2,185!
1307
                    row: rowMarkerStartIndex + mappedRow,
2,185✔
1308
                    drawHandle: onRowMoved !== undefined,
2,185✔
1309
                    cursor: rowMarkers === "clickable-number" ? "pointer" : undefined,
2,185!
1310
                };
2,185✔
1311
            } else if (isTrailing) {
151,960✔
1312
                //If the grid is empty, we will return text
3,989✔
1313
                const isFirst = col === rowMarkerOffset;
3,989✔
1314

3,989✔
1315
                const maybeFirstColumnHint = isFirst ? trailingRowOptions?.hint ?? "" : "";
3,989✔
1316
                const c = mangledColsRef.current[col];
3,989✔
1317

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

26,505✔
1351
                    if (isOutsideMainArea && !isSelected && !isInFreezeArea) {
26,505!
1352
                        return loadingCell;
×
1353
                    }
×
1354
                }
26,505✔
1355
                let result = getCellContent([outerCol, row]);
145,786✔
1356
                if (rowMarkerOffset !== 0 && result.span !== undefined) {
145,786!
1357
                    result = {
×
1358
                        ...result,
×
1359
                        span: [result.span[0] + rowMarkerOffset, result.span[1] + rowMarkerOffset],
×
1360
                    };
×
1361
                }
×
1362
                return result;
145,786✔
1363
            }
145,786✔
1364
        },
151,960✔
1365
        [
742✔
1366
            showTrailingBlankRow,
742✔
1367
            mangledRows,
742✔
1368
            hasRowMarkers,
742✔
1369
            rowNumberMapper,
742✔
1370
            rowMarkerCheckboxStyle,
742✔
1371
            gridSelection?.rows,
742✔
1372
            rowMarkers,
742✔
1373
            rowMarkerStartIndex,
742✔
1374
            onRowMoved,
742✔
1375
            rowMarkerOffset,
742✔
1376
            trailingRowOptions?.hint,
742✔
1377
            trailingRowOptions?.addIcon,
742✔
1378
            experimental?.strict,
742✔
1379
            getCellContent,
742✔
1380
        ]
742✔
1381
    );
742✔
1382

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

742✔
1410
    const setOverlaySimple = React.useCallback(
742✔
1411
        (val: Omit<NonNullable<typeof overlay>, "theme">) => {
742✔
1412
            const [col, row] = val.cell;
25✔
1413
            const column = mangledCols[col];
25✔
1414
            const groupTheme =
25✔
1415
                column?.group !== undefined ? mangledGetGroupDetails(column.group)?.overrideTheme : undefined;
25!
1416
            const colTheme = column?.themeOverride;
25✔
1417
            const rowTheme = getRowThemeOverride?.(row);
25!
1418

25✔
1419
            setOverlay({
25✔
1420
                ...val,
25✔
1421
                theme: mergeAndRealizeTheme(mergedTheme, groupTheme, colTheme, rowTheme, val.content.themeOverride),
25✔
1422
            });
25✔
1423
        },
25✔
1424
        [getRowThemeOverride, mangledCols, mangledGetGroupDetails, mergedTheme]
742✔
1425
    );
742✔
1426

742✔
1427
    const reselect = React.useCallback(
742✔
1428
        (bounds: Rectangle, fromKeyboard: boolean, initialValue?: string) => {
742✔
1429
            if (gridSelection.current === undefined) return;
26!
1430

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

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

742✔
1480
    const focusOnRowFromTrailingBlankRow = React.useCallback(
742✔
1481
        (col: number, row: number) => {
742✔
1482
            const bounds = gridRef.current?.getBounds(col, row);
1✔
1483
            if (bounds === undefined || scrollRef.current === null) {
1!
1484
                return;
×
1485
            }
×
1486

1✔
1487
            const content = getMangledCellContent([col, row]);
1✔
1488
            if (!content.allowOverlay) {
1!
1489
                return;
×
1490
            }
×
1491

1✔
1492
            setOverlaySimple({
1✔
1493
                target: bounds,
1✔
1494
                content,
1✔
1495
                initialValue: undefined,
1✔
1496
                highlight: true,
1✔
1497
                cell: [col, row],
1✔
1498
                forceEditMode: true,
1✔
1499
            });
1✔
1500
        },
1✔
1501
        [getMangledCellContent, scrollRef, setOverlaySimple]
742✔
1502
    );
742✔
1503

742✔
1504
    const scrollTo = React.useCallback<ScrollToFn>(
742✔
1505
        (col, row, dir = "both", paddingX = 0, paddingY = 0, options = undefined): void => {
742✔
1506
            if (scrollRef.current !== null) {
53✔
1507
                const grid = gridRef.current;
53✔
1508
                const canvas = canvasRef.current;
53✔
1509

53✔
1510
                const trueCol = typeof col !== "number" ? (col.unit === "cell" ? col.amount : undefined) : col;
53!
1511
                const trueRow = typeof row !== "number" ? (row.unit === "cell" ? row.amount : undefined) : row;
53!
1512
                const desiredX = typeof col !== "number" && col.unit === "px" ? col.amount : undefined;
53!
1513
                const desiredY = typeof row !== "number" && row.unit === "px" ? row.amount : undefined;
53✔
1514
                if (grid !== null && canvas !== null) {
53✔
1515
                    let targetRect: Rectangle = {
53✔
1516
                        x: 0,
53✔
1517
                        y: 0,
53✔
1518
                        width: 0,
53✔
1519
                        height: 0,
53✔
1520
                    };
53✔
1521

53✔
1522
                    let scrollX = 0;
53✔
1523
                    let scrollY = 0;
53✔
1524

53✔
1525
                    if (trueCol !== undefined || trueRow !== undefined) {
53!
1526
                        targetRect = grid.getBounds((trueCol ?? 0) + rowMarkerOffset, trueRow ?? 0) ?? targetRect;
53!
1527
                        if (targetRect.width === 0 || targetRect.height === 0) return;
53!
1528
                    }
53✔
1529

53✔
1530
                    const scrollBounds = canvas.getBoundingClientRect();
53✔
1531
                    const scale = scrollBounds.width / canvas.offsetWidth;
53✔
1532

53✔
1533
                    if (desiredX !== undefined) {
53!
1534
                        targetRect = {
×
1535
                            ...targetRect,
×
1536
                            x: desiredX - scrollBounds.left - scrollRef.current.scrollLeft,
×
1537
                            width: 1,
×
1538
                        };
×
1539
                    }
×
1540
                    if (desiredY !== undefined) {
53✔
1541
                        targetRect = {
4✔
1542
                            ...targetRect,
4✔
1543
                            y: desiredY + scrollBounds.top - scrollRef.current.scrollTop,
4✔
1544
                            height: 1,
4✔
1545
                        };
4✔
1546
                    }
4✔
1547

53✔
1548
                    if (targetRect !== undefined) {
53✔
1549
                        const bounds = {
53✔
1550
                            x: targetRect.x - paddingX,
53✔
1551
                            y: targetRect.y - paddingY,
53✔
1552
                            width: targetRect.width + 2 * paddingX,
53✔
1553
                            height: targetRect.height + 2 * paddingY,
53✔
1554
                        };
53✔
1555

53✔
1556
                        let frozenWidth = 0;
53✔
1557
                        for (let i = 0; i < freezeColumns; i++) {
53!
1558
                            frozenWidth += columns[i].width;
×
1559
                        }
×
1560
                        let trailingRowHeight = 0;
53✔
1561
                        const freezeTrailingRowsEffective = freezeTrailingRows + (lastRowSticky ? 1 : 0);
53✔
1562
                        if (freezeTrailingRowsEffective > 0) {
53✔
1563
                            trailingRowHeight = getFreezeTrailingHeight(
51✔
1564
                                mangledRows,
51✔
1565
                                freezeTrailingRowsEffective,
51✔
1566
                                rowHeight
51✔
1567
                            );
51✔
1568
                        }
51✔
1569

53✔
1570
                        // scrollBounds is already scaled
53✔
1571
                        let sLeft = frozenWidth * scale + scrollBounds.left + rowMarkerOffset * rowMarkerWidth * scale;
53✔
1572
                        let sRight = scrollBounds.right;
53✔
1573
                        let sTop = scrollBounds.top + totalHeaderHeight * scale;
53✔
1574
                        let sBottom = scrollBounds.bottom - trailingRowHeight * scale;
53✔
1575

53✔
1576
                        const minx = targetRect.width + paddingX * 2;
53✔
1577
                        switch (options?.hAlign) {
53✔
1578
                            case "start":
53!
1579
                                sRight = sLeft + minx;
×
1580
                                break;
×
1581
                            case "end":
53!
1582
                                sLeft = sRight - minx;
×
1583
                                break;
×
1584
                            case "center":
53!
1585
                                sLeft = Math.floor((sLeft + sRight) / 2) - minx / 2;
×
1586
                                sRight = sLeft + minx;
×
1587
                                break;
×
1588
                        }
53✔
1589

53✔
1590
                        const miny = targetRect.height + paddingY * 2;
53✔
1591
                        switch (options?.vAlign) {
53✔
1592
                            case "start":
53✔
1593
                                sBottom = sTop + miny;
1✔
1594
                                break;
1✔
1595
                            case "end":
53✔
1596
                                sTop = sBottom - miny;
1✔
1597
                                break;
1✔
1598
                            case "center":
53✔
1599
                                sTop = Math.floor((sTop + sBottom) / 2) - miny / 2;
1✔
1600
                                sBottom = sTop + miny;
1✔
1601
                                break;
1✔
1602
                        }
53✔
1603

53✔
1604
                        if (sLeft > bounds.x) {
53!
1605
                            scrollX = bounds.x - sLeft;
×
1606
                        } else if (sRight < bounds.x + bounds.width) {
53✔
1607
                            scrollX = bounds.x + bounds.width - sRight;
7✔
1608
                        }
7✔
1609

53✔
1610
                        if (sTop > bounds.y) {
53!
1611
                            scrollY = bounds.y - sTop;
×
1612
                        } else if (sBottom < bounds.y + bounds.height) {
53✔
1613
                            scrollY = bounds.y + bounds.height - sBottom;
16✔
1614
                        }
16✔
1615

53✔
1616
                        if (dir === "vertical" || (typeof col === "number" && col < freezeColumns)) {
53✔
1617
                            scrollX = 0;
4✔
1618
                        } else if (
4✔
1619
                            dir === "horizontal" ||
49✔
1620
                            (typeof row === "number" && row >= mangledRows - freezeTrailingRowsEffective)
41✔
1621
                        ) {
49✔
1622
                            scrollY = 0;
10✔
1623
                        }
10✔
1624

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

742✔
1655
    const focusCallback = React.useRef(focusOnRowFromTrailingBlankRow);
742✔
1656
    const getCellContentRef = React.useRef(getCellContent);
742✔
1657

742✔
1658
    focusCallback.current = focusOnRowFromTrailingBlankRow;
742✔
1659
    getCellContentRef.current = getCellContent;
742✔
1660

742✔
1661
    const rowsRef = React.useRef(rows);
742✔
1662
    rowsRef.current = rows;
742✔
1663

742✔
1664
    const colsRef = React.useRef(mangledCols.length);
742✔
1665
    colsRef.current = mangledCols.length;
742✔
1666

742✔
1667
    const appendRow = React.useCallback(
742✔
1668
        async (col: number, openOverlay: boolean = true, behavior?: ScrollBehavior): Promise<void> => {
742✔
1669
            const c = mangledCols[col];
2✔
1670
            if (c?.trailingRowOptions?.disabled === true) {
2!
1671
                return;
×
1672
            }
×
1673
            const appendResult = onRowAppended?.();
2✔
1674

2✔
1675
            let r: "top" | "bottom" | number | undefined = undefined;
2✔
1676
            let bottom = true;
2✔
1677
            if (appendResult !== undefined) {
2!
1678
                r = await appendResult;
×
1679
                if (r === "top") bottom = false;
×
1680
                if (typeof r === "number") bottom = false;
×
1681
            }
×
1682

2✔
1683
            let backoff = 0;
2✔
1684
            const doFocus = () => {
2✔
1685
                if (rowsRef.current <= rows) {
4✔
1686
                    if (backoff < 500) {
2✔
1687
                        window.setTimeout(doFocus, backoff);
2✔
1688
                    }
2✔
1689
                    backoff = 50 + backoff * 2;
2✔
1690
                    return;
2✔
1691
                }
2✔
1692

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

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

742✔
1724
        const appendColumn = React.useCallback(
742✔
1725
        async (row: number, openOverlay: boolean = true): Promise<void> => {
742✔
1726
            const appendResult = onColumnAppended?.();
1✔
1727

1✔
1728
            let r: "left" | "right" | number | undefined = undefined;
1✔
1729
            let right = true;
1✔
1730
            if (appendResult !== undefined) {
1!
NEW
1731
                r = await appendResult;
×
NEW
1732
                if (r === "left") right = false;
×
NEW
1733
                if (typeof r === "number") right = false;
×
NEW
1734
            }
×
1735

1✔
1736
            let backoff = 0;
1✔
1737
            const doFocus = () => {
1✔
1738
                if (colsRef.current <= mangledCols.length) {
2✔
1739
                    if (backoff < 500) {
1✔
1740
                        window.setTimeout(doFocus, backoff);
1✔
1741
                    }
1✔
1742
                    backoff = 50 + backoff * 2;
1✔
1743
                    return;
1✔
1744
                }
1✔
1745

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

2✔
1763
                const cell = getCellContentRef.current([col - rowMarkerOffset, row]);
2✔
1764
                if (cell.allowOverlay && isReadWriteCell(cell) && cell.readonly !== true && openOverlay) {
2!
NEW
1765
                    window.setTimeout(() => {
×
NEW
1766
                        focusCallback.current(col, row);
×
NEW
1767
                    }, 0);
×
NEW
1768
                }
×
1769
            };
2✔
1770
            doFocus();
1✔
1771
        },
1✔
1772
        [mangledCols, onColumnAppended, rowMarkerOffset, scrollTo, setCurrent]
742✔
1773
    );
742✔
1774

742✔
1775
    const getCustomNewRowTargetColumn = React.useCallback(
742✔
1776
        (col: number): number | undefined => {
742✔
1777
            const customTargetColumn =
1✔
1778
                columns[col]?.trailingRowOptions?.targetColumn ?? trailingRowOptions?.targetColumn;
1!
1779

1✔
1780
            if (typeof customTargetColumn === "number") {
1!
1781
                const customTargetOffset = hasRowMarkers ? 1 : 0;
×
1782
                return customTargetColumn + customTargetOffset;
×
1783
            }
×
1784

1✔
1785
            if (typeof customTargetColumn === "object") {
1!
1786
                const maybeIndex = columnsIn.indexOf(customTargetColumn);
×
1787
                if (maybeIndex >= 0) {
×
1788
                    const customTargetOffset = hasRowMarkers ? 1 : 0;
×
1789
                    return maybeIndex + customTargetOffset;
×
1790
                }
×
1791
            }
×
1792

1✔
1793
            return undefined;
1✔
1794
        },
1✔
1795
        [columns, columnsIn, hasRowMarkers, trailingRowOptions?.targetColumn]
742✔
1796
    );
742✔
1797

742✔
1798
    const lastSelectedRowRef = React.useRef<number>();
742✔
1799
    const lastSelectedColRef = React.useRef<number>();
742✔
1800

742✔
1801
    const themeForCell = React.useCallback(
742✔
1802
        (cell: InnerGridCell, pos: Item): FullTheme => {
742✔
1803
            const [col, row] = pos;
28✔
1804
            return mergeAndRealizeTheme(
28✔
1805
                mergedTheme,
28✔
1806
                mangledCols[col]?.themeOverride,
28✔
1807
                getRowThemeOverride?.(row),
28!
1808
                cell.themeOverride
28✔
1809
            );
28✔
1810
        },
28✔
1811
        [getRowThemeOverride, mangledCols, mergedTheme]
742✔
1812
    );
742✔
1813

742✔
1814
    const { mapper } = useRowGrouping(rowGrouping, rowsIn);
742✔
1815

742✔
1816
    const rowGroupingNavBehavior = rowGrouping?.navigationBehavior;
742!
1817

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

111✔
1831
                lastMouseSelectLocation.current = [col, row];
111✔
1832

111✔
1833
                if (col === 0 && hasRowMarkers) {
111✔
1834
                    if (
15✔
1835
                        (showTrailingBlankRow === true && row === rows) ||
15✔
1836
                        rowMarkers === "number" ||
15✔
1837
                        rowSelect === "none"
14✔
1838
                    )
15✔
1839
                        return;
15✔
1840

14✔
1841
                    const markerCell = getMangledCellContent(args.location);
14✔
1842
                    if (markerCell.kind !== InnerGridCellKind.Marker) {
15!
1843
                        return;
×
1844
                    }
✔
1845

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

14✔
1861
                    setOverlay(undefined);
14✔
1862
                    focus();
14✔
1863
                    const isSelected = selectedRows.hasIndex(row);
14✔
1864

14✔
1865
                    const lastHighlighted = lastSelectedRowRef.current;
14✔
1866
                    if (
14✔
1867
                        rowSelect === "multi" &&
14✔
1868
                        (args.shiftKey || args.isLongTouch === true) &&
8✔
1869
                        lastHighlighted !== undefined &&
1✔
1870
                        selectedRows.hasIndex(lastHighlighted)
1✔
1871
                    ) {
15✔
1872
                        const newSlice: Slice = [Math.min(lastHighlighted, row), Math.max(lastHighlighted, row) + 1];
1✔
1873

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

89✔
1900
                        if (renderer?.onSelect !== undefined) {
89✔
1901
                            let prevented = false;
7✔
1902
                            renderer.onSelect({
7✔
1903
                                ...args,
7✔
1904
                                cell,
7✔
1905
                                posX: args.localEventX,
7✔
1906
                                posY: args.localEventY,
7✔
1907
                                bounds: args.bounds,
7✔
1908
                                preventDefault: () => (prevented = true),
7✔
1909
                                theme: themeForCell(cell, args.location),
7✔
1910
                            });
7✔
1911
                            if (prevented) {
7✔
1912
                                return;
4✔
1913
                            }
4✔
1914
                        }
7✔
1915

85✔
1916
                        if (rowGroupingNavBehavior === "block" && mapper(row).isGroupHeader) {
89!
1917
                            return;
×
1918
                        }
✔
1919

85✔
1920
                        const isLastStickyRow = lastRowSticky && row === rows;
85✔
1921

89✔
1922
                        const startedFromLastSticky =
89✔
1923
                            lastRowSticky && gridSelection !== undefined && gridSelection.current?.cell[1] === rows;
89✔
1924

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

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

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

144✔
2077
            const time = performance.now();
144✔
2078
            mouseDownData.current = {
144✔
2079
                button: args.button,
144✔
2080
                time,
144✔
2081
                location: args.location,
144✔
2082
            };
144✔
2083

144✔
2084
            if (args?.kind === "header") {
145✔
2085
                isActivelyDraggingHeader.current = true;
18✔
2086
            }
18✔
2087

144✔
2088
            const fh = args.kind === "cell" && args.isFillHandle;
145✔
2089

145✔
2090
            if (!fh && args.kind !== "cell" && args.isEdge) return;
145✔
2091

137✔
2092
            setMouseState({
137✔
2093
                previousSelection: gridSelection,
137✔
2094
                fillHandle: fh,
137✔
2095
            });
137✔
2096
            lastMouseSelectLocation.current = undefined;
137✔
2097

137✔
2098
            if (!args.isTouch && args.button === 0 && !fh) {
145✔
2099
                handleSelect(args);
124✔
2100
            } else if (!args.isTouch && args.button === 1) {
138✔
2101
                lastMouseSelectLocation.current = args.location;
4✔
2102
            }
4✔
2103
        },
145✔
2104
        [gridSelection, handleSelect]
742✔
2105
    );
742✔
2106

742✔
2107
    const [renameGroup, setRenameGroup] = React.useState<{
742✔
2108
        group: string;
742✔
2109
        bounds: Rectangle;
742✔
2110
    }>();
742✔
2111

742✔
2112
    const handleGroupHeaderSelection = React.useCallback(
742✔
2113
        (args: GridMouseEventArgs) => {
742✔
2114
            if (args.kind !== groupHeaderKind || columnSelect !== "multi") {
3!
2115
                return;
×
2116
            }
×
2117
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
3!
2118
            const [col] = args.location;
3✔
2119
            const selectedColumns = gridSelection.columns;
3✔
2120

3✔
2121
            if (col < rowMarkerOffset) return;
3!
2122

3✔
2123
            const needle = mangledCols[col];
3✔
2124
            let start = col;
3✔
2125
            let end = col;
3✔
2126
            for (let i = col - 1; i >= rowMarkerOffset; i--) {
3✔
2127
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
3!
2128
                start--;
3✔
2129
            }
3✔
2130

3✔
2131
            for (let i = col + 1; i < mangledCols.length; i++) {
3✔
2132
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
27!
2133
                end++;
27✔
2134
            }
27✔
2135

3✔
2136
            focus();
3✔
2137

3✔
2138
            if (isMultiKey) {
3✔
2139
                if (selectedColumns.hasAll([start, end + 1])) {
2✔
2140
                    let newVal = selectedColumns;
1✔
2141
                    for (let index = start; index <= end; index++) {
1✔
2142
                        newVal = newVal.remove(index);
11✔
2143
                    }
11✔
2144
                    setSelectedColumns(newVal, undefined, isMultiKey);
1✔
2145
                } else {
1✔
2146
                    setSelectedColumns(undefined, [start, end + 1], isMultiKey);
1✔
2147
                }
1✔
2148
            } else {
3✔
2149
                setSelectedColumns(CompactSelection.fromSingleSelection([start, end + 1]), undefined, isMultiKey);
1✔
2150
            }
1✔
2151
        },
3✔
2152
        [columnSelect, focus, gridSelection.columns, mangledCols, rowMarkerOffset, setSelectedColumns]
742✔
2153
    );
742✔
2154

742✔
2155
    const isPrevented = React.useRef(false);
742✔
2156

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

742✔
2207
    const [scrollDir, setScrollDir] = React.useState<GridMouseEventArgs["scrollEdge"]>();
742✔
2208

742✔
2209
    const fillPattern = React.useCallback(
742✔
2210
        async (previousSelection: GridSelection, currentSelection: GridSelection) => {
742✔
2211
            const patternRange = previousSelection.current?.range;
7✔
2212

7✔
2213
            if (
7✔
2214
                patternRange === undefined ||
7✔
2215
                getCellsForSelection === undefined ||
7✔
2216
                currentSelection.current === undefined
7✔
2217
            ) {
7!
2218
                return;
×
2219
            }
×
2220
            const currentRange = currentSelection.current.range;
7✔
2221

7✔
2222
            if (onFillPattern !== undefined) {
7✔
2223
                let canceled = false;
1✔
2224
                onFillPattern({
1✔
2225
                    fillDestination: { ...currentRange, x: currentRange.x - rowMarkerOffset },
1✔
2226
                    patternSource: { ...patternRange, x: patternRange.x - rowMarkerOffset },
1✔
2227
                    preventDefault: () => (canceled = true),
1✔
2228
                });
1✔
2229
                if (canceled) return;
1!
2230
            }
1✔
2231

7✔
2232
            let cells = getCellsForSelection(patternRange, abortControllerRef.current.signal);
7✔
2233
            if (typeof cells !== "object") cells = await cells();
7!
2234

7✔
2235
            const pattern = cells;
7✔
2236

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

7✔
2253
            gridRef.current?.damage(
7✔
2254
                editItemList.map(c => ({
7✔
2255
                    cell: c.location,
29✔
2256
                }))
7✔
2257
            );
7✔
2258
        },
7✔
2259
        [getCellsForSelection, mangledOnCellsEdited, onFillPattern, rowMarkerOffset]
742✔
2260
    );
742✔
2261

742✔
2262
    const fillRight = React.useCallback(() => {
742✔
2263
        if (gridSelection.current === undefined || gridSelection.current.range.width <= 1) return;
1!
2264

1✔
2265
        const firstColSelection = {
1✔
2266
            ...gridSelection,
1✔
2267
            current: {
1✔
2268
                ...gridSelection.current,
1✔
2269
                range: {
1✔
2270
                    ...gridSelection.current.range,
1✔
2271
                    width: 1,
1✔
2272
                },
1✔
2273
            },
1✔
2274
        };
1✔
2275

1✔
2276
        void fillPattern(firstColSelection, gridSelection);
1✔
2277
    }, [fillPattern, gridSelection]);
742✔
2278

742✔
2279
    const fillDown = React.useCallback(() => {
742✔
2280
        if (gridSelection.current === undefined || gridSelection.current.range.height <= 1) return;
1!
2281

1✔
2282
        const firstRowSelection = {
1✔
2283
            ...gridSelection,
1✔
2284
            current: {
1✔
2285
                ...gridSelection.current,
1✔
2286
                range: {
1✔
2287
                    ...gridSelection.current.range,
1✔
2288
                    height: 1,
1✔
2289
                },
1✔
2290
            },
1✔
2291
        };
1✔
2292

1✔
2293
        void fillPattern(firstRowSelection, gridSelection);
1✔
2294
    }, [fillPattern, gridSelection]);
742✔
2295

742✔
2296
    const onMouseUp = React.useCallback(
742✔
2297
        (args: GridMouseEventArgs, isOutside: boolean) => {
742✔
2298
            const mouse = mouseState;
144✔
2299
            setMouseState(undefined);
144✔
2300
            setFillHighlightRegion(undefined);
144✔
2301
            setScrollDir(undefined);
144✔
2302
            isActivelyDraggingHeader.current = false;
144✔
2303

144✔
2304
            if (isOutside) return;
144✔
2305

143✔
2306
            if (
143✔
2307
                mouse?.fillHandle === true &&
144✔
2308
                gridSelection.current !== undefined &&
5✔
2309
                mouse.previousSelection?.current !== undefined
5✔
2310
            ) {
144✔
2311
                if (fillHighlightRegion === undefined) return;
5!
2312
                const newRange = {
5✔
2313
                    ...gridSelection,
5✔
2314
                    current: {
5✔
2315
                        ...gridSelection.current,
5✔
2316
                        range: combineRects(mouse.previousSelection.current.range, fillHighlightRegion),
5✔
2317
                    },
5✔
2318
                };
5✔
2319
                void fillPattern(mouse.previousSelection, newRange);
5✔
2320
                setGridSelection(newRange, true);
5✔
2321
                return;
5✔
2322
            }
5✔
2323

138✔
2324
            const [col, row] = args.location;
138✔
2325
            const [lastMouseDownCol, lastMouseDownRow] = lastMouseSelectLocation.current ?? [];
144✔
2326

144✔
2327
            const preventDefault = () => {
144✔
2328
                isPrevented.current = true;
×
2329
            };
×
2330

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

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

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

×
2416
                        onGroupHeaderContextMenu?.(clickLocation, { ...args, preventDefault });
×
2417
                        return;
×
2418
                    }
×
2419
                }
×
2420
                if (args.kind === "cell") {
4✔
2421
                    // click that cell
2✔
2422
                    if (!handleMaybeClick(args)) {
2✔
2423
                        handleSelect(args);
2✔
2424
                    }
2✔
2425
                } else if (args.kind === groupHeaderKind) {
2✔
2426
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
1✔
2427
                } else {
1✔
2428
                    if (args.kind === headerKind) {
1✔
2429
                        onHeaderClicked?.(clickLocation, {
1✔
2430
                            ...args,
1✔
2431
                            preventDefault,
1✔
2432
                        });
1✔
2433
                    }
1✔
2434
                    handleSelect(args);
1✔
2435
                }
1✔
2436
                return;
4✔
2437
            }
4✔
2438

134✔
2439
            if (args.kind === "header") {
144✔
2440
                if (clickLocation < 0) {
16✔
2441
                    return;
3✔
2442
                }
3✔
2443

13✔
2444
                if (args.isEdge) {
16✔
2445
                    if (args.isDoubleClick === true) {
2✔
2446
                        void normalSizeColumn(col);
1✔
2447
                    }
1✔
2448
                } else if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
16✔
2449
                    onHeaderClicked?.(clickLocation, { ...args, preventDefault });
5✔
2450
                }
5✔
2451
            }
16✔
2452

131✔
2453
            if (args.kind === groupHeaderKind) {
144✔
2454
                if (clickLocation < 0) {
3!
2455
                    return;
×
2456
                }
×
2457

3✔
2458
                if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
3✔
2459
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
3!
2460
                    if (!isPrevented.current) {
3✔
2461
                        handleGroupHeaderSelection(args);
3✔
2462
                    }
3✔
2463
                }
3✔
2464
            }
3✔
2465

131✔
2466
            if (args.kind === "cell" && (args.button === 0 || args.button === 1)) {
144✔
2467
                handleMaybeClick(args);
111✔
2468
            }
111✔
2469

131✔
2470
            lastMouseSelectLocation.current = undefined;
131✔
2471
        },
144✔
2472
        [
742✔
2473
            mouseState,
742✔
2474
            gridSelection,
742✔
2475
            rowMarkerOffset,
742✔
2476
            fillHighlightRegion,
742✔
2477
            fillPattern,
742✔
2478
            setGridSelection,
742✔
2479
            onCellClicked,
742✔
2480
            getMangledCellContent,
742✔
2481
            getCellRenderer,
742✔
2482
            cellActivationBehavior,
742✔
2483
            themeForCell,
742✔
2484
            mangledOnCellsEdited,
742✔
2485
            onCellActivated,
742✔
2486
            reselect,
742✔
2487
            onCellContextMenu,
742✔
2488
            onHeaderContextMenu,
742✔
2489
            onGroupHeaderContextMenu,
742✔
2490
            handleSelect,
742✔
2491
            onGroupHeaderClicked,
742✔
2492
            onHeaderClicked,
742✔
2493
            normalSizeColumn,
742✔
2494
            handleGroupHeaderSelection,
742✔
2495
        ]
742✔
2496
    );
742✔
2497

742✔
2498
    const onMouseMoveImpl = React.useCallback(
742✔
2499
        (args: GridMouseEventArgs) => {
742✔
2500
            const a: GridMouseEventArgs = {
39✔
2501
                ...args,
39✔
2502
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
39✔
2503
            };
39✔
2504
            onMouseMove?.(a);
39✔
2505

39✔
2506
            if (mouseState !== undefined && args.buttons === 0) {
39✔
2507
                setMouseState(undefined);
6✔
2508
                setFillHighlightRegion(undefined);
6✔
2509
                setScrollDir(undefined);
6✔
2510
                isActivelyDraggingHeader.current = false;
6✔
2511
            }
6✔
2512

39✔
2513
            setScrollDir(cv => {
39✔
2514
                if (isActivelyDraggingHeader.current) return [args.scrollEdge[0], 0];
39✔
2515
                if (args.scrollEdge[0] === cv?.[0] && args.scrollEdge[1] === cv[1]) return cv;
39✔
2516
                return mouseState === undefined || (mouseDownData.current?.location[0] ?? 0) < rowMarkerOffset
39!
2517
                    ? undefined
13✔
2518
                    : args.scrollEdge;
16✔
2519
            });
39✔
2520
        },
39✔
2521
        [mouseState, onMouseMove, rowMarkerOffset]
742✔
2522
    );
742✔
2523

742✔
2524
    const onHeaderMenuClickInner = React.useCallback(
742✔
2525
        (col: number, screenPosition: Rectangle) => {
742✔
2526
            onHeaderMenuClick?.(col - rowMarkerOffset, screenPosition);
1✔
2527
        },
1✔
2528
        [onHeaderMenuClick, rowMarkerOffset]
742✔
2529
    );
742✔
2530

742✔
2531
    const onHeaderIndicatorClickInner = React.useCallback(
742✔
2532
        (col: number, screenPosition: Rectangle) => {
742✔
2533
            onHeaderIndicatorClick?.(col - rowMarkerOffset, screenPosition);
×
2534
        },
×
2535
        [onHeaderIndicatorClick, rowMarkerOffset]
742✔
2536
    );
742✔
2537

742✔
2538
    const currentCell = gridSelection?.current?.cell;
742✔
2539
    const onVisibleRegionChangedImpl = React.useCallback(
742✔
2540
        (
742✔
2541
            region: Rectangle,
156✔
2542
            clientWidth: number,
156✔
2543
            clientHeight: number,
156✔
2544
            rightElWidth: number,
156✔
2545
            tx: number,
156✔
2546
            ty: number
156✔
2547
        ) => {
156✔
2548
            hasJustScrolled.current = false;
156✔
2549
            let selected = currentCell;
156✔
2550
            if (selected !== undefined) {
156✔
2551
                selected = [selected[0] - rowMarkerOffset, selected[1]];
11✔
2552
            }
11✔
2553

156✔
2554
            const freezeRegion =
156✔
2555
                freezeColumns === 0
156✔
2556
                    ? undefined
155✔
2557
                    : {
1✔
2558
                          x: 0,
1✔
2559
                          y: region.y,
1✔
2560
                          width: freezeColumns,
1✔
2561
                          height: region.height,
1✔
2562
                      };
1✔
2563

156✔
2564
            const freezeRegions: Rectangle[] = [];
156✔
2565
            if (freezeRegion !== undefined) freezeRegions.push(freezeRegion);
156✔
2566
            if (freezeTrailingRows > 0) {
156✔
2567
                freezeRegions.push({
1✔
2568
                    x: region.x - rowMarkerOffset,
1✔
2569
                    y: rows - freezeTrailingRows,
1✔
2570
                    width: region.width,
1✔
2571
                    height: freezeTrailingRows,
1✔
2572
                });
1✔
2573

1✔
2574
                if (freezeColumns > 0) {
1✔
2575
                    freezeRegions.push({
1✔
2576
                        x: 0,
1✔
2577
                        y: rows - freezeTrailingRows,
1✔
2578
                        width: freezeColumns,
1✔
2579
                        height: freezeTrailingRows,
1✔
2580
                    });
1✔
2581
                }
1✔
2582
            }
1✔
2583

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

742✔
2614
    const onColumnProposeMoveImpl = whenDefined(
742✔
2615
        onColumnProposeMove,
742✔
2616
        React.useCallback(
742✔
2617
            (startIndex: number, endIndex: number) => {
742✔
2618
                return onColumnProposeMove?.(startIndex - rowMarkerOffset, endIndex - rowMarkerOffset) !== false;
×
2619
            },
×
2620
            [onColumnProposeMove, rowMarkerOffset]
742✔
2621
        )
742✔
2622
    );
742✔
2623

742✔
2624
    const onColumnMovedImpl = whenDefined(
742✔
2625
        onColumnMoved,
742✔
2626
        React.useCallback(
742✔
2627
            (startIndex: number, endIndex: number) => {
742✔
2628
                onColumnMoved?.(startIndex - rowMarkerOffset, endIndex - rowMarkerOffset);
1✔
2629
                if (columnSelect !== "none") {
1✔
2630
                    setSelectedColumns(CompactSelection.fromSingleSelection(endIndex), undefined, true);
1✔
2631
                }
1✔
2632
            },
1✔
2633
            [columnSelect, onColumnMoved, rowMarkerOffset, setSelectedColumns]
742✔
2634
        )
742✔
2635
    );
742✔
2636

742✔
2637
    const isActivelyDragging = React.useRef(false);
742✔
2638
    const onDragStartImpl = React.useCallback(
742✔
2639
        (args: GridDragEventArgs) => {
742✔
2640
            if (args.location[0] === 0 && rowMarkerOffset > 0) {
1!
2641
                args.preventDefault();
×
2642
                return;
×
2643
            }
×
2644
            onDragStart?.({
1✔
2645
                ...args,
1✔
2646
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
1✔
2647
            });
1✔
2648

1✔
2649
            if (!args.defaultPrevented()) {
1✔
2650
                isActivelyDragging.current = true;
1✔
2651
            }
1✔
2652
            setMouseState(undefined);
1✔
2653
        },
1✔
2654
        [onDragStart, rowMarkerOffset]
742✔
2655
    );
742✔
2656

742✔
2657
    const onDragEnd = React.useCallback(() => {
742✔
2658
        isActivelyDragging.current = false;
×
2659
    }, []);
742✔
2660

742✔
2661
    const rowGroupingSelectionBehavior = rowGrouping?.selectionBehavior;
742!
2662

742✔
2663
    const getSelectionRowLimits = React.useCallback(
742✔
2664
        (selectedRow: number): readonly [number, number] | undefined => {
742✔
2665
            if (rowGroupingSelectionBehavior !== "block-spanning") return undefined;
16!
2666

×
2667
            const { isGroupHeader, path, groupRows } = mapper(selectedRow);
×
2668

×
2669
            if (isGroupHeader) {
×
2670
                return [selectedRow, selectedRow];
×
2671
            }
×
2672

×
2673
            const groupRowIndex = path[path.length - 1];
×
2674
            const lowerBounds = selectedRow - groupRowIndex;
×
2675
            const upperBounds = selectedRow + groupRows - groupRowIndex - 1;
×
2676

×
2677
            return [lowerBounds, upperBounds];
×
2678
        },
16✔
2679
        [mapper, rowGroupingSelectionBehavior]
742✔
2680
    );
742✔
2681

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

12✔
2716
                if (row < 0) {
12✔
2717
                    row = visibleRegionRef.current.y;
1✔
2718
                }
1✔
2719

12✔
2720
                if (mouseState.fillHandle === true && mouseState.previousSelection?.current !== undefined) {
12✔
2721
                    const prevRange = mouseState.previousSelection.current.range;
6✔
2722
                    row = Math.min(row, showTrailingBlankRow ? rows - 1 : rows);
6!
2723
                    const rect = getClosestRect(prevRange, col, row, allowedFillDirections);
6✔
2724
                    setFillHighlightRegion(rect);
6✔
2725
                } else {
6✔
2726
                    const startedFromLastStickyRow = showTrailingBlankRow && selectedRow === rows;
6✔
2727
                    if (startedFromLastStickyRow) return;
6!
2728

6✔
2729
                    const landedOnLastStickyRow = showTrailingBlankRow && row === rows;
6✔
2730
                    if (landedOnLastStickyRow) {
6!
2731
                        if (args.kind === outOfBoundsKind) row--;
×
2732
                        else return;
×
2733
                    }
×
2734

6✔
2735
                    col = Math.max(col, rowMarkerOffset);
6✔
2736
                    const clampLimits = getSelectionRowLimits(selectedRow);
6✔
2737
                    row = clampLimits === undefined ? row : clamp(row, clampLimits[0], clampLimits[1]);
6!
2738

6✔
2739
                    // FIXME: Restrict row based on rowGrouping.selectionBehavior here
6✔
2740

6✔
2741
                    const deltaX = col - selectedCol;
6✔
2742
                    const deltaY = row - selectedRow;
6✔
2743

6✔
2744
                    const newRange: Rectangle = {
6✔
2745
                        x: deltaX >= 0 ? selectedCol : col,
6!
2746
                        y: deltaY >= 0 ? selectedRow : row,
6✔
2747
                        width: Math.abs(deltaX) + 1,
6✔
2748
                        height: Math.abs(deltaY) + 1,
6✔
2749
                    };
6✔
2750

6✔
2751
                    setCurrent(
6✔
2752
                        {
6✔
2753
                            ...gridSelection.current,
6✔
2754
                            range: newRange,
6✔
2755
                        },
6✔
2756
                        true,
6✔
2757
                        false,
6✔
2758
                        "drag"
6✔
2759
                    );
6✔
2760
                }
6✔
2761
            }
12✔
2762

28✔
2763
            onItemHovered?.({ ...args, location: [args.location[0] - rowMarkerOffset, args.location[1]] as any });
29✔
2764
        },
29✔
2765
        [
742✔
2766
            mouseState,
742✔
2767
            rowMarkerOffset,
742✔
2768
            rowSelect,
742✔
2769
            gridSelection,
742✔
2770
            rangeSelect,
742✔
2771
            onItemHovered,
742✔
2772
            setSelectedRows,
742✔
2773
            showTrailingBlankRow,
742✔
2774
            rows,
742✔
2775
            allowedFillDirections,
742✔
2776
            getSelectionRowLimits,
742✔
2777
            setCurrent,
742✔
2778
        ]
742✔
2779
    );
742✔
2780

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

742✔
2805
    useAutoscroll(scrollDir, scrollRef, adjustSelectionOnScroll);
742✔
2806

742✔
2807
    // 1 === move one
742✔
2808
    // 2 === move to end
742✔
2809
    const adjustSelection = React.useCallback(
742✔
2810
        (direction: [0 | 1 | -1 | 2 | -2, 0 | 1 | -1 | 2 | -2]) => {
742✔
2811
            if (gridSelection.current === undefined) return;
10!
2812

10✔
2813
            const [x, y] = direction;
10✔
2814
            const [col, row] = gridSelection.current.cell;
10✔
2815
            const old = gridSelection.current.range;
10✔
2816
            let left = old.x;
10✔
2817
            let right = old.x + old.width;
10✔
2818
            let top = old.y;
10✔
2819
            let bottom = old.y + old.height;
10✔
2820

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

10✔
2824
            // take care of vertical first in case new spans come in
10✔
2825
            if (y !== 0) {
10✔
2826
                switch (y) {
4✔
2827
                    case 2: {
4✔
2828
                        // go to end
2✔
2829
                        bottom = maxRow;
2✔
2830
                        top = row;
2✔
2831
                        scrollTo(0, bottom, "vertical");
2✔
2832

2✔
2833
                        break;
2✔
2834
                    }
2✔
2835
                    case -2: {
4✔
2836
                        // go to start
1✔
2837
                        top = minRow;
1✔
2838
                        bottom = row + 1;
1✔
2839
                        scrollTo(0, top, "vertical");
1✔
2840

1✔
2841
                        break;
1✔
2842
                    }
1✔
2843
                    case 1: {
4✔
2844
                        // motion down
1✔
2845
                        if (top < row) {
1!
2846
                            top++;
×
2847
                            scrollTo(0, top, "vertical");
×
2848
                        } else {
1✔
2849
                            bottom = Math.min(maxRow, bottom + 1);
1✔
2850
                            scrollTo(0, bottom, "vertical");
1✔
2851
                        }
1✔
2852

1✔
2853
                        break;
1✔
2854
                    }
1✔
2855
                    case -1: {
4!
2856
                        // motion up
×
2857
                        if (bottom > row + 1) {
×
2858
                            bottom--;
×
2859
                            scrollTo(0, bottom, "vertical");
×
2860
                        } else {
×
2861
                            top = Math.max(minRow, top - 1);
×
2862
                            scrollTo(0, top, "vertical");
×
2863
                        }
×
2864

×
2865
                        break;
×
2866
                    }
×
2867
                    default: {
4!
2868
                        assertNever(y);
×
2869
                    }
×
2870
                }
4✔
2871
            }
4✔
2872

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

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

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

742✔
2976
    const scrollToActiveCellRef = React.useRef(scrollToActiveCell);
742✔
2977
    scrollToActiveCellRef.current = scrollToActiveCell;
742✔
2978

742✔
2979
    const updateSelectedCell = React.useCallback(
742✔
2980
        (col: number, row: number, fromEditingTrailingRow: boolean, freeMove: boolean): boolean => {
742✔
2981
            const rowMax = mangledRows - (fromEditingTrailingRow ? 0 : 1);
68!
2982
            col = clamp(col, rowMarkerOffset, columns.length - 1 + rowMarkerOffset);
68✔
2983
            row = clamp(row, 0, rowMax);
68✔
2984

68✔
2985
            const curCol = currentCell?.[0];
68✔
2986
            const curRow = currentCell?.[1];
68✔
2987

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

30✔
3017
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
68✔
3018
                lastSent.current = undefined;
2✔
3019
            }
2✔
3020

30✔
3021
            if (scrollToActiveCellRef.current) {
30✔
3022
                scrollTo(col - rowMarkerOffset, row);
30✔
3023
            }
30✔
3024

30✔
3025
            return true;
30✔
3026
        },
68✔
3027
        [
742✔
3028
            mangledRows,
742✔
3029
            rowMarkerOffset,
742✔
3030
            columns.length,
742✔
3031
            currentCell,
742✔
3032
            gridSelection,
742✔
3033
            scrollTo,
742✔
3034
            setGridSelection,
742✔
3035
            setCurrent,
742✔
3036
        ]
742✔
3037
    );
742✔
3038

742✔
3039
    const onFinishEditing = React.useCallback(
742✔
3040
        (newValue: GridCell | undefined, movement: readonly [-1 | 0 | 1, -1 | 0 | 1]) => {
742✔
3041
            if (overlay?.cell !== undefined && newValue !== undefined && isEditableGridCell(newValue)) {
12✔
3042
                mangledOnCellsEdited([{ location: overlay.cell, value: newValue }]);
4✔
3043
                window.requestAnimationFrame(() => {
4✔
3044
                    gridRef.current?.damage([
4✔
3045
                        {
4✔
3046
                            cell: overlay.cell,
4✔
3047
                        },
4✔
3048
                    ]);
4✔
3049
                });
4✔
3050
            }
4✔
3051
            focus(true);
12✔
3052
            setOverlay(undefined);
12✔
3053

12✔
3054
            const [movX, movY] = movement;
12✔
3055
            if (gridSelection.current !== undefined && (movX !== 0 || movY !== 0)) {
12✔
3056
                const isEditingTrailingRow =
3✔
3057
                    gridSelection.current.cell[1] === mangledRows - 1 && newValue !== undefined;
3!
3058
                const isEditingTrailingCol =
3✔
3059
                    gridSelection.current.cell[0] === mangledCols.length - 1 && newValue !== undefined;
3!
3060
                let updateSelected = true;
3✔
3061
                if (isEditingTrailingRow && movY === 1) {
3!
NEW
3062
                    updateSelected = false;
×
NEW
3063
                    const col = gridSelection.current.cell[0] + movX;
×
NEW
3064
                    const customTargetColumn = getCustomNewRowTargetColumn(col);
×
NEW
3065
                    void appendRow(customTargetColumn ?? col, false);
×
NEW
3066
                }
×
3067
                if (isEditingTrailingCol && movX === 1) {
3!
NEW
3068
                    updateSelected = false;
×
NEW
3069
                    const row = gridSelection.current.cell[1] + movY;
×
NEW
3070
                    void appendColumn(row, false);
×
NEW
3071
                }
×
3072
                if (updateSelected) {
3✔
3073
                    updateSelectedCell(
3✔
3074
                        clamp(gridSelection.current.cell[0] + movX, 0, mangledCols.length - 1),
3✔
3075
                        clamp(gridSelection.current.cell[1] + movY, 0, mangledRows - 1),
3✔
3076
                        isEditingTrailingRow,
3✔
3077
                        false
3✔
3078
                    );
3✔
3079
                }
3✔
3080
            }
3✔
3081
            onFinishedEditing?.(newValue, movement);
12✔
3082
        },
12✔
3083
        [
742✔
3084
            overlay?.cell,
742✔
3085
            focus,
742✔
3086
            gridSelection,
742✔
3087
            onFinishedEditing,
742✔
3088
            mangledOnCellsEdited,
742✔
3089
            mangledRows,
742✔
3090
            updateSelectedCell,
742✔
3091
            mangledCols.length,
742✔
3092
        ]
742✔
3093
    );
742✔
3094

742✔
3095
    const overlayID = React.useMemo(() => {
742✔
3096
        return `gdg-overlay-${idCounter++}`;
151✔
3097
    }, []);
742✔
3098

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

742✔
3137
    const overlayOpen = overlay !== undefined;
742✔
3138

742✔
3139
    const handleFixedKeybindings = React.useCallback(
742✔
3140
        (event: GridKeyEventArgs): boolean => {
742✔
3141
            const cancel = () => {
74✔
3142
                event.stopPropagation();
50✔
3143
                event.preventDefault();
50✔
3144
            };
50✔
3145

74✔
3146
            const details = {
74✔
3147
                didMatch: false,
74✔
3148
            };
74✔
3149

74✔
3150
            const { bounds } = event;
74✔
3151
            const selectedColumns = gridSelection.columns;
74✔
3152
            const selectedRows = gridSelection.rows;
74✔
3153

74✔
3154
            const keys = keybindings;
74✔
3155

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

8✔
3185
                    // delete order:
8✔
3186
                    // 1) primary range
8✔
3187
                    // 2) secondary ranges
8✔
3188
                    // 3) columns
8✔
3189
                    // 4) rows
8✔
3190

8✔
3191
                    if (toDelete.current !== undefined) {
8✔
3192
                        deleteRange(toDelete.current.range);
5✔
3193
                        for (const r of toDelete.current.rangeStack) {
5!
UNCOV
3194
                            deleteRange(r);
×
UNCOV
3195
                        }
×
3196
                    }
5✔
3197

8✔
3198
                    for (const r of toDelete.rows) {
8✔
3199
                        deleteRange({
1✔
3200
                            x: rowMarkerOffset,
1✔
3201
                            y: r,
1✔
3202
                            width: columnsIn.length,
1✔
3203
                            height: 1,
1✔
3204
                        });
1✔
3205
                    }
1✔
3206

8✔
3207
                    for (const col of toDelete.columns) {
8✔
3208
                        deleteRange({
1✔
3209
                            x: col,
1✔
3210
                            y: 0,
1✔
3211
                            width: 1,
1✔
3212
                            height: rows,
1✔
3213
                        });
1✔
3214
                    }
1✔
3215
                }
8✔
3216
            }
8✔
3217

74✔
3218
            if (details.didMatch) {
74✔
3219
                cancel();
11✔
3220
                return true;
11✔
3221
            }
11✔
3222

63✔
3223
            if (gridSelection.current === undefined) return false;
74✔
3224
            let [col, row] = gridSelection.current.cell;
60✔
3225
            const [, startRow] = gridSelection.current.cell;
60✔
3226
            let freeMove = false;
60✔
3227
            let cancelOnlyOnMove = false;
60✔
3228

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

4✔
3337
                if (isHotkey(keys.acceptOverlayDown, event, details)) {
4✔
3338
                    setOverlay(undefined);
2✔
3339
                    row++;
2✔
3340
                }
2✔
3341

4✔
3342
                if (isHotkey(keys.acceptOverlayUp, event, details)) {
4!
UNCOV
3343
                    setOverlay(undefined);
×
UNCOV
3344
                    row--;
×
UNCOV
3345
                }
×
3346

4✔
3347
                if (isHotkey(keys.acceptOverlayLeft, event, details)) {
4!
3348
                    setOverlay(undefined);
×
3349
                    col--;
×
UNCOV
3350
                }
×
3351

4✔
3352
                if (isHotkey(keys.acceptOverlayRight, event, details)) {
4!
3353
                    setOverlay(undefined);
×
3354
                    col++;
×
UNCOV
3355
                }
×
3356
            }
4✔
3357
            // #endregion
60✔
3358

60✔
3359
            const mustRestrictRow = rowGroupingNavBehavior !== undefined && rowGroupingNavBehavior !== "normal";
74!
3360

74✔
3361
            if (mustRestrictRow && row !== startRow) {
74!
UNCOV
3362
                const skipUp =
×
UNCOV
3363
                    rowGroupingNavBehavior === "skip-up" ||
×
UNCOV
3364
                    rowGroupingNavBehavior === "skip" ||
×
UNCOV
3365
                    rowGroupingNavBehavior === "block";
×
3366
                const skipDown =
×
3367
                    rowGroupingNavBehavior === "skip-down" ||
×
3368
                    rowGroupingNavBehavior === "skip" ||
×
3369
                    rowGroupingNavBehavior === "block";
×
3370
                const didMoveUp = row < startRow;
×
3371
                if (didMoveUp && skipUp) {
×
3372
                    while (row >= 0 && mapper(row).isGroupHeader) {
×
3373
                        row--;
×
3374
                    }
×
3375

×
3376
                    if (row < 0) {
×
3377
                        row = startRow;
×
3378
                    }
×
3379
                } else if (!didMoveUp && skipDown) {
×
3380
                    while (row < rows && mapper(row).isGroupHeader) {
×
3381
                        row++;
×
3382
                    }
×
3383

×
3384
                    if (row >= rows) {
×
3385
                        row = startRow;
×
3386
                    }
×
3387
                }
×
3388
            }
✔
3389

60✔
3390
            const moved = updateSelectedCell(col, row, false, freeMove);
60✔
3391

60✔
3392
            const didMatch = details.didMatch;
60✔
3393

60✔
3394
            if (didMatch && (moved || !cancelOnlyOnMove || trapFocus)) {
74✔
3395
                cancel();
39✔
3396
            }
39✔
3397

60✔
3398
            return didMatch;
60✔
3399
        },
74✔
3400
        [
742✔
3401
            rowGroupingNavBehavior,
742✔
3402
            overlayOpen,
742✔
3403
            gridSelection,
742✔
3404
            keybindings,
742✔
3405
            columnSelect,
742✔
3406
            rowSelect,
742✔
3407
            rangeSelect,
742✔
3408
            rowMarkerOffset,
742✔
3409
            mapper,
742✔
3410
            rows,
742✔
3411
            updateSelectedCell,
742✔
3412
            setGridSelection,
742✔
3413
            onSelectionCleared,
742✔
3414
            columnsIn.length,
742✔
3415
            onDelete,
742✔
3416
            trapFocus,
742✔
3417
            deleteRange,
742✔
3418
            setSelectedColumns,
742✔
3419
            setSelectedRows,
742✔
3420
            showTrailingBlankRow,
742✔
3421
            getCustomNewRowTargetColumn,
742✔
3422
            appendRow,
742✔
3423
            onCellActivated,
742✔
3424
            reselect,
742✔
3425
            fillDown,
742✔
3426
            fillRight,
742✔
3427
            adjustSelection,
742✔
3428
        ]
742✔
3429
    );
742✔
3430

742✔
3431
    const onKeyDown = React.useCallback(
742✔
3432
        (event: GridKeyEventArgs) => {
742✔
3433
            let cancelled = false;
74✔
3434
            if (onKeyDownIn !== undefined) {
74✔
3435
                onKeyDownIn({
1✔
3436
                    ...event,
1✔
3437
                    ...(event.location && {
1✔
3438
                        location: [event.location[0] - rowMarkerOffset, event.location[1]] as any,
1✔
3439
                    }),
1✔
3440
                    cancel: () => {
1✔
UNCOV
3441
                        cancelled = true;
×
UNCOV
3442
                    },
×
3443
                });
1✔
3444
            }
1✔
3445

74✔
3446
            if (cancelled) return;
74!
3447

74✔
3448
            if (handleFixedKeybindings(event)) return;
74✔
3449

16✔
3450
            if (gridSelection.current === undefined) return;
16✔
3451
            const [col, row] = gridSelection.current.cell;
13✔
3452
            const vr = visibleRegionRef.current;
13✔
3453

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

742✔
3490
    const onContextMenu = React.useCallback(
742✔
3491
        (args: GridMouseEventArgs, preventDefault: () => void) => {
742✔
3492
            const adjustedCol = args.location[0] - rowMarkerOffset;
7✔
3493
            if (args.kind === "header") {
7!
UNCOV
3494
                onHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
UNCOV
3495
            }
×
3496

7✔
3497
            if (args.kind === groupHeaderKind) {
7!
3498
                if (adjustedCol < 0) {
×
3499
                    return;
×
UNCOV
3500
                }
×
UNCOV
3501
                onGroupHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
3502
            }
×
3503

7✔
3504
            if (args.kind === "cell") {
7✔
3505
                const [col, row] = args.location;
7✔
3506
                onCellContextMenu?.([adjustedCol, row], {
7✔
3507
                    ...args,
7✔
3508
                    preventDefault,
7✔
3509
                });
7✔
3510

7✔
3511
                if (!gridSelectionHasItem(gridSelection, args.location)) {
7✔
3512
                    updateSelectedCell(col, row, false, false);
3✔
3513
                }
3✔
3514
            }
7✔
3515
        },
7✔
3516
        [
742✔
3517
            gridSelection,
742✔
3518
            onCellContextMenu,
742✔
3519
            onGroupHeaderContextMenu,
742✔
3520
            onHeaderContextMenu,
742✔
3521
            rowMarkerOffset,
742✔
3522
            updateSelectedCell,
742✔
3523
        ]
742✔
3524
    );
742✔
3525

742✔
3526
    const onPasteInternal = React.useCallback(
742✔
3527
        async (e?: ClipboardEvent) => {
742✔
3528
            if (!keybindings.paste) return;
6!
3529
            function pasteToCell(
6✔
3530
                inner: InnerGridCell,
51✔
3531
                target: Item,
51✔
3532
                rawValue: string | boolean | string[] | number | boolean | BooleanEmpty | BooleanIndeterminate,
51✔
3533
                formatted?: string | string[]
51✔
3534
            ): EditListItem | undefined {
51✔
3535
                const stringifiedRawValue =
51✔
3536
                    typeof rawValue === "object" ? rawValue?.join("\n") ?? "" : rawValue?.toString() ?? "";
51!
3537

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

6✔
3583
            const selectedColumns = gridSelection.columns;
6✔
3584
            const selectedRows = gridSelection.rows;
6✔
3585
            const focused =
6✔
3586
                scrollRef.current?.contains(document.activeElement) === true ||
6✔
3587
                canvasRef.current?.contains(document.activeElement) === true;
6✔
3588

6✔
3589
            let target: Item | undefined;
6✔
3590

6✔
3591
            if (gridSelection.current !== undefined) {
6✔
3592
                target = [gridSelection.current.range.x, gridSelection.current.range.y];
5✔
3593
            } else if (selectedColumns.length === 1) {
6!
UNCOV
3594
                target = [selectedColumns.first() ?? 0, 0];
×
3595
            } else if (selectedRows.length === 1) {
1!
UNCOV
3596
                target = [rowMarkerOffset, selectedRows.first() ?? 0];
×
UNCOV
3597
            }
×
3598

6✔
3599
            if (focused && target !== undefined) {
6✔
3600
                let data: CopyBuffer | undefined;
5✔
3601
                let text: string | undefined;
5✔
3602

5✔
3603
                const textPlain = "text/plain";
5✔
3604
                const textHtml = "text/html";
5✔
3605

5✔
3606
                if (navigator.clipboard.read !== undefined) {
5!
UNCOV
3607
                    const clipboardContent = await navigator.clipboard.read();
×
UNCOV
3608

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

5✔
3638
                const [targetCol, targetRow] = target;
5✔
3639

5✔
3640
                const editList: EditListItem[] = [];
5✔
3641
                do {
5✔
3642
                    if (onPaste === undefined) {
5✔
3643
                        const cellData = getMangledCellContent(target);
2✔
3644
                        const rawValue = text ?? data?.map(r => r.map(cb => cb.rawValue).join("\t")).join("\t") ?? "";
2!
3645
                        const newVal = pasteToCell(cellData, target, rawValue, undefined);
2✔
3646
                        if (newVal !== undefined) {
2✔
3647
                            editList.push(newVal);
1✔
3648
                        }
1✔
3649
                        break;
2✔
3650
                    }
2✔
3651

3✔
3652
                    if (data === undefined) {
3✔
3653
                        if (text === undefined) return;
3!
3654
                        data = unquote(text);
3✔
3655
                    }
3✔
3656

3✔
3657
                    if (
3✔
3658
                        onPaste === false ||
3✔
3659
                        (typeof onPaste === "function" &&
3✔
3660
                            onPaste?.(
2✔
3661
                                [target[0] - rowMarkerOffset, target[1]],
2✔
3662
                                data.map(r => r.map(cb => cb.rawValue?.toString() ?? ""))
2!
3663
                            ) !== true)
2✔
3664
                    ) {
5!
UNCOV
3665
                        return;
×
UNCOV
3666
                    }
✔
3667

3✔
3668
                    for (const [row, dataRow] of data.entries()) {
5✔
3669
                        if (row + targetRow >= rows) break;
21!
3670
                        for (const [col, dataItem] of dataRow.entries()) {
21✔
3671
                            const index = [col + targetCol, row + targetRow] as const;
63✔
3672
                            const [writeCol, writeRow] = index;
63✔
3673
                            if (writeCol >= mangledCols.length) continue;
63✔
3674
                            if (writeRow >= mangledRows) continue;
49!
3675
                            const cellData = getMangledCellContent(index);
49✔
3676
                            const newVal = pasteToCell(cellData, index, dataItem.rawValue, dataItem.formatted);
49✔
3677
                            if (newVal !== undefined) {
63✔
3678
                                editList.push(newVal);
35✔
3679
                            }
35✔
3680
                        }
63✔
3681
                    }
21✔
3682
                    // eslint-disable-next-line no-constant-condition
3✔
3683
                } while (false);
5✔
3684

5✔
3685
                mangledOnCellsEdited(editList);
5✔
3686

5✔
3687
                gridRef.current?.damage(
5✔
3688
                    editList.map(c => ({
5✔
3689
                        cell: c.location,
36✔
3690
                    }))
5✔
3691
                );
5✔
3692
            }
5✔
3693
        },
6✔
3694
        [
742✔
3695
            coercePasteValue,
742✔
3696
            getCellRenderer,
742✔
3697
            getMangledCellContent,
742✔
3698
            gridSelection,
742✔
3699
            keybindings.paste,
742✔
3700
            scrollRef,
742✔
3701
            mangledCols.length,
742✔
3702
            mangledOnCellsEdited,
742✔
3703
            mangledRows,
742✔
3704
            onPaste,
742✔
3705
            rowMarkerOffset,
742✔
3706
            rows,
742✔
3707
        ]
742✔
3708
    );
742✔
3709

742✔
3710
    useEventListener("paste", onPasteInternal, safeWindow, false, true);
742✔
3711

742✔
3712
    // While this function is async, we deeply prefer not to await if we don't have to. This will lead to unpacking
742✔
3713
    // promises in rather awkward ways when possible to avoid awaiting. We have to use fallback copy mechanisms when
742✔
3714
    // an await has happened.
742✔
3715
    const onCopy = React.useCallback(
742✔
3716
        async (e?: ClipboardEvent, ignoreFocus?: boolean) => {
742✔
3717
            if (!keybindings.copy) return;
6!
3718
            const focused =
6✔
3719
                ignoreFocus === true ||
6✔
3720
                scrollRef.current?.contains(document.activeElement) === true ||
5✔
3721
                canvasRef.current?.contains(document.activeElement) === true;
5✔
3722

6✔
3723
            const selectedColumns = gridSelection.columns;
6✔
3724
            const selectedRows = gridSelection.rows;
6✔
3725

6✔
3726
            const copyToClipboardWithHeaders = (
6✔
3727
                cells: readonly (readonly GridCell[])[],
5✔
3728
                columnIndexes: readonly number[]
5✔
3729
            ) => {
5✔
3730
                if (!copyHeaders) {
5✔
3731
                    copyToClipboard(cells, columnIndexes, e);
5✔
3732
                } else {
5!
UNCOV
3733
                    const headers = columnIndexes.map(index => ({
×
UNCOV
3734
                        kind: GridCellKind.Text,
×
UNCOV
3735
                        data: columnsIn[index].title,
×
UNCOV
3736
                        displayData: columnsIn[index].title,
×
3737
                        allowOverlay: false,
×
3738
                    })) as GridCell[];
×
3739
                    copyToClipboard([headers, ...cells], columnIndexes, e);
×
3740
                }
×
3741
            };
5✔
3742

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

742✔
3820
    useEventListener("copy", onCopy, safeWindow, false, false);
742✔
3821

742✔
3822
    const onCut = React.useCallback(
742✔
3823
        async (e?: ClipboardEvent) => {
742✔
3824
            if (!keybindings.cut) return;
1!
3825
            const focused =
1✔
3826
                scrollRef.current?.contains(document.activeElement) === true ||
1✔
3827
                canvasRef.current?.contains(document.activeElement) === true;
1✔
3828

1✔
3829
            if (!focused) return;
1!
3830
            await onCopy(e);
1✔
3831
            if (gridSelection.current !== undefined) {
1✔
3832
                let effectiveSelection: GridSelection = {
1✔
3833
                    current: {
1✔
3834
                        cell: gridSelection.current.cell,
1✔
3835
                        range: gridSelection.current.range,
1✔
3836
                        rangeStack: [],
1✔
3837
                    },
1✔
3838
                    rows: CompactSelection.empty(),
1✔
3839
                    columns: CompactSelection.empty(),
1✔
3840
                };
1✔
3841
                const onDeleteResult = onDelete?.(effectiveSelection);
1✔
3842
                if (onDeleteResult === false) return;
1!
3843
                effectiveSelection = onDeleteResult === true ? effectiveSelection : onDeleteResult;
1!
3844
                if (effectiveSelection.current === undefined) return;
1!
3845
                deleteRange(effectiveSelection.current.range);
1✔
3846
            }
1✔
3847
        },
1✔
3848
        [deleteRange, gridSelection, keybindings.cut, onCopy, scrollRef, onDelete]
742✔
3849
    );
742✔
3850

742✔
3851
    useEventListener("cut", onCut, safeWindow, false, false);
742✔
3852

742✔
3853
    const onSearchResultsChanged = React.useCallback(
742✔
3854
        (results: readonly Item[], navIndex: number) => {
742✔
3855
            if (onSearchResultsChangedIn !== undefined) {
7!
UNCOV
3856
                if (rowMarkerOffset !== 0) {
×
UNCOV
3857
                    results = results.map(item => [item[0] - rowMarkerOffset, item[1]]);
×
UNCOV
3858
                }
×
UNCOV
3859
                onSearchResultsChangedIn(results, navIndex);
×
3860
                return;
×
3861
            }
×
3862
            if (results.length === 0 || navIndex === -1) return;
7✔
3863

2✔
3864
            const [col, row] = results[navIndex];
2✔
3865
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
7!
UNCOV
3866
                return;
×
UNCOV
3867
            }
✔
3868
            lastSent.current = [col, row];
2✔
3869
            updateSelectedCell(col, row, false, false);
2✔
3870
        },
7✔
3871
        [onSearchResultsChangedIn, rowMarkerOffset, updateSelectedCell]
742✔
3872
    );
742✔
3873

742✔
3874
    // this effects purpose in life is to scroll the newly selected cell into view when and ONLY when that cell
742✔
3875
    // is from an external gridSelection change. Also note we want the unmangled out selection because scrollTo
742✔
3876
    // expects unmangled indexes
742✔
3877
    const [outCol, outRow] = gridSelectionOuter?.current?.cell ?? [];
742✔
3878
    const scrollToRef = React.useRef(scrollTo);
742✔
3879
    scrollToRef.current = scrollTo;
742✔
3880
    React.useLayoutEffect(() => {
742✔
3881
        if (
237✔
3882
            scrollToActiveCellRef.current &&
237✔
3883
            !hasJustScrolled.current &&
237✔
3884
            outCol !== undefined &&
237✔
3885
            outRow !== undefined &&
90✔
3886
            (outCol !== expectedExternalGridSelection.current?.current?.cell[0] ||
90✔
3887
                outRow !== expectedExternalGridSelection.current?.current?.cell[1])
90✔
3888
        ) {
237!
UNCOV
3889
            scrollToRef.current(outCol, outRow);
×
UNCOV
3890
        }
×
3891
        hasJustScrolled.current = false; //only allow skipping a single scroll
237✔
3892
    }, [outCol, outRow]);
742✔
3893

742✔
3894
    const selectionOutOfBounds =
742✔
3895
        gridSelection.current !== undefined &&
742✔
3896
        (gridSelection.current.cell[0] >= mangledCols.length || gridSelection.current.cell[1] >= mangledRows);
366✔
3897
    React.useLayoutEffect(() => {
742✔
3898
        if (selectionOutOfBounds) {
161✔
3899
            setGridSelection(emptyGridSelection, false);
1✔
3900
        }
1✔
3901
    }, [selectionOutOfBounds, setGridSelection]);
742✔
3902

742✔
3903
    const disabledRows = React.useMemo(() => {
742✔
3904
        if (showTrailingBlankRow === true && trailingRowOptions?.tint === true) {
154✔
3905
            return CompactSelection.fromSingleSelection(mangledRows - 1);
148✔
3906
        }
148✔
3907
        return CompactSelection.empty();
6✔
3908
    }, [mangledRows, showTrailingBlankRow, trailingRowOptions?.tint]);
742✔
3909

742✔
3910
    const mangledVerticalBorder = React.useCallback(
742✔
3911
        (col: number) => {
742✔
3912
            return typeof verticalBorder === "boolean"
8,093!
UNCOV
3913
                ? verticalBorder
×
3914
                : verticalBorder?.(col - rowMarkerOffset) ?? true;
8,093!
3915
        },
8,093✔
3916
        [rowMarkerOffset, verticalBorder]
742✔
3917
    );
742✔
3918

742✔
3919
    const renameGroupNode = React.useMemo(() => {
742✔
3920
        if (renameGroup === undefined || canvasRef.current === null) return null;
154✔
3921
        const { bounds, group } = renameGroup;
2✔
3922
        const canvasBounds = canvasRef.current.getBoundingClientRect();
2✔
3923
        return (
2✔
3924
            <GroupRename
2✔
3925
                bounds={bounds}
2✔
3926
                group={group}
2✔
3927
                canvasBounds={canvasBounds}
2✔
3928
                onClose={() => setRenameGroup(undefined)}
2✔
3929
                onFinish={newVal => {
2✔
3930
                    setRenameGroup(undefined);
1✔
3931
                    onGroupHeaderRenamed?.(group, newVal);
1✔
3932
                }}
1✔
3933
            />
2✔
3934
        );
154✔
3935
    }, [onGroupHeaderRenamed, renameGroup]);
742✔
3936

742✔
3937
    const mangledFreezeColumns = Math.min(mangledCols.length, freezeColumns + (hasRowMarkers ? 1 : 0));
742✔
3938

742✔
3939
    React.useImperativeHandle(
742✔
3940
        forwardedRef,
742✔
3941
        () => ({
742✔
3942
            appendRow: (col: number, openOverlay?: boolean) => appendRow(col + rowMarkerOffset, openOverlay),
30✔
3943
            appendColumn: (row: number, openOverlay?: boolean) => appendColumn(row, openOverlay),
30✔
3944
            updateCells: damageList => {
30✔
3945
                if (rowMarkerOffset !== 0) {
2✔
3946
                    damageList = damageList.map(x => ({ cell: [x.cell[0] + rowMarkerOffset, x.cell[1]] }));
1✔
3947
                }
1✔
3948
                return gridRef.current?.damage(damageList);
2✔
3949
            },
2✔
3950
            getBounds: (col, row) => {
30✔
3951
                if (canvasRef?.current === null || scrollRef?.current === null) {
2!
UNCOV
3952
                    return undefined;
×
UNCOV
3953
                }
×
3954

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

×
4042
                const args = gridRef.current.getMouseArgsForPosition(posX, posY, ev);
×
4043
                if (args === undefined) {
×
4044
                    return undefined;
×
4045
                }
×
4046

×
4047
                return {
×
4048
                    ...args,
×
4049
                    location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
×
4050
                };
×
4051
            },
×
4052
        }),
30✔
4053
        [appendRow, appendColumn, normalSizeColumn, scrollRef, onCopy, onKeyDown, onPasteInternal, rowMarkerOffset, scrollTo]
742✔
4054
    );
742✔
4055

742✔
4056
    const [selCol, selRow] = currentCell ?? [];
742✔
4057
    const onCellFocused = React.useCallback(
742✔
4058
        (cell: Item) => {
742✔
4059
            const [col, row] = cell;
30✔
4060

30✔
4061
            if (row === -1) {
30!
4062
                if (columnSelect !== "none") {
×
4063
                    setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, false);
×
4064
                    focus();
×
4065
                }
×
4066
                return;
×
4067
            }
×
4068

30✔
4069
            if (selCol === col && selRow === row) return;
30✔
4070
            setCurrent(
1✔
4071
                {
1✔
4072
                    cell,
1✔
4073
                    range: { x: col, y: row, width: 1, height: 1 },
1✔
4074
                },
1✔
4075
                true,
1✔
4076
                false,
1✔
4077
                "keyboard-nav"
1✔
4078
            );
1✔
4079
            scrollTo(col, row);
1✔
4080
        },
30✔
4081
        [columnSelect, focus, scrollTo, selCol, selRow, setCurrent, setSelectedColumns]
742✔
4082
    );
742✔
4083

742✔
4084
    const [isFocused, setIsFocused] = React.useState(false);
742✔
4085
    const setIsFocusedDebounced = React.useRef(
742✔
4086
        debounce((val: boolean) => {
742✔
4087
            setIsFocused(val);
57✔
4088
        }, 5)
742✔
4089
    );
742✔
4090

742✔
4091
    const onCanvasFocused = React.useCallback(() => {
742✔
4092
        setIsFocusedDebounced.current(true);
76✔
4093

76✔
4094
        // check for mouse state, don't do anything if the user is clicked to focus.
76✔
4095
        if (
76✔
4096
            gridSelection.current === undefined &&
76✔
4097
            gridSelection.columns.length === 0 &&
6✔
4098
            gridSelection.rows.length === 0 &&
5✔
4099
            mouseState === undefined
5✔
4100
        ) {
76✔
4101
            setCurrent(
5✔
4102
                {
5✔
4103
                    cell: [rowMarkerOffset, cellYOffset],
5✔
4104
                    range: {
5✔
4105
                        x: rowMarkerOffset,
5✔
4106
                        y: cellYOffset,
5✔
4107
                        width: 1,
5✔
4108
                        height: 1,
5✔
4109
                    },
5✔
4110
                },
5✔
4111
                true,
5✔
4112
                false,
5✔
4113
                "keyboard-select"
5✔
4114
            );
5✔
4115
        }
5✔
4116
    }, [cellYOffset, gridSelection, mouseState, rowMarkerOffset, setCurrent]);
742✔
4117

742✔
4118
    const onFocusOut = React.useCallback(() => {
742✔
4119
        setIsFocusedDebounced.current(false);
39✔
4120
    }, []);
742✔
4121

742✔
4122
    const [idealWidth, idealHeight] = React.useMemo(() => {
742✔
4123
        let h: number;
168✔
4124
        const scrollbarWidth = experimental?.scrollbarWidthOverride ?? getScrollBarWidth();
168✔
4125
        const rowsCountWithTrailingRow = rows + (showTrailingBlankRow ? 1 : 0);
168✔
4126
        if (typeof rowHeight === "number") {
168✔
4127
            h = totalHeaderHeight + rowsCountWithTrailingRow * rowHeight;
167✔
4128
        } else {
168✔
4129
            let avg = 0;
1✔
4130
            const toAverage = Math.min(rowsCountWithTrailingRow, 10);
1✔
4131
            for (let i = 0; i < toAverage; i++) {
1✔
4132
                avg += rowHeight(i);
10✔
4133
            }
10✔
4134
            avg = Math.floor(avg / toAverage);
1✔
4135

1✔
4136
            h = totalHeaderHeight + rowsCountWithTrailingRow * avg;
1✔
4137
        }
1✔
4138
        h += scrollbarWidth;
168✔
4139

168✔
4140
        const w = mangledCols.reduce((acc, x) => x.width + acc, 0) + scrollbarWidth;
168✔
4141

168✔
4142
        // We need to set a reasonable cap here as some browsers will just ignore huge values
168✔
4143
        // rather than treat them as huge values.
168✔
4144
        return [`${Math.min(100_000, w)}px`, `${Math.min(100_000, h)}px`];
168✔
4145
    }, [mangledCols, experimental?.scrollbarWidthOverride, rowHeight, rows, showTrailingBlankRow, totalHeaderHeight]);
742✔
4146

742✔
4147
    const cssStyle = React.useMemo(() => {
742✔
4148
        return makeCSSStyle(mergedTheme);
151✔
4149
    }, [mergedTheme]);
742✔
4150

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

1✔
4272
/**
1✔
4273
 * The primary component of Glide Data Grid.
1✔
4274
 * @category DataEditor
1✔
4275
 * @param {DataEditorProps} props
1✔
4276
 */
1✔
4277
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