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

glideapps / glide-data-grid / 6998620881

26 Nov 2023 11:15PM UTC coverage: 91.226% (+4.8%) from 86.42%
6998620881

Pull #810

github

jassmith
5.99.9-alpha1
Pull Request #810: 6.0.0

2445 of 3036 branches covered (0.0%)

293 of 303 new or added lines in 50 files covered. (96.7%)

286 existing lines in 12 files now uncovered.

15013 of 16457 relevant lines covered (91.23%)

2925.61 hits per line

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

88.88
/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 DataGridOverlayEditor from "../internal/data-grid-overlay-editor/data-grid-overlay-editor.js";
1✔
10
import {
1✔
11
    type EditableGridCell,
1✔
12
    type GridCell,
1✔
13
    GridCellKind,
1✔
14
    type GridDragEventArgs,
1✔
15
    type GridKeyEventArgs,
1✔
16
    type GridMouseEventArgs,
1✔
17
    type GridSelection,
1✔
18
    isEditableGridCell,
1✔
19
    type Rectangle,
1✔
20
    isReadWriteCell,
1✔
21
    type InnerGridCell,
1✔
22
    InnerGridCellKind,
1✔
23
    CompactSelection,
1✔
24
    type Slice,
1✔
25
    isInnerOnlyCell,
1✔
26
    type ProvideEditorCallback,
1✔
27
    type DrawCustomCellCallback,
1✔
28
    type GridMouseCellEventArgs,
1✔
29
    type GridColumn,
1✔
30
    isObjectEditorCallbackResult,
1✔
31
    type GroupHeaderClickedEventArgs,
1✔
32
    type HeaderClickedEventArgs,
1✔
33
    type CellClickedEventArgs,
1✔
34
    type Item,
1✔
35
    type MarkerCell,
1✔
36
    headerCellUnheckedMarker,
1✔
37
    headerCellCheckedMarker,
1✔
38
    headerCellIndeterminateMarker,
1✔
39
    groupHeaderKind,
1✔
40
    outOfBoundsKind,
1✔
41
    type ValidatedGridCell,
1✔
42
    type ImageEditorType,
1✔
43
    type CustomCell,
1✔
44
    headerKind,
1✔
45
    gridSelectionHasItem,
1✔
46
    BooleanEmpty,
1✔
47
    BooleanIndeterminate,
1✔
48
} from "../internal/data-grid/data-grid-types.js";
1✔
49
import DataGridSearch, { type DataGridSearchProps } from "../internal/data-grid-search/data-grid-search.js";
1✔
50
import { browserIsOSX } from "../common/browser-detect.js";
1✔
51
import { getDataEditorTheme, makeCSSStyle, type Theme, ThemeContext } from "../common/styles.js";
1✔
52
import type { DataGridRef } from "../internal/data-grid/data-grid.js";
1✔
53
import { getScrollBarWidth, useEventListener, useStateWithReactiveInput, whenDefined } from "../common/utils.js";
1✔
54
import { isGroupEqual } from "../internal/data-grid/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 } from "./data-editor-fns.js";
1✔
61
import { DataEditorContainer } from "../internal/data-editor-container/data-grid-container.js";
1✔
62
import { toggleBoolean } from "../cells/boolean-cell.js";
1✔
63
import { useAutoscroll } from "./use-autoscroll.js";
1✔
64
import type { CustomRenderer, CellRenderer, InternalCellRenderer } from "../cells/cell-types.js";
1✔
65
import { decodeHTML, type CopyBuffer } from "./copy-paste.js";
1✔
66
import { useRemAdjuster } from "./use-rem-adjuster.js";
1✔
67

1✔
68
let idCounter = 0;
1✔
69

1✔
70
interface MouseState {
1✔
71
    readonly previousSelection?: GridSelection;
1✔
72
    readonly fillHandle?: boolean;
1✔
73
}
1✔
74

1✔
75
type Props = Partial<
1✔
76
    Omit<
1✔
77
        DataGridSearchProps,
1✔
78
        | "accessibilityHeight"
1✔
79
        | "canvasRef"
1✔
80
        | "cellXOffset"
1✔
81
        | "cellYOffset"
1✔
82
        | "className"
1✔
83
        | "clientSize"
1✔
84
        | "columns"
1✔
85
        | "disabledRows"
1✔
86
        | "drawCustomCell"
1✔
87
        | "enableGroups"
1✔
88
        | "firstColAccessible"
1✔
89
        | "firstColSticky"
1✔
90
        | "freezeColumns"
1✔
91
        | "getCellContent"
1✔
92
        | "getCellRenderer"
1✔
93
        | "getCellsForSelection"
1✔
94
        | "gridRef"
1✔
95
        | "groupHeaderHeight"
1✔
96
        | "headerHeight"
1✔
97
        | "isFilling"
1✔
98
        | "isFocused"
1✔
99
        | "lockColumns"
1✔
100
        | "maxColumnWidth"
1✔
101
        | "minColumnWidth"
1✔
102
        | "onCanvasBlur"
1✔
103
        | "onCanvasFocused"
1✔
104
        | "onCellFocused"
1✔
105
        | "onContextMenu"
1✔
106
        | "onDragEnd"
1✔
107
        | "onMouseDown"
1✔
108
        | "onMouseMove"
1✔
109
        | "onMouseUp"
1✔
110
        | "onVisibleRegionChanged"
1✔
111
        | "rowHeight"
1✔
112
        | "rows"
1✔
113
        | "scrollRef"
1✔
114
        | "searchInputRef"
1✔
115
        | "selectedColumns"
1✔
116
        | "selection"
1✔
117
        | "theme"
1✔
118
        | "trailingRowType"
1✔
119
        | "translateX"
1✔
120
        | "translateY"
1✔
121
        | "verticalBorder"
1✔
122
    >
1✔
123
>;
1✔
124

1✔
125
type EditListItem = { location: Item; value: EditableGridCell };
1✔
126

1✔
127
type EmitEvents = "copy" | "paste" | "delete" | "fill-right" | "fill-down";
1✔
128

1✔
129
function getSpanStops(cells: readonly (readonly GridCell[])[]): number[] {
5✔
130
    return uniq(
5✔
131
        flatten(
5✔
132
            flatten(cells)
5✔
133
                .filter(c => c.span !== undefined)
5✔
134
                .map(c => range((c.span?.[0] ?? 0) + 1, (c.span?.[1] ?? 0) + 1))
5✔
135
        )
5✔
136
    );
5✔
137
}
5✔
138

1✔
139
function shiftSelection(input: GridSelection, offset: number): GridSelection {
279✔
140
    if (input === undefined || offset === 0 || (input.columns.length === 0 && input.current === undefined))
279✔
141
        return input;
279✔
142

35✔
143
    return {
35✔
144
        current:
35✔
145
            input.current === undefined
35✔
146
                ? undefined
1✔
147
                : {
34✔
148
                      cell: [input.current.cell[0] + offset, input.current.cell[1]],
34✔
149
                      range: {
34✔
150
                          ...input.current.range,
34✔
151
                          x: input.current.range.x + offset,
34✔
152
                      },
34✔
153
                      rangeStack: input.current.rangeStack.map(r => ({
34✔
UNCOV
154
                          ...r,
×
UNCOV
155
                          x: r.x + offset,
×
156
                      })),
34✔
157
                  },
34✔
158
        rows: input.rows,
279✔
159
        columns: input.columns.offset(offset),
279✔
160
    };
279✔
161
}
279✔
162

1✔
163
interface Keybinds {
1✔
164
    readonly selectAll: boolean;
1✔
165
    readonly selectRow: boolean;
1✔
166
    readonly selectColumn: boolean;
1✔
167
    readonly downFill: boolean;
1✔
168
    readonly rightFill: boolean;
1✔
169
    readonly pageUp: boolean;
1✔
170
    readonly pageDown: boolean;
1✔
171
    readonly clear: boolean;
1✔
172
    readonly copy: boolean;
1✔
173
    readonly paste: boolean;
1✔
174
    readonly cut: boolean;
1✔
175
    readonly search: boolean;
1✔
176
    readonly first: boolean;
1✔
177
    readonly last: boolean;
1✔
178
}
1✔
179

1✔
180
const keybindingDefaults: Keybinds = {
1✔
181
    selectAll: true,
1✔
182
    selectRow: true,
1✔
183
    selectColumn: true,
1✔
184
    downFill: false,
1✔
185
    rightFill: false,
1✔
186
    pageUp: false,
1✔
187
    pageDown: false,
1✔
188
    clear: true,
1✔
189
    copy: true,
1✔
190
    paste: true,
1✔
191
    cut: true,
1✔
192
    search: false,
1✔
193
    first: true,
1✔
194
    last: true,
1✔
195
};
1✔
196

1✔
197
/**
1✔
198
 * @category DataEditor
1✔
199
 */
1✔
200
export interface DataEditorProps extends Props {
1✔
201
    /** Emitted whenever the user has requested the deletion of the selection.
1✔
202
     * @group Editing
1✔
203
     */
1✔
204
    readonly onDelete?: (selection: GridSelection) => boolean | GridSelection;
1✔
205
    /** Emitted whenever a cell edit is completed.
1✔
206
     * @group Editing
1✔
207
     */
1✔
208
    readonly onCellEdited?: (cell: Item, newValue: EditableGridCell) => void;
1✔
209
    /** Emitted whenever a cell mutation is completed and provides all edits inbound as a single batch.
1✔
210
     * @group Editing
1✔
211
     */
1✔
212
    readonly onCellsEdited?: (newValues: readonly EditListItem[]) => boolean | void;
1✔
213
    /** Emitted whenever a row append operation is requested. Append location can be set in callback.
1✔
214
     * @group Editing
1✔
215
     */
1✔
216
    readonly onRowAppended?: () => Promise<"top" | "bottom" | number | undefined> | void;
1✔
217
    /** Emitted when a column header should show a context menu. Usually right click.
1✔
218
     * @group Events
1✔
219
     */
1✔
220
    readonly onHeaderClicked?: (colIndex: number, event: HeaderClickedEventArgs) => void;
1✔
221
    /** Emitted when a group header is clicked.
1✔
222
     * @group Events
1✔
223
     */
1✔
224
    readonly onGroupHeaderClicked?: (colIndex: number, event: GroupHeaderClickedEventArgs) => void;
1✔
225
    /** Emitted whe the user wishes to rename a group.
1✔
226
     * @group Events
1✔
227
     */
1✔
228
    readonly onGroupHeaderRenamed?: (groupName: string, newVal: string) => void;
1✔
229
    /** Emitted when a cell is clicked.
1✔
230
     * @group Events
1✔
231
     */
1✔
232
    readonly onCellClicked?: (cell: Item, event: CellClickedEventArgs) => void;
1✔
233
    /** Emitted when a cell is activated, by pressing Enter, Space or double clicking it.
1✔
234
     * @group Events
1✔
235
     */
1✔
236
    readonly onCellActivated?: (cell: Item) => void;
1✔
237
    /** Emitted when editing has finished, regardless of data changing or not.
1✔
238
     * @group Editing
1✔
239
     */
1✔
240
    readonly onFinishedEditing?: (newValue: GridCell | undefined, movement: Item) => void;
1✔
241
    /** Emitted when a column header should show a context menu. Usually right click.
1✔
242
     * @group Events
1✔
243
     */
1✔
244
    readonly onHeaderContextMenu?: (colIndex: number, event: HeaderClickedEventArgs) => void;
1✔
245
    /** Emitted when a group header should show a context menu. Usually right click.
1✔
246
     * @group Events
1✔
247
     */
1✔
248
    readonly onGroupHeaderContextMenu?: (colIndex: number, event: GroupHeaderClickedEventArgs) => void;
1✔
249
    /** Emitted when a cell should show a context menu. Usually right click.
1✔
250
     * @group Events
1✔
251
     */
1✔
252
    readonly onCellContextMenu?: (cell: Item, event: CellClickedEventArgs) => void;
1✔
253
    /** Used for validating cell values during editing.
1✔
254
     * @group Editing
1✔
255
     * @param cell The cell which is being validated.
1✔
256
     * @param newValue The new value being proposed.
1✔
257
     * @param prevValue The previous value before the edit.
1✔
258
     * @returns A return of false indicates the value will not be accepted. A value of
1✔
259
     * true indicates the value will be accepted. Returning a new GridCell will immediately coerce the value to match.
1✔
260
     */
1✔
261
    readonly validateCell?: (
1✔
262
        cell: Item,
1✔
263
        newValue: EditableGridCell,
1✔
264
        prevValue: GridCell
1✔
265
    ) => boolean | ValidatedGridCell;
1✔
266

1✔
267
    /** The columns to display in the data grid.
1✔
268
     * @group Data
1✔
269
     */
1✔
270
    readonly columns: readonly GridColumn[];
1✔
271

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

1✔
298
    /**
1✔
299
     * The number of rows in the grid.
1✔
300
     * @group Data
1✔
301
     */
1✔
302
    readonly rows: number;
1✔
303

1✔
304
    /** Determines if row markers should be automatically added to the grid.
1✔
305
     * Interactive row markers allow the user to select a row.
1✔
306
     *
1✔
307
     * - "clickable-number" renders a number that can be clicked to
1✔
308
     *   select the row
1✔
309
     * - "both" causes the row marker to show up as a number but
1✔
310
     *   reveal a checkbox when the marker is hovered.
1✔
311
     *
1✔
312
     * @defaultValue `none`
1✔
313
     * @group Style
1✔
314
     */
1✔
315
    readonly rowMarkers?: "checkbox" | "number" | "clickable-number" | "checkbox-visible" | "both" | "none";
1✔
316
    /**
1✔
317
     * Sets the width of row markers in pixels, if unset row markers will automatically size.
1✔
318
     * @group Style
1✔
319
     */
1✔
320
    readonly rowMarkerWidth?: number;
1✔
321
    /** Changes the starting index for row markers.
1✔
322
     * @defaultValue 1
1✔
323
     * @group Style
1✔
324
     */
1✔
325
    readonly rowMarkerStartIndex?: number;
1✔
326

1✔
327
    /** Changes the theme of the row marker column
1✔
328
     * @group Style
1✔
329
     */
1✔
330
    readonly rowMarkerTheme?: Partial<Theme>;
1✔
331

1✔
332
    /** Sets the width of the data grid.
1✔
333
     * @group Style
1✔
334
     */
1✔
335
    readonly width?: number | string;
1✔
336
    /** Sets the height of the data grid.
1✔
337
     * @group Style
1✔
338
     */
1✔
339
    readonly height?: number | string;
1✔
340
    /** Custom classname for data grid wrapper.
1✔
341
     * @group Style
1✔
342
     */
1✔
343
    readonly className?: string;
1✔
344

1✔
345
    /** If set to `default`, `gridSelection` will be coerced to always include full spans.
1✔
346
     * @group Selection
1✔
347
     * @defaultValue `default`
1✔
348
     */
1✔
349
    readonly spanRangeBehavior?: "default" | "allowPartial";
1✔
350

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

1✔
386
    /** Sets the initial scroll Y offset.
1✔
387
     * @see {@link scrollOffsetX}
1✔
388
     * @group Advanced
1✔
389
     */
1✔
390
    readonly scrollOffsetY?: number;
1✔
391
    /** Sets the initial scroll X offset
1✔
392
     * @see {@link scrollOffsetY}
1✔
393
     * @group Advanced
1✔
394
     */
1✔
395
    readonly scrollOffsetX?: number;
1✔
396

1✔
397
    /** Determins the height of each row.
1✔
398
     * @group Style
1✔
399
     * @defaultValue 34
1✔
400
     */
1✔
401
    readonly rowHeight?: DataGridSearchProps["rowHeight"];
1✔
402
    /** Fires whenever the mouse moves
1✔
403
     * @group Events
1✔
404
     * @param args
1✔
405
     */
1✔
406
    readonly onMouseMove?: DataGridSearchProps["onMouseMove"];
1✔
407

1✔
408
    /**
1✔
409
     * The minimum width a column can be resized to.
1✔
410
     * @defaultValue 50
1✔
411
     * @group Style
1✔
412
     */
1✔
413
    readonly minColumnWidth?: DataGridSearchProps["minColumnWidth"];
1✔
414
    /**
1✔
415
     * The maximum width a column can be resized to.
1✔
416
     * @defaultValue 500
1✔
417
     * @group Style
1✔
418
     */
1✔
419
    readonly maxColumnWidth?: DataGridSearchProps["maxColumnWidth"];
1✔
420
    /**
1✔
421
     * The maximum width a column can be automatically sized to.
1✔
422
     * @defaultValue `maxColumnWidth`
1✔
423
     * @group Style
1✔
424
     */
1✔
425
    readonly maxColumnAutoWidth?: number;
1✔
426

1✔
427
    /**
1✔
428
     * Used to provide an override to the default image editor for the data grid. `provideEditor` may be a better
1✔
429
     * choice for most people.
1✔
430
     * @group Advanced
1✔
431
     * */
1✔
432
    readonly imageEditorOverride?: ImageEditorType;
1✔
433
    /**
1✔
434
     * If specified, it will be used to render Markdown, instead of the default Markdown renderer used by the Grid.
1✔
435
     * You'll want to use this if you need to process your Markdown for security purposes, or if you want to use a
1✔
436
     * renderer with different Markdown features.
1✔
437
     * @group Advanced
1✔
438
     */
1✔
439
    readonly markdownDivCreateNode?: (content: string) => DocumentFragment;
1✔
440

1✔
441
    /** Callback for providing a custom editor for a cell.
1✔
442
     * @group Editing
1✔
443
     */
1✔
444
    readonly provideEditor?: ProvideEditorCallback<GridCell>;
1✔
445
    /**
1✔
446
     * Allows coercion of pasted values.
1✔
447
     * @group Editing
1✔
448
     * @param val The pasted value
1✔
449
     * @param cell The cell being pasted into
1✔
450
     * @returns `undefined` to accept default behavior or a `GridCell` which should be used to represent the pasted value.
1✔
451
     */
1✔
452
    readonly coercePasteValue?: (val: string, cell: GridCell) => GridCell | undefined;
1✔
453

1✔
454
    /**
1✔
455
     * Emitted when the grid selection is cleared.
1✔
456
     * @group Selection
1✔
457
     */
1✔
458
    readonly onSelectionCleared?: () => void;
1✔
459

1✔
460
    /**
1✔
461
     * Callback used to override the rendering of any cell.
1✔
462
     * @group Drawing
1✔
463
     */
1✔
464
    readonly drawCell?: DrawCustomCellCallback;
1✔
465

1✔
466
    /**
1✔
467
     * The current selection of the data grid. Contains all selected cells, ranges, rows, and columns.
1✔
468
     * Used in conjunction with {@link onGridSelectionChange}
1✔
469
     * method to implement a controlled selection.
1✔
470
     * @group Selection
1✔
471
     */
1✔
472
    readonly gridSelection?: GridSelection;
1✔
473
    /**
1✔
474
     * Emitted whenever the grid selection changes. Specifying
1✔
475
     * this function will make the grid’s selection controlled, so
1✔
476
     * so you will need to specify {@link gridSelection} as well. See
1✔
477
     * the "Controlled Selection" example for details.
1✔
478
     *
1✔
479
     * @param newSelection The new gridSelection as created by user input.
1✔
480
     * @group Selection
1✔
481
     */
1✔
482
    readonly onGridSelectionChange?: (newSelection: GridSelection) => void;
1✔
483
    /**
1✔
484
     * Emitted whenever the visible cells change, usually due to scrolling.
1✔
485
     * @group Events
1✔
486
     * @param range An inclusive range of all visible cells. May include cells obscured by UI elements such
1✔
487
     * as headers.
1✔
488
     * @param tx The x transform of the cell region.
1✔
489
     * @param ty The y transform of the cell region.
1✔
490
     * @param extras Contains information about the selected cell and
1✔
491
     * any visible freeze columns.
1✔
492
     */
1✔
493
    readonly onVisibleRegionChanged?: (
1✔
494
        range: Rectangle,
1✔
495
        tx?: number,
1✔
496
        ty?: number,
1✔
497
        extras?: {
1✔
498
            /** The selected item if visible */
1✔
499
            selected?: Item;
1✔
500
            /** A selection of visible freeze columns */
1✔
501
            freezeRegion?: Rectangle;
1✔
502
        }
1✔
503
    ) => void;
1✔
504

1✔
505
    /**
1✔
506
     * The primary callback for getting cell data into the data grid.
1✔
507
     * @group Data
1✔
508
     * @param cell The location of the cell being requested.
1✔
509
     * @returns A valid GridCell to be rendered by the Grid.
1✔
510
     */
1✔
511
    readonly getCellContent: (cell: Item) => GridCell;
1✔
512
    /**
1✔
513
     * Determines if row selection requires a modifier key to enable multi-selection or not. In auto mode it adapts to
1✔
514
     * touch or mouse environments automatically, in multi-mode it always acts as if the multi key (Ctrl) is pressed.
1✔
515
     * @group Editing
1✔
516
     * @defaultValue `auto`
1✔
517
     */
1✔
518
    readonly rowSelectionMode?: "auto" | "multi";
1✔
519

1✔
520
    /**
1✔
521
     * Add table headers to copied data.
1✔
522
     * @group Editing
1✔
523
     * @defaultValue `false`
1✔
524
     */
1✔
525
    readonly copyHeaders?: boolean;
1✔
526

1✔
527
    /**
1✔
528
     * Determins which keybindings are enabled.
1✔
529
     * @group Editing
1✔
530
     * @defaultValue is
1✔
531

1✔
532
            {
1✔
533
                selectAll: true,
1✔
534
                selectRow: true,
1✔
535
                selectColumn: true,
1✔
536
                downFill: false,
1✔
537
                rightFill: false,
1✔
538
                pageUp: false,
1✔
539
                pageDown: false,
1✔
540
                clear: true,
1✔
541
                copy: true,
1✔
542
                paste: true,
1✔
543
                search: false,
1✔
544
                first: true,
1✔
545
                last: true,
1✔
546
            }
1✔
547
     */
1✔
548
    readonly keybindings?: Partial<Keybinds>;
1✔
549

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

1✔
573
    /** The number of columns which should remain in place when scrolling horizontally. The row marker column, if
1✔
574
     * enabled is always frozen and is not included in this count.
1✔
575
     * @defaultValue 0
1✔
576
     * @group Style
1✔
577
     */
1✔
578
    readonly freezeColumns?: DataGridSearchProps["freezeColumns"];
1✔
579

1✔
580
    /**
1✔
581
     * Controls the drawing of the left hand vertical border of a column. If set to a boolean value it controls all
1✔
582
     * borders.
1✔
583
     * @defaultValue `true`
1✔
584
     * @group Style
1✔
585
     */
1✔
586
    readonly verticalBorder?: DataGridSearchProps["verticalBorder"] | boolean;
1✔
587

1✔
588
    /**
1✔
589
     * Called when data is pasted into the grid. If left undefined, the `DataEditor` will operate in a
1✔
590
     * fallback mode and attempt to paste the text buffer into the current cell assuming the current cell is not
1✔
591
     * readonly and can accept the data type. If `onPaste` is set to false or the function returns false, the grid will
1✔
592
     * simply ignore paste. If `onPaste` evaluates to true the grid will attempt to split the data by tabs and newlines
1✔
593
     * and paste into available cells.
1✔
594
     *
1✔
595
     * The grid will not attempt to add additional rows if more data is pasted then can fit. In that case it is
1✔
596
     * advisable to simply return false from onPaste and handle the paste manually.
1✔
597
     * @group Editing
1✔
598
     */
1✔
599
    readonly onPaste?: ((target: Item, values: readonly (readonly string[])[]) => boolean) | boolean;
1✔
600

1✔
601
    /**
1✔
602
     * The theme used by the data grid to get all color and font information
1✔
603
     * @group Style
1✔
604
     */
1✔
605
    readonly theme?: Partial<Theme>;
1✔
606

1✔
607
    readonly renderers?: readonly InternalCellRenderer<InnerGridCell>[];
1✔
608

1✔
609
    /**
1✔
610
     * An array of custom renderers which can be used to extend the data grid.
1✔
611
     * @group Advanced
1✔
612
     */
1✔
613
    readonly customRenderers?: readonly CustomRenderer<CustomCell<any>>[];
1✔
614

1✔
615
    readonly scaleToRem?: boolean;
1✔
616

1✔
617
    /**
1✔
618
     * Custom predicate function to decide whether the click event occurred outside the grid
1✔
619
     * Especially used when custom editor is opened with the portal and is outside the grid, but there is no possibility
1✔
620
     * to add a class "click-outside-ignore"
1✔
621
     * If this function is supplied and returns false, the click event is ignored
1✔
622
     */
1✔
623
    readonly isOutsideClick?: (e: MouseEvent | TouchEvent) => boolean;
1✔
624
}
1✔
625

1✔
626
type ScrollToFn = (
1✔
627
    col: number | { amount: number; unit: "cell" | "px" },
1✔
628
    row: number | { amount: number; unit: "cell" | "px" },
1✔
629
    dir?: "horizontal" | "vertical" | "both",
1✔
630
    paddingX?: number,
1✔
631
    paddingY?: number,
1✔
632
    options?: {
1✔
633
        hAlign?: "start" | "center" | "end";
1✔
634
        vAlign?: "start" | "center" | "end";
1✔
635
    }
1✔
636
) => void;
1✔
637

1✔
638
/** @category DataEditor */
1✔
639
export interface DataEditorRef {
1✔
640
    /**
1✔
641
     * Programatically appends a row.
1✔
642
     * @param col The column index to focus in the new row.
1✔
643
     * @returns A promise which waits for the append to complete.
1✔
644
     */
1✔
645
    appendRow: (col: number, openOverlay?: boolean) => Promise<void>;
1✔
646
    /**
1✔
647
     * Triggers cells to redraw.
1✔
648
     */
1✔
649
    updateCells: DataGridRef["damage"];
1✔
650
    /**
1✔
651
     * Gets the screen space bounds of the requested item.
1✔
652
     */
1✔
653
    getBounds: DataGridRef["getBounds"];
1✔
654
    /**
1✔
655
     * Triggers the data grid to focus itself or the correct accessibility element.
1✔
656
     */
1✔
657
    focus: DataGridRef["focus"];
1✔
658
    /**
1✔
659
     * Generic API for emitting events as if they had been triggered via user interaction.
1✔
660
     */
1✔
661
    emit: (eventName: EmitEvents) => Promise<void>;
1✔
662
    /**
1✔
663
     * Scrolls to the desired cell or location in the grid.
1✔
664
     */
1✔
665
    scrollTo: ScrollToFn;
1✔
666
    /**
1✔
667
     * Causes the columns in the selection to have their natural size recomputed and re-emitted as a resize event.
1✔
668
     */
1✔
669
    remeasureColumns: (cols: CompactSelection) => void;
1✔
670
}
1✔
671

1✔
672
const loadingCell: GridCell = {
1✔
673
    kind: GridCellKind.Loading,
1✔
674
    allowOverlay: false,
1✔
675
};
1✔
676

1✔
677
const emptyGridSelection: GridSelection = {
1✔
678
    columns: CompactSelection.empty(),
1✔
679
    rows: CompactSelection.empty(),
1✔
680
    current: undefined,
1✔
681
};
1✔
682

1✔
683
const DataEditorImpl: React.ForwardRefRenderFunction<DataEditorRef, DataEditorProps> = (p, forwardedRef) => {
1✔
684
    const [gridSelectionInner, setGridSelectionInner] = React.useState<GridSelection>(emptyGridSelection);
649✔
685
    const [overlay, setOverlay] = React.useState<{
649✔
686
        target: Rectangle;
649✔
687
        content: GridCell;
649✔
688
        theme: Theme;
649✔
689
        initialValue: string | undefined;
649✔
690
        cell: Item;
649✔
691
        highlight: boolean;
649✔
692
        forceEditMode: boolean;
649✔
693
    }>();
649✔
694
    const searchInputRef = React.useRef<HTMLInputElement | null>(null);
649✔
695
    const canvasRef = React.useRef<HTMLCanvasElement | null>(null);
649✔
696
    const [mouseState, setMouseState] = React.useState<MouseState>();
649✔
697
    const scrollRef = React.useRef<HTMLDivElement | null>(null);
649✔
698
    const lastSent = React.useRef<[number, number]>();
649✔
699

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

649✔
806
    const minColumnWidth = Math.max(minColumnWidthIn, 20);
649✔
807
    const maxColumnWidth = Math.max(maxColumnWidthIn, minColumnWidth);
649✔
808
    const maxColumnAutoWidth = Math.max(maxColumnAutoWidthIn ?? maxColumnWidth, minColumnWidth);
649✔
809

649✔
810
    const docStyle = React.useMemo(() => {
649✔
811
        if (typeof window === "undefined") return { fontSize: "16px" };
132!
812
        return window.getComputedStyle(document.documentElement);
132✔
813
    }, []);
649✔
814

649✔
815
    const fontSizeStr = docStyle.fontSize;
649✔
816

649✔
817
    const remSize = React.useMemo(() => Number.parseFloat(fontSizeStr), [fontSizeStr]);
649✔
818

649✔
819
    const { rowHeight, headerHeight, groupHeaderHeight, theme, overscrollX, overscrollY } = useRemAdjuster({
649✔
820
        groupHeaderHeight: groupHeaderHeightIn,
649✔
821
        headerHeight: headerHeightIn,
649✔
822
        overscrollX: overscrollXIn,
649✔
823
        overscrollY: overscrollYIn,
649✔
824
        remSize,
649✔
825
        rowHeight: rowHeightIn,
649✔
826
        scaleToRem,
649✔
827
        theme: themeIn,
649✔
828
    });
649✔
829

649✔
830
    const keybindings = React.useMemo(() => {
649✔
831
        return keybindingsIn === undefined
132✔
832
            ? keybindingDefaults
129✔
833
            : {
3✔
834
                  ...keybindingDefaults,
3✔
835
                  ...keybindingsIn,
3✔
836
              };
3✔
837
    }, [keybindingsIn]);
649✔
838

649✔
839
    const rowMarkerWidth = rowMarkerWidthRaw ?? (rows > 10_000 ? 48 : rows > 1000 ? 44 : rows > 100 ? 36 : 32);
649!
840
    const hasRowMarkers = rowMarkers !== "none";
649✔
841
    const rowMarkerOffset = hasRowMarkers ? 1 : 0;
649✔
842
    const showTrailingBlankRow = onRowAppended !== undefined;
649✔
843
    const lastRowSticky = trailingRowOptions?.sticky === true;
649✔
844

649✔
845
    const [showSearchInner, setShowSearchInner] = React.useState(false);
649✔
846
    const showSearch = showSearchIn ?? showSearchInner;
649✔
847

649✔
848
    const onSearchClose = React.useCallback(() => {
649✔
849
        if (onSearchCloseIn !== undefined) {
2✔
850
            onSearchCloseIn();
2✔
851
        } else {
2!
852
            setShowSearchInner(false);
×
UNCOV
853
        }
×
854
    }, [onSearchCloseIn]);
649✔
855

649✔
856
    const gridSelectionOuterMangled: GridSelection | undefined = React.useMemo((): GridSelection | undefined => {
649✔
857
        return gridSelectionOuter === undefined ? undefined : shiftSelection(gridSelectionOuter, rowMarkerOffset);
255✔
858
    }, [gridSelectionOuter, rowMarkerOffset]);
649✔
859
    const gridSelection = gridSelectionOuterMangled ?? gridSelectionInner;
649✔
860

649✔
861
    const abortControllerRef = React.useRef(new AbortController());
649✔
862
    React.useEffect(() => {
649✔
863
        return () => {
132✔
864
            // eslint-disable-next-line react-hooks/exhaustive-deps
132✔
865
            abortControllerRef?.current.abort();
132✔
866
        };
132✔
867
    }, []);
649✔
868

649✔
869
    const [getCellsForSelection, getCellsForSeletionDirect] = useCellsForSelection(
649✔
870
        getCellsForSelectionIn,
649✔
871
        getCellContent,
649✔
872
        rowMarkerOffset,
649✔
873
        abortControllerRef.current,
649✔
874
        rows
649✔
875
    );
649✔
876

649✔
877
    const validateCell = React.useCallback<NonNullable<typeof validateCellIn>>(
649✔
878
        (cell, newValue, prevValue) => {
649✔
879
            if (validateCellIn === undefined) return true;
16✔
880
            const item: Item = [cell[0] - rowMarkerOffset, cell[1]];
1✔
881
            return validateCellIn?.(item, newValue, prevValue);
1✔
882
        },
16✔
883
        [rowMarkerOffset, validateCellIn]
649✔
884
    );
649✔
885

649✔
886
    const expectedExternalGridSelection = React.useRef<GridSelection | undefined>(gridSelectionOuter);
649✔
887
    const setGridSelection = React.useCallback(
649✔
888
        (newVal: GridSelection, expand: boolean): void => {
649✔
889
            if (expand) {
166✔
890
                newVal = expandSelection(
124✔
891
                    newVal,
124✔
892
                    getCellsForSelection,
124✔
893
                    rowMarkerOffset,
124✔
894
                    spanRangeBehavior,
124✔
895
                    abortControllerRef.current
124✔
896
                );
124✔
897
            }
124✔
898
            if (onGridSelectionChange !== undefined) {
166✔
899
                expectedExternalGridSelection.current = shiftSelection(newVal, -rowMarkerOffset);
127✔
900
                onGridSelectionChange(expectedExternalGridSelection.current);
127✔
901
            } else {
166✔
902
                setGridSelectionInner(newVal);
39✔
903
            }
39✔
904
        },
166✔
905
        [onGridSelectionChange, getCellsForSelection, rowMarkerOffset, spanRangeBehavior]
649✔
906
    );
649✔
907

649✔
908
    const onColumnResize = whenDefined(
649✔
909
        onColumnResizeIn,
649✔
910
        React.useCallback<NonNullable<typeof onColumnResizeIn>>(
649✔
911
            (_, w, ind, wg) => {
649✔
912
                onColumnResizeIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
11✔
913
            },
11✔
914
            [onColumnResizeIn, rowMarkerOffset, columnsIn]
649✔
915
        )
649✔
916
    );
649✔
917

649✔
918
    const onColumnResizeEnd = whenDefined(
649✔
919
        onColumnResizeEndIn,
649✔
920
        React.useCallback<NonNullable<typeof onColumnResizeEndIn>>(
649✔
921
            (_, w, ind, wg) => {
649✔
922
                onColumnResizeEndIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
2✔
923
            },
2✔
924
            [onColumnResizeEndIn, rowMarkerOffset, columnsIn]
649✔
925
        )
649✔
926
    );
649✔
927

649✔
928
    const onColumnResizeStart = whenDefined(
649✔
929
        onColumnResizeStartIn,
649✔
930
        React.useCallback<NonNullable<typeof onColumnResizeStartIn>>(
649✔
931
            (_, w, ind, wg) => {
649✔
932
                onColumnResizeStartIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
×
UNCOV
933
            },
×
934
            [onColumnResizeStartIn, rowMarkerOffset, columnsIn]
649✔
935
        )
649✔
936
    );
649✔
937

649✔
938
    const drawHeader = whenDefined(
649✔
939
        drawHeaderIn,
649✔
940
        React.useCallback<NonNullable<typeof drawHeaderIn>>(
649✔
941
            args => {
649✔
942
                return drawHeaderIn?.({ ...args, columnIndex: args.columnIndex - rowMarkerOffset }) ?? false;
×
UNCOV
943
            },
×
944
            [drawHeaderIn, rowMarkerOffset]
649✔
945
        )
649✔
946
    );
649✔
947

649✔
948
    const onDelete = React.useCallback<NonNullable<DataEditorProps["onDelete"]>>(
649✔
949
        sel => {
649✔
950
            if (onDeleteIn !== undefined) {
8✔
951
                const result = onDeleteIn(shiftSelection(sel, -rowMarkerOffset));
5✔
952
                if (typeof result === "boolean") {
5!
953
                    return result;
×
UNCOV
954
                }
×
955
                return shiftSelection(result, rowMarkerOffset);
5✔
956
            }
5✔
957
            return true;
3✔
958
        },
8✔
959
        [onDeleteIn, rowMarkerOffset]
649✔
960
    );
649✔
961

649✔
962
    const [setCurrent, setSelectedRows, setSelectedColumns] = useSelectionBehavior(
649✔
963
        gridSelection,
649✔
964
        setGridSelection,
649✔
965
        rangeSelectionBlending,
649✔
966
        columnSelectionBlending,
649✔
967
        rowSelectionBlending,
649✔
968
        rangeSelect
649✔
969
    );
649✔
970

649✔
971
    const mergedTheme = React.useMemo(() => {
649✔
972
        return { ...getDataEditorTheme(), ...theme };
132✔
973
    }, [theme]);
649✔
974

649✔
975
    const [clientSize, setClientSize] = React.useState<readonly [number, number, number]>([10, 10, 0]);
649✔
976

649✔
977
    const rendererMap = React.useMemo(() => {
649✔
978
        if (renderers === undefined) return {};
132!
979
        const result: Partial<Record<InnerGridCellKind | GridCellKind, InternalCellRenderer<InnerGridCell>>> = {};
132✔
980
        for (const r of renderers) {
132✔
981
            result[r.kind] = r;
1,716✔
982
        }
1,716✔
983
        return result;
132✔
984
    }, [renderers]);
649✔
985

649✔
986
    const getCellRenderer: <T extends InnerGridCell>(cell: T) => CellRenderer<T> | undefined = React.useCallback(
649✔
987
        <T extends InnerGridCell>(cell: T) => {
649✔
988
            if (cell.kind !== GridCellKind.Custom) {
133,307✔
989
                return rendererMap[cell.kind] as unknown as CellRenderer<T>;
129,577✔
990
            }
129,577✔
991
            return additionalRenderers?.find(x => x.isMatch(cell)) as CellRenderer<T>;
133,307✔
992
        },
133,307✔
993
        [additionalRenderers, rendererMap]
649✔
994
    );
649✔
995

649✔
996
    const columns = useColumnSizer(
649✔
997
        columnsIn,
649✔
998
        rows,
649✔
999
        getCellsForSeletionDirect,
649✔
1000
        clientSize[0] - (rowMarkerOffset === 0 ? 0 : rowMarkerWidth) - clientSize[2],
649✔
1001
        minColumnWidth,
649✔
1002
        maxColumnAutoWidth,
649✔
1003
        mergedTheme,
649✔
1004
        getCellRenderer,
649✔
1005
        abortControllerRef.current
649✔
1006
    );
649✔
1007

649✔
1008
    const enableGroups = React.useMemo(() => {
649✔
1009
        return columns.some(c => c.group !== undefined);
132✔
1010
    }, [columns]);
649✔
1011

649✔
1012
    const totalHeaderHeight = enableGroups ? headerHeight + groupHeaderHeight : headerHeight;
649✔
1013

649✔
1014
    const numSelectedRows = gridSelection.rows.length;
649✔
1015
    const rowMarkerHeader =
649✔
1016
        rowMarkers === "none"
649✔
1017
            ? ""
517✔
1018
            : numSelectedRows === 0
131✔
1019
            ? headerCellUnheckedMarker
87✔
1020
            : numSelectedRows === rows
44✔
1021
            ? headerCellCheckedMarker
6✔
1022
            : headerCellIndeterminateMarker;
38✔
1023

649✔
1024
    const mangledCols = React.useMemo(() => {
649✔
1025
        if (rowMarkers === "none") return columns;
146✔
1026
        return [
45✔
1027
            {
45✔
1028
                title: rowMarkerHeader,
45✔
1029
                width: rowMarkerWidth,
45✔
1030
                icon: undefined,
45✔
1031
                hasMenu: false,
45✔
1032
                style: "normal" as const,
45✔
1033
                themeOverride: rowMarkerTheme,
45✔
1034
            },
45✔
1035
            ...columns,
45✔
1036
        ];
45✔
1037
    }, [columns, rowMarkerWidth, rowMarkers, rowMarkerHeader, rowMarkerTheme]);
649✔
1038

649✔
1039
    const [visibleRegionY, visibleRegionTy] = React.useMemo(() => {
649✔
1040
        return [
132✔
1041
            scrollOffsetY !== undefined && typeof rowHeight === "number" ? Math.floor(scrollOffsetY / rowHeight) : 0,
132!
1042
            scrollOffsetY !== undefined && typeof rowHeight === "number" ? -(scrollOffsetY % rowHeight) : 0,
132!
1043
        ];
132✔
1044
    }, [scrollOffsetY, rowHeight]);
649✔
1045

649✔
1046
    type VisibleRegion = Rectangle & {
649✔
1047
        /** value in px */
649✔
1048
        tx?: number;
649✔
1049
        /** value in px */
649✔
1050
        ty?: number;
649✔
1051
        extras?: {
649✔
1052
            selected?: Item;
649✔
1053
            freezeRegion?: Rectangle;
649✔
1054
        };
649✔
1055
    };
649✔
1056

649✔
1057
    const visibleRegionRef = React.useRef<VisibleRegion>({
649✔
1058
        height: 1,
649✔
1059
        width: 1,
649✔
1060
        x: 0,
649✔
1061
        y: 0,
649✔
1062
    });
649✔
1063
    const visibleRegionInput = React.useMemo<VisibleRegion>(
649✔
1064
        () => ({
649✔
1065
            x: visibleRegionRef.current.x,
132✔
1066
            y: visibleRegionY,
132✔
1067
            width: visibleRegionRef.current.width ?? 1,
132!
1068
            height: visibleRegionRef.current.height ?? 1,
132!
1069
            // tx: 'TODO',
132✔
1070
            ty: visibleRegionTy,
132✔
1071
        }),
132✔
1072
        [visibleRegionTy, visibleRegionY]
649✔
1073
    );
649✔
1074

649✔
1075
    const hasJustScrolled = React.useRef(false);
649✔
1076

649✔
1077
    const [visibleRegion, setVisibleRegion, empty] = useStateWithReactiveInput<VisibleRegion>(visibleRegionInput);
649✔
1078

649✔
1079
    const vScrollReady = (visibleRegion.height ?? 1) > 1;
649!
1080
    React.useLayoutEffect(() => {
649✔
1081
        if (scrollOffsetY !== undefined && scrollRef.current !== null && vScrollReady) {
264!
1082
            if (scrollRef.current.scrollTop === scrollOffsetY) return;
×
1083
            scrollRef.current.scrollTop = scrollOffsetY;
×
UNCOV
1084
            if (scrollRef.current.scrollTop !== scrollOffsetY) {
×
1085
                empty();
×
UNCOV
1086
            }
×
1087
            hasJustScrolled.current = true;
×
UNCOV
1088
        }
×
1089
    }, [scrollOffsetY, vScrollReady, empty]);
649✔
1090

649✔
1091
    const hScrollReady = (visibleRegion.width ?? 1) > 1;
649!
1092
    React.useLayoutEffect(() => {
649✔
1093
        if (scrollOffsetX !== undefined && scrollRef.current !== null && hScrollReady) {
264!
1094
            if (scrollRef.current.scrollLeft === scrollOffsetX) return;
×
1095
            scrollRef.current.scrollLeft = scrollOffsetX;
×
UNCOV
1096
            if (scrollRef.current.scrollLeft !== scrollOffsetX) {
×
1097
                empty();
×
UNCOV
1098
            }
×
1099
            hasJustScrolled.current = true;
×
UNCOV
1100
        }
×
1101
    }, [scrollOffsetX, hScrollReady, empty]);
649✔
1102

649✔
1103
    const cellXOffset = visibleRegion.x + rowMarkerOffset;
649✔
1104
    const cellYOffset = visibleRegion.y;
649✔
1105

649✔
1106
    const gridRef = React.useRef<DataGridRef | null>(null);
649✔
1107

649✔
1108
    const focus = React.useCallback((immediate?: boolean) => {
649✔
1109
        if (immediate === true) {
120✔
1110
            gridRef.current?.focus();
7✔
1111
        } else {
120✔
1112
            window.requestAnimationFrame(() => {
113✔
1113
                gridRef.current?.focus();
112✔
1114
            });
113✔
1115
        }
113✔
1116
    }, []);
649✔
1117

649✔
1118
    const mangledRows = showTrailingBlankRow ? rows + 1 : rows;
649!
1119

649✔
1120
    const mangledOnCellsEdited = React.useCallback<NonNullable<typeof onCellsEdited>>(
649✔
1121
        (items: readonly EditListItem[]) => {
649✔
1122
            const mangledItems =
26✔
1123
                rowMarkerOffset === 0
26✔
1124
                    ? items
21✔
1125
                    : items.map(x => ({
5✔
1126
                          ...x,
29✔
1127
                          location: [x.location[0] - rowMarkerOffset, x.location[1]] as const,
29✔
1128
                      }));
5✔
1129
            const r = onCellsEdited?.(mangledItems);
26✔
1130

26✔
1131
            if (r !== true) {
26✔
1132
                for (const i of mangledItems) onCellEdited?.(i.location, i.value);
25✔
1133
            }
25✔
1134

26✔
1135
            return r;
26✔
1136
        },
26✔
1137
        [onCellEdited, onCellsEdited, rowMarkerOffset]
649✔
1138
    );
649✔
1139

649✔
1140
    const highlightRegions = React.useMemo(() => {
649✔
1141
        if (highlightRegionsIn === undefined) return undefined;
132✔
1142
        if (rowMarkerOffset === 0) return highlightRegionsIn;
1!
UNCOV
1143

×
1144
        return highlightRegionsIn
×
UNCOV
1145
            .map(r => {
×
1146
                const maxWidth = mangledCols.length - r.range.x - rowMarkerOffset;
×
1147
                if (maxWidth <= 0) return undefined;
×
1148
                return {
×
UNCOV
1149
                    color: r.color,
×
UNCOV
1150
                    range: {
×
UNCOV
1151
                        ...r.range,
×
UNCOV
1152
                        x: r.range.x + rowMarkerOffset,
×
UNCOV
1153
                        width: Math.min(maxWidth, r.range.width),
×
UNCOV
1154
                    },
×
UNCOV
1155
                    style: r.style,
×
UNCOV
1156
                };
×
UNCOV
1157
            })
×
1158
            .filter(x => x !== undefined) as typeof highlightRegionsIn;
×
1159
    }, [highlightRegionsIn, mangledCols.length, rowMarkerOffset]);
649✔
1160

649✔
1161
    const mangledColsRef = React.useRef(mangledCols);
649✔
1162
    mangledColsRef.current = mangledCols;
649✔
1163
    const getMangledCellContent = React.useCallback(
649✔
1164
        ([col, row]: Item, forceStrict: boolean = false): InnerGridCell => {
649✔
1165
            const isTrailing = showTrailingBlankRow && row === mangledRows - 1;
130,457✔
1166
            const isRowMarkerCol = col === 0 && hasRowMarkers;
130,457✔
1167
            if (isRowMarkerCol) {
130,457✔
1168
                if (isTrailing) {
2,183✔
1169
                    return loadingCell;
98✔
1170
                }
98✔
1171
                return {
2,085✔
1172
                    kind: InnerGridCellKind.Marker,
2,085✔
1173
                    allowOverlay: false,
2,085✔
1174
                    checked: gridSelection?.rows.hasIndex(row) === true,
2,183✔
1175
                    markerKind: rowMarkers === "clickable-number" ? "number" : rowMarkers,
2,183!
1176
                    row: rowMarkerStartIndex + row,
2,183✔
1177
                    drawHandle: onRowMoved !== undefined,
2,183✔
1178
                    cursor: rowMarkers === "clickable-number" ? "pointer" : undefined,
2,183!
1179
                };
2,183✔
1180
            } else if (isTrailing) {
130,457✔
1181
                //If the grid is empty, we will return text
3,647✔
1182
                const isFirst = col === rowMarkerOffset;
3,647✔
1183

3,647✔
1184
                const maybeFirstColumnHint = isFirst ? trailingRowOptions?.hint ?? "" : "";
3,647✔
1185
                const c = mangledColsRef.current[col];
3,647✔
1186

3,647✔
1187
                if (c?.trailingRowOptions?.disabled === true) {
3,647!
1188
                    return loadingCell;
×
1189
                } else {
3,647✔
1190
                    const hint = c?.trailingRowOptions?.hint ?? maybeFirstColumnHint;
3,647!
1191
                    const icon = c?.trailingRowOptions?.addIcon ?? trailingRowOptions?.addIcon;
3,647!
1192
                    return {
3,647✔
1193
                        kind: InnerGridCellKind.NewRow,
3,647✔
1194
                        hint,
3,647✔
1195
                        allowOverlay: false,
3,647✔
1196
                        icon,
3,647✔
1197
                    };
3,647✔
1198
                }
3,647✔
1199
            } else {
128,274✔
1200
                const outerCol = col - rowMarkerOffset;
124,627✔
1201
                if (forceStrict || experimental?.strict === true) {
124,627✔
1202
                    const vr = visibleRegionRef.current;
21,679✔
1203
                    const isOutsideMainArea =
21,679✔
1204
                        vr.x > outerCol || outerCol > vr.x + vr.width || vr.y > row || row > vr.y + vr.height;
21,679✔
1205
                    const isSelected = outerCol === vr.extras?.selected?.[0] && row === vr.extras?.selected[1];
21,679!
1206
                    const isOutsideFreezeArea =
21,679✔
1207
                        vr.extras?.freezeRegion === undefined ||
21,679!
UNCOV
1208
                        vr.extras.freezeRegion.x > outerCol ||
×
UNCOV
1209
                        outerCol > vr.extras.freezeRegion.x + vr.extras.freezeRegion.width ||
×
UNCOV
1210
                        vr.extras.freezeRegion.y > row ||
×
UNCOV
1211
                        row > vr.extras.freezeRegion.y + vr.extras.freezeRegion.height;
×
1212
                    if (isOutsideMainArea && !isSelected && isOutsideFreezeArea) {
21,679!
1213
                        return {
×
UNCOV
1214
                            kind: GridCellKind.Loading,
×
UNCOV
1215
                            allowOverlay: false,
×
UNCOV
1216
                        };
×
UNCOV
1217
                    }
×
1218
                }
21,679✔
1219
                let result = getCellContent([outerCol, row]);
124,627✔
1220
                if (rowMarkerOffset !== 0 && result.span !== undefined) {
124,627!
1221
                    result = {
×
UNCOV
1222
                        ...result,
×
UNCOV
1223
                        span: [result.span[0] + rowMarkerOffset, result.span[1] + rowMarkerOffset],
×
UNCOV
1224
                    };
×
UNCOV
1225
                }
×
1226
                return result;
124,627✔
1227
            }
124,627✔
1228
        },
130,457✔
1229
        [
649✔
1230
            showTrailingBlankRow,
649✔
1231
            mangledRows,
649✔
1232
            hasRowMarkers,
649✔
1233
            gridSelection?.rows,
649✔
1234
            onRowMoved,
649✔
1235
            rowMarkers,
649✔
1236
            rowMarkerOffset,
649✔
1237
            trailingRowOptions?.hint,
649✔
1238
            trailingRowOptions?.addIcon,
649✔
1239
            experimental?.strict,
649✔
1240
            getCellContent,
649✔
1241
            rowMarkerStartIndex,
649✔
1242
        ]
649✔
1243
    );
649✔
1244

649✔
1245
    const mangledGetGroupDetails = React.useCallback<NonNullable<DataEditorProps["getGroupDetails"]>>(
649✔
1246
        group => {
649✔
1247
            let result = getGroupDetails?.(group) ?? { name: group };
7,821✔
1248
            if (onGroupHeaderRenamed !== undefined && group !== "") {
7,821✔
1249
                result = {
91✔
1250
                    icon: result.icon,
91✔
1251
                    name: result.name,
91✔
1252
                    overrideTheme: result.overrideTheme,
91✔
1253
                    actions: [
91✔
1254
                        ...(result.actions ?? []),
91✔
1255
                        {
91✔
1256
                            title: "Rename",
91✔
1257
                            icon: "renameIcon",
91✔
1258
                            onClick: e =>
91✔
1259
                                setRenameGroup({
2✔
1260
                                    group: result.name,
2✔
1261
                                    bounds: e.bounds,
2✔
1262
                                }),
2✔
1263
                        },
91✔
1264
                    ],
91✔
1265
                };
91✔
1266
            }
91✔
1267
            return result;
7,821✔
1268
        },
7,821✔
1269
        [getGroupDetails, onGroupHeaderRenamed]
649✔
1270
    );
649✔
1271

649✔
1272
    const setOverlaySimple = React.useCallback(
649✔
1273
        (val: Omit<NonNullable<typeof overlay>, "theme">) => {
649✔
1274
            const [col, row] = val.cell;
16✔
1275
            const column = mangledCols[col];
16✔
1276
            const groupTheme =
16✔
1277
                column?.group !== undefined ? mangledGetGroupDetails(column.group)?.overrideTheme : undefined;
16!
1278
            const colTheme = column?.themeOverride;
16✔
1279
            const rowTheme = getRowThemeOverride?.(row);
16!
1280

16✔
1281
            setOverlay({
16✔
1282
                ...val,
16✔
1283
                theme: { ...mergedTheme, ...groupTheme, ...colTheme, ...rowTheme, ...val.content.themeOverride },
16✔
1284
            });
16✔
1285
        },
16✔
1286
        [getRowThemeOverride, mangledCols, mangledGetGroupDetails, mergedTheme]
649✔
1287
    );
649✔
1288

649✔
1289
    const reselect = React.useCallback(
649✔
1290
        (bounds: Rectangle, fromKeyboard: boolean, initialValue?: string) => {
649✔
1291
            if (gridSelection.current === undefined) return;
16!
1292

16✔
1293
            const [col, row] = gridSelection.current.cell;
16✔
1294
            const c = getMangledCellContent([col, row]);
16✔
1295
            if (c.kind !== GridCellKind.Boolean && c.allowOverlay) {
16✔
1296
                let content = c;
15✔
1297
                if (initialValue !== undefined) {
15✔
1298
                    switch (content.kind) {
7✔
1299
                        case GridCellKind.Number: {
7!
1300
                            const d = maybe(() => (initialValue === "-" ? -0 : Number.parseFloat(initialValue)), 0);
×
1301
                            content = {
×
UNCOV
1302
                                ...content,
×
UNCOV
1303
                                data: Number.isNaN(d) ? 0 : d,
×
UNCOV
1304
                            };
×
1305
                            break;
×
UNCOV
1306
                        }
×
1307
                        case GridCellKind.Text:
7✔
1308
                        case GridCellKind.Markdown:
7✔
1309
                        case GridCellKind.Uri:
7✔
1310
                            content = {
7✔
1311
                                ...content,
7✔
1312
                                data: initialValue,
7✔
1313
                            };
7✔
1314
                            break;
7✔
1315
                    }
7✔
1316
                }
7✔
1317

15✔
1318
                setOverlaySimple({
15✔
1319
                    target: bounds,
15✔
1320
                    content,
15✔
1321
                    initialValue,
15✔
1322
                    cell: [col, row],
15✔
1323
                    highlight: initialValue === undefined,
15✔
1324
                    forceEditMode: initialValue !== undefined,
15✔
1325
                });
15✔
1326
            } else if (c.kind === GridCellKind.Boolean && fromKeyboard && c.readonly !== true) {
16!
1327
                mangledOnCellsEdited([
×
UNCOV
1328
                    {
×
UNCOV
1329
                        location: gridSelection.current.cell,
×
UNCOV
1330
                        value: {
×
UNCOV
1331
                            ...c,
×
UNCOV
1332
                            data: toggleBoolean(c.data),
×
UNCOV
1333
                        },
×
UNCOV
1334
                    },
×
UNCOV
1335
                ]);
×
1336
                gridRef.current?.damage([{ cell: gridSelection.current.cell }]);
×
UNCOV
1337
            }
×
1338
        },
16✔
1339
        [getMangledCellContent, gridSelection, mangledOnCellsEdited, setOverlaySimple]
649✔
1340
    );
649✔
1341

649✔
1342
    const focusOnRowFromTrailingBlankRow = React.useCallback(
649✔
1343
        (col: number, row: number) => {
649✔
1344
            const bounds = gridRef.current?.getBounds(col, row);
1✔
1345
            if (bounds === undefined || scrollRef.current === null) {
1!
1346
                return;
×
UNCOV
1347
            }
×
1348

1✔
1349
            const content = getMangledCellContent([col, row]);
1✔
1350
            if (!content.allowOverlay) {
1!
1351
                return;
×
UNCOV
1352
            }
×
1353

1✔
1354
            setOverlaySimple({
1✔
1355
                target: bounds,
1✔
1356
                content,
1✔
1357
                initialValue: undefined,
1✔
1358
                highlight: true,
1✔
1359
                cell: [col, row],
1✔
1360
                forceEditMode: true,
1✔
1361
            });
1✔
1362
        },
1✔
1363
        [getMangledCellContent, setOverlaySimple]
649✔
1364
    );
649✔
1365

649✔
1366
    const scrollTo = React.useCallback<ScrollToFn>(
649✔
1367
        (col, row, dir = "both", paddingX = 0, paddingY = 0, options = undefined): void => {
649✔
1368
            if (scrollRef.current !== null) {
43✔
1369
                const grid = gridRef.current;
43✔
1370
                const canvas = canvasRef.current;
43✔
1371

43✔
1372
                const trueCol = typeof col !== "number" ? (col.unit === "cell" ? col.amount : undefined) : col;
43!
1373
                const trueRow = typeof row !== "number" ? (row.unit === "cell" ? row.amount : undefined) : row;
43!
1374
                const desiredX = typeof col !== "number" && col.unit === "px" ? col.amount : undefined;
43!
1375
                const desiredY = typeof row !== "number" && row.unit === "px" ? row.amount : undefined;
43✔
1376
                if (grid !== null && canvas !== null) {
43✔
1377
                    let targetRect: Rectangle = {
43✔
1378
                        x: 0,
43✔
1379
                        y: 0,
43✔
1380
                        width: 0,
43✔
1381
                        height: 0,
43✔
1382
                    };
43✔
1383

43✔
1384
                    let scrollX = 0;
43✔
1385
                    let scrollY = 0;
43✔
1386

43✔
1387
                    if (trueCol !== undefined || trueRow !== undefined) {
43!
1388
                        targetRect = grid.getBounds((trueCol ?? 0) + rowMarkerOffset, trueRow ?? 0) ?? targetRect;
43!
1389
                        if (targetRect.width === 0 || targetRect.height === 0) return;
43!
1390
                    }
43✔
1391

43✔
1392
                    const scrollBounds = canvas.getBoundingClientRect();
43✔
1393
                    const scale = scrollBounds.width / canvas.offsetWidth;
43✔
1394

43✔
1395
                    if (desiredX !== undefined) {
43!
1396
                        targetRect = {
×
UNCOV
1397
                            ...targetRect,
×
UNCOV
1398
                            x: desiredX - scrollBounds.left - scrollRef.current.scrollLeft,
×
UNCOV
1399
                            width: 1,
×
UNCOV
1400
                        };
×
UNCOV
1401
                    }
×
1402
                    if (desiredY !== undefined) {
43✔
1403
                        targetRect = {
4✔
1404
                            ...targetRect,
4✔
1405
                            y: desiredY + scrollBounds.top - scrollRef.current.scrollTop,
4✔
1406
                            height: 1,
4✔
1407
                        };
4✔
1408
                    }
4✔
1409

43✔
1410
                    if (targetRect !== undefined) {
43✔
1411
                        const bounds = {
43✔
1412
                            x: targetRect.x - paddingX,
43✔
1413
                            y: targetRect.y - paddingY,
43✔
1414
                            width: targetRect.width + 2 * paddingX,
43✔
1415
                            height: targetRect.height + 2 * paddingY,
43✔
1416
                        };
43✔
1417

43✔
1418
                        let frozenWidth = 0;
43✔
1419
                        for (let i = 0; i < freezeColumns; i++) {
43!
1420
                            frozenWidth += columns[i].width;
×
UNCOV
1421
                        }
×
1422
                        let trailingRowHeight = 0;
43✔
1423
                        if (lastRowSticky) {
43✔
1424
                            trailingRowHeight = typeof rowHeight === "number" ? rowHeight : rowHeight(rows);
43!
1425
                        }
43✔
1426

43✔
1427
                        // scrollBounds is already scaled
43✔
1428
                        let sLeft = frozenWidth * scale + scrollBounds.left + rowMarkerOffset * rowMarkerWidth * scale;
43✔
1429
                        let sRight = scrollBounds.right;
43✔
1430
                        let sTop = scrollBounds.top + totalHeaderHeight * scale;
43✔
1431
                        let sBottom = scrollBounds.bottom - trailingRowHeight * scale;
43✔
1432

43✔
1433
                        const minx = targetRect.width + paddingX * 2;
43✔
1434
                        switch (options?.hAlign) {
43✔
1435
                            case "start":
43!
1436
                                sRight = sLeft + minx;
×
1437
                                break;
×
1438
                            case "end":
43!
1439
                                sLeft = sRight - minx;
×
1440
                                break;
×
1441
                            case "center":
43!
1442
                                sLeft = Math.floor((sLeft + sRight) / 2) - minx / 2;
×
1443
                                sRight = sLeft + minx;
×
1444
                                break;
×
1445
                        }
43✔
1446

43✔
1447
                        const miny = targetRect.height + paddingY * 2;
43✔
1448
                        switch (options?.vAlign) {
43✔
1449
                            case "start":
43✔
1450
                                sBottom = sTop + miny;
1✔
1451
                                break;
1✔
1452
                            case "end":
43✔
1453
                                sTop = sBottom - miny;
1✔
1454
                                break;
1✔
1455
                            case "center":
43✔
1456
                                sTop = Math.floor((sTop + sBottom) / 2) - miny / 2;
1✔
1457
                                sBottom = sTop + miny;
1✔
1458
                                break;
1✔
1459
                        }
43✔
1460

43✔
1461
                        if (sLeft > bounds.x) {
43!
1462
                            scrollX = bounds.x - sLeft;
×
1463
                        } else if (sRight < bounds.x + bounds.width) {
43✔
1464
                            scrollX = bounds.x + bounds.width - sRight;
4✔
1465
                        }
4✔
1466

43✔
1467
                        if (sTop > bounds.y) {
43!
1468
                            scrollY = bounds.y - sTop;
×
1469
                        } else if (sBottom < bounds.y + bounds.height) {
43✔
1470
                            scrollY = bounds.y + bounds.height - sBottom;
12✔
1471
                        }
12✔
1472

43✔
1473
                        if (dir === "vertical" || (typeof col === "number" && col < freezeColumns)) {
43✔
1474
                            scrollX = 0;
2✔
1475
                        } else if (dir === "horizontal") {
43✔
1476
                            scrollY = 0;
6✔
1477
                        }
6✔
1478

43✔
1479
                        if (scrollX !== 0 || scrollY !== 0) {
43✔
1480
                            // Remove scaling as scrollTo method is unaffected by transform scale.
15✔
1481
                            if (scale !== 1) {
15!
1482
                                scrollX /= scale;
×
1483
                                scrollY /= scale;
×
UNCOV
1484
                            }
×
1485
                            scrollRef.current.scrollTo(
15✔
1486
                                scrollX + scrollRef.current.scrollLeft,
15✔
1487
                                scrollY + scrollRef.current.scrollTop
15✔
1488
                            );
15✔
1489
                        }
15✔
1490
                    }
43✔
1491
                }
43✔
1492
            }
43✔
1493
        },
43✔
1494
        [rowMarkerOffset, rowMarkerWidth, totalHeaderHeight, lastRowSticky, freezeColumns, columns, rowHeight, rows]
649✔
1495
    );
649✔
1496

649✔
1497
    const focusCallback = React.useRef(focusOnRowFromTrailingBlankRow);
649✔
1498
    const getCellContentRef = React.useRef(getCellContent);
649✔
1499
    const rowsRef = React.useRef(rows);
649✔
1500
    focusCallback.current = focusOnRowFromTrailingBlankRow;
649✔
1501
    getCellContentRef.current = getCellContent;
649✔
1502
    rowsRef.current = rows;
649✔
1503
    const appendRow = React.useCallback(
649✔
1504
        async (col: number, openOverlay: boolean = true): Promise<void> => {
649✔
1505
            const c = mangledCols[col];
1✔
1506
            if (c?.trailingRowOptions?.disabled === true) {
1!
1507
                return;
×
UNCOV
1508
            }
×
1509
            const appendResult = onRowAppended?.();
1✔
1510

1✔
1511
            let r: "top" | "bottom" | number | undefined = undefined;
1✔
1512
            let bottom = true;
1✔
1513
            if (appendResult !== undefined) {
1!
1514
                r = await appendResult;
×
1515
                if (r === "top") bottom = false;
×
1516
                if (typeof r === "number") bottom = false;
×
UNCOV
1517
            }
×
1518

1✔
1519
            let backoff = 0;
1✔
1520
            const doFocus = () => {
1✔
1521
                if (rowsRef.current <= rows) {
2✔
1522
                    if (backoff < 500) {
1✔
1523
                        window.setTimeout(doFocus, backoff);
1✔
1524
                    }
1✔
1525
                    backoff = 50 + backoff * 2;
1✔
1526
                    return;
1✔
1527
                }
1✔
1528

1✔
1529
                const row = typeof r === "number" ? r : bottom ? rows : 0;
2!
1530
                scrollTo(col - rowMarkerOffset, row);
2✔
1531
                setCurrent(
2✔
1532
                    {
2✔
1533
                        cell: [col, row],
2✔
1534
                        range: {
2✔
1535
                            x: col,
2✔
1536
                            y: row,
2✔
1537
                            width: 1,
2✔
1538
                            height: 1,
2✔
1539
                        },
2✔
1540
                    },
2✔
1541
                    false,
2✔
1542
                    false,
2✔
1543
                    "edit"
2✔
1544
                );
2✔
1545

2✔
1546
                const cell = getCellContentRef.current([col - rowMarkerOffset, row]);
2✔
1547
                if (cell.allowOverlay && isReadWriteCell(cell) && cell.readonly !== true && openOverlay) {
2✔
1548
                    // wait for scroll to have a chance to process
1✔
1549
                    window.setTimeout(() => {
1✔
1550
                        focusCallback.current(col, row);
1✔
1551
                    }, 0);
1✔
1552
                }
1✔
1553
            };
2✔
1554
            // Queue up to allow the consumer to react to the event and let us check if they did
1✔
1555
            doFocus();
1✔
1556
        },
1✔
1557
        [mangledCols, onRowAppended, rowMarkerOffset, rows, scrollTo, setCurrent]
649✔
1558
    );
649✔
1559

649✔
1560
    const getCustomNewRowTargetColumn = React.useCallback(
649✔
1561
        (col: number): number | undefined => {
649✔
1562
            const customTargetColumn =
1✔
1563
                columns[col]?.trailingRowOptions?.targetColumn ?? trailingRowOptions?.targetColumn;
1!
1564

1✔
1565
            if (typeof customTargetColumn === "number") {
1!
1566
                const customTargetOffset = hasRowMarkers ? 1 : 0;
×
1567
                return customTargetColumn + customTargetOffset;
×
UNCOV
1568
            }
×
1569

1✔
1570
            if (typeof customTargetColumn === "object") {
1!
1571
                const maybeIndex = columnsIn.indexOf(customTargetColumn);
×
UNCOV
1572
                if (maybeIndex >= 0) {
×
1573
                    const customTargetOffset = hasRowMarkers ? 1 : 0;
×
1574
                    return maybeIndex + customTargetOffset;
×
UNCOV
1575
                }
×
UNCOV
1576
            }
×
1577

1✔
1578
            return undefined;
1✔
1579
        },
1✔
1580
        [columns, columnsIn, hasRowMarkers, trailingRowOptions?.targetColumn]
649✔
1581
    );
649✔
1582

649✔
1583
    const lastSelectedRowRef = React.useRef<number>();
649✔
1584
    const lastSelectedColRef = React.useRef<number>();
649✔
1585

649✔
1586
    const themeForCell = React.useCallback(
649✔
1587
        (cell: InnerGridCell, pos: Item): Theme => {
649✔
1588
            const [col, row] = pos;
20✔
1589
            return {
20✔
1590
                ...mergedTheme,
20✔
1591
                ...mangledCols[col]?.themeOverride,
20✔
1592
                ...getRowThemeOverride?.(row),
20!
1593
                ...cell.themeOverride,
20✔
1594
            };
20✔
1595
        },
20✔
1596
        [getRowThemeOverride, mangledCols, mergedTheme]
649✔
1597
    );
649✔
1598

649✔
1599
    const handleSelect = React.useCallback(
649✔
1600
        (args: GridMouseEventArgs) => {
649✔
1601
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
113!
1602
            const isMultiRow = isMultiKey && rowSelect === "multi";
113✔
1603
            const isMultiCol = isMultiKey && columnSelect === "multi";
113✔
1604
            const [col, row] = args.location;
113✔
1605
            const selectedColumns = gridSelection.columns;
113✔
1606
            const selectedRows = gridSelection.rows;
113✔
1607
            const [cellCol, cellRow] = gridSelection.current?.cell ?? [];
113✔
1608
            // eslint-disable-next-line unicorn/prefer-switch
113✔
1609
            if (args.kind === "cell") {
113✔
1610
                lastSelectedColRef.current = undefined;
97✔
1611

97✔
1612
                lastMouseSelectLocation.current = [col, row];
97✔
1613

97✔
1614
                if (col === 0 && hasRowMarkers) {
97✔
1615
                    if (
15✔
1616
                        (showTrailingBlankRow === true && row === rows) ||
15✔
1617
                        rowMarkers === "number" ||
15✔
1618
                        rowSelect === "none"
14✔
1619
                    )
15✔
1620
                        return;
15✔
1621

14✔
1622
                    const markerCell = getMangledCellContent(args.location);
14✔
1623
                    if (markerCell.kind !== InnerGridCellKind.Marker) {
15!
1624
                        return;
×
UNCOV
1625
                    }
✔
1626

14✔
1627
                    if (onRowMoved !== undefined) {
15!
1628
                        const renderer = getCellRenderer(markerCell);
×
1629
                        assert(renderer?.kind === InnerGridCellKind.Marker);
×
1630
                        const postClick = renderer?.onClick?.({
×
UNCOV
1631
                            ...args,
×
UNCOV
1632
                            cell: markerCell,
×
UNCOV
1633
                            posX: args.localEventX,
×
UNCOV
1634
                            posY: args.localEventY,
×
UNCOV
1635
                            bounds: args.bounds,
×
UNCOV
1636
                            theme: themeForCell(markerCell, args.location),
×
1637
                            preventDefault: () => undefined,
×
UNCOV
1638
                        }) as MarkerCell | undefined;
×
1639
                        if (postClick === undefined || postClick.checked === markerCell.checked) return;
×
UNCOV
1640
                    }
✔
1641

14✔
1642
                    setOverlay(undefined);
14✔
1643
                    focus();
14✔
1644
                    const isSelected = selectedRows.hasIndex(row);
14✔
1645

14✔
1646
                    const lastHighlighted = lastSelectedRowRef.current;
14✔
1647
                    if (
14✔
1648
                        rowSelect === "multi" &&
14✔
1649
                        (args.shiftKey || args.isLongTouch === true) &&
8✔
1650
                        lastHighlighted !== undefined &&
1✔
1651
                        selectedRows.hasIndex(lastHighlighted)
1✔
1652
                    ) {
15✔
1653
                        const newSlice: Slice = [Math.min(lastHighlighted, row), Math.max(lastHighlighted, row) + 1];
1✔
1654

1✔
1655
                        if (isMultiRow || rowSelectionMode === "multi") {
1!
1656
                            setSelectedRows(undefined, newSlice, true);
×
1657
                        } else {
1✔
1658
                            setSelectedRows(CompactSelection.fromSingleSelection(newSlice), undefined, isMultiRow);
1✔
1659
                        }
1✔
1660
                    } else if (isMultiRow || args.isTouch || rowSelectionMode === "multi") {
15✔
1661
                        if (isSelected) {
3✔
1662
                            setSelectedRows(selectedRows.remove(row), undefined, true);
1✔
1663
                        } else {
2✔
1664
                            setSelectedRows(undefined, row, true);
2✔
1665
                            lastSelectedRowRef.current = row;
2✔
1666
                        }
2✔
1667
                    } else if (isSelected && selectedRows.length === 1) {
13✔
1668
                        setSelectedRows(CompactSelection.empty(), undefined, isMultiKey);
1✔
1669
                    } else {
10✔
1670
                        setSelectedRows(CompactSelection.fromSingleSelection(row), undefined, isMultiKey);
9✔
1671
                        lastSelectedRowRef.current = row;
9✔
1672
                    }
9✔
1673
                } else if (col >= rowMarkerOffset && showTrailingBlankRow && row === rows) {
97✔
1674
                    const customTargetColumn = getCustomNewRowTargetColumn(col);
1✔
1675
                    void appendRow(customTargetColumn ?? col);
1✔
1676
                } else {
82✔
1677
                    if (cellCol !== col || cellRow !== row) {
81✔
1678
                        const cell = getMangledCellContent(args.location);
75✔
1679
                        const renderer = getCellRenderer(cell);
75✔
1680

75✔
1681
                        if (renderer?.onSelect !== undefined) {
75!
1682
                            let prevented = false;
×
1683
                            renderer.onSelect({
×
UNCOV
1684
                                ...args,
×
UNCOV
1685
                                cell,
×
UNCOV
1686
                                posX: args.localEventX,
×
UNCOV
1687
                                posY: args.localEventY,
×
UNCOV
1688
                                bounds: args.bounds,
×
1689
                                preventDefault: () => (prevented = true),
×
UNCOV
1690
                                theme: themeForCell(cell, args.location),
×
UNCOV
1691
                            });
×
UNCOV
1692
                            if (prevented) {
×
1693
                                return;
×
UNCOV
1694
                            }
×
UNCOV
1695
                        }
×
1696
                        const isLastStickyRow = lastRowSticky && row === rows;
75✔
1697

75✔
1698
                        const startedFromLastSticky =
75✔
1699
                            lastRowSticky && gridSelection !== undefined && gridSelection.current?.cell[1] === rows;
75✔
1700

75✔
1701
                        if (
75✔
1702
                            (args.shiftKey || args.isLongTouch === true) &&
75✔
1703
                            cellCol !== undefined &&
6✔
1704
                            cellRow !== undefined &&
6✔
1705
                            gridSelection.current !== undefined &&
6✔
1706
                            !startedFromLastSticky
6✔
1707
                        ) {
75✔
1708
                            if (isLastStickyRow) {
6!
UNCOV
1709
                                // If we're making a selection and shift click in to the last sticky row,
×
UNCOV
1710
                                // just drop the event. Don't kill the selection.
×
1711
                                return;
×
UNCOV
1712
                            }
×
1713

6✔
1714
                            const left = Math.min(col, cellCol);
6✔
1715
                            const right = Math.max(col, cellCol);
6✔
1716
                            const top = Math.min(row, cellRow);
6✔
1717
                            const bottom = Math.max(row, cellRow);
6✔
1718
                            setCurrent(
6✔
1719
                                {
6✔
1720
                                    ...gridSelection.current,
6✔
1721
                                    range: {
6✔
1722
                                        x: left,
6✔
1723
                                        y: top,
6✔
1724
                                        width: right - left + 1,
6✔
1725
                                        height: bottom - top + 1,
6✔
1726
                                    },
6✔
1727
                                },
6✔
1728
                                true,
6✔
1729
                                isMultiKey,
6✔
1730
                                "click"
6✔
1731
                            );
6✔
1732
                            lastSelectedRowRef.current = undefined;
6✔
1733
                            focus();
6✔
1734
                        } else {
75✔
1735
                            setCurrent(
69✔
1736
                                {
69✔
1737
                                    cell: [col, row],
69✔
1738
                                    range: { x: col, y: row, width: 1, height: 1 },
69✔
1739
                                },
69✔
1740
                                true,
69✔
1741
                                isMultiKey,
69✔
1742
                                "click"
69✔
1743
                            );
69✔
1744
                            lastSelectedRowRef.current = undefined;
69✔
1745
                            setOverlay(undefined);
69✔
1746
                            focus();
69✔
1747
                        }
69✔
1748
                    }
75✔
1749
                }
81✔
1750
            } else if (args.kind === "header") {
113✔
1751
                lastMouseSelectLocation.current = [col, row];
12✔
1752
                setOverlay(undefined);
12✔
1753
                if (hasRowMarkers && col === 0) {
12✔
1754
                    lastSelectedRowRef.current = undefined;
4✔
1755
                    lastSelectedColRef.current = undefined;
4✔
1756
                    if (rowSelect === "multi") {
4✔
1757
                        if (selectedRows.length !== rows) {
4✔
1758
                            setSelectedRows(CompactSelection.fromSingleSelection([0, rows]), undefined, isMultiKey);
3✔
1759
                        } else {
4✔
1760
                            setSelectedRows(CompactSelection.empty(), undefined, isMultiKey);
1✔
1761
                        }
1✔
1762
                        focus();
4✔
1763
                    }
4✔
1764
                } else {
12✔
1765
                    const lastCol = lastSelectedColRef.current;
8✔
1766
                    if (
8✔
1767
                        columnSelect === "multi" &&
8✔
1768
                        (args.shiftKey || args.isLongTouch === true) &&
7!
UNCOV
1769
                        lastCol !== undefined &&
×
UNCOV
1770
                        selectedColumns.hasIndex(lastCol)
×
1771
                    ) {
8!
1772
                        const newSlice: Slice = [Math.min(lastCol, col), Math.max(lastCol, col) + 1];
×
UNCOV
1773

×
UNCOV
1774
                        if (isMultiCol) {
×
1775
                            setSelectedColumns(undefined, newSlice, isMultiKey);
×
UNCOV
1776
                        } else {
×
1777
                            setSelectedColumns(CompactSelection.fromSingleSelection(newSlice), undefined, isMultiKey);
×
UNCOV
1778
                        }
×
1779
                    } else if (isMultiCol) {
8✔
1780
                        if (selectedColumns.hasIndex(col)) {
1!
1781
                            setSelectedColumns(selectedColumns.remove(col), undefined, isMultiKey);
×
1782
                        } else {
1✔
1783
                            setSelectedColumns(undefined, col, isMultiKey);
1✔
1784
                        }
1✔
1785
                        lastSelectedColRef.current = col;
1✔
1786
                    } else if (columnSelect !== "none") {
8✔
1787
                        setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, isMultiKey);
7✔
1788
                        lastSelectedColRef.current = col;
7✔
1789
                    }
7✔
1790
                    lastSelectedRowRef.current = undefined;
8✔
1791
                    focus();
8✔
1792
                }
8✔
1793
            } else if (args.kind === groupHeaderKind) {
16✔
1794
                lastMouseSelectLocation.current = [col, row];
3✔
1795
            } else if (args.kind === outOfBoundsKind && !args.isMaybeScrollbar) {
4✔
1796
                setGridSelection(emptyGridSelection, false);
1✔
1797
                setOverlay(undefined);
1✔
1798
                focus();
1✔
1799
                onSelectionCleared?.();
1!
1800
                lastSelectedRowRef.current = undefined;
1✔
1801
                lastSelectedColRef.current = undefined;
1✔
1802
            }
1✔
1803
        },
113✔
1804
        [
649✔
1805
            appendRow,
649✔
1806
            columnSelect,
649✔
1807
            focus,
649✔
1808
            getCellRenderer,
649✔
1809
            getCustomNewRowTargetColumn,
649✔
1810
            getMangledCellContent,
649✔
1811
            gridSelection,
649✔
1812
            hasRowMarkers,
649✔
1813
            lastRowSticky,
649✔
1814
            onSelectionCleared,
649✔
1815
            onRowMoved,
649✔
1816
            rowMarkerOffset,
649✔
1817
            rowMarkers,
649✔
1818
            rowSelect,
649✔
1819
            rowSelectionMode,
649✔
1820
            rows,
649✔
1821
            setCurrent,
649✔
1822
            setGridSelection,
649✔
1823
            setSelectedColumns,
649✔
1824
            setSelectedRows,
649✔
1825
            showTrailingBlankRow,
649✔
1826
            themeForCell,
649✔
1827
        ]
649✔
1828
    );
649✔
1829
    const isActivelyDraggingHeader = React.useRef(false);
649✔
1830
    const lastMouseSelectLocation = React.useRef<readonly [number, number]>();
649✔
1831
    const touchDownArgs = React.useRef(visibleRegion);
649✔
1832
    const mouseDownData = React.useRef<{
649✔
1833
        wasDoubleClick: boolean;
649✔
1834
        time: number;
649✔
1835
        button: number;
649✔
1836
        location: Item;
649✔
1837
    }>();
649✔
1838
    const onMouseDown = React.useCallback(
649✔
1839
        (args: GridMouseEventArgs) => {
649✔
1840
            isPrevented.current = false;
126✔
1841
            touchDownArgs.current = visibleRegionRef.current;
126✔
1842
            if (args.button !== 0 && args.button !== 1) {
126✔
1843
                mouseDownData.current = undefined;
1✔
1844
                return;
1✔
1845
            }
1✔
1846

125✔
1847
            const time = performance.now();
125✔
1848
            const wasDoubleClick = time - (mouseDownData.current?.time ?? -1000) < 250;
126✔
1849
            mouseDownData.current = {
126✔
1850
                wasDoubleClick,
126✔
1851
                button: args.button,
126✔
1852
                time,
126✔
1853
                location: args.location,
126✔
1854
            };
126✔
1855

126✔
1856
            if (args?.kind === "header") {
126✔
1857
                isActivelyDraggingHeader.current = true;
18✔
1858
            }
18✔
1859

125✔
1860
            const fh = args.kind === "cell" && args.isFillHandle;
126✔
1861

126✔
1862
            if (!fh && args.kind !== "cell" && args.isEdge) return;
126✔
1863

118✔
1864
            setMouseState({
118✔
1865
                previousSelection: gridSelection,
118✔
1866
                fillHandle: fh,
118✔
1867
            });
118✔
1868
            lastMouseSelectLocation.current = undefined;
118✔
1869

118✔
1870
            if (!args.isTouch && args.button === 0) {
126✔
1871
                handleSelect(args);
110✔
1872
            } else if (!args.isTouch && args.button === 1) {
126✔
1873
                lastMouseSelectLocation.current = args.location;
4✔
1874
            }
4✔
1875
        },
126✔
1876
        [gridSelection, handleSelect]
649✔
1877
    );
649✔
1878

649✔
1879
    const [renameGroup, setRenameGroup] = React.useState<{
649✔
1880
        group: string;
649✔
1881
        bounds: Rectangle;
649✔
1882
    }>();
649✔
1883

649✔
1884
    const handleGroupHeaderSelection = React.useCallback(
649✔
1885
        (args: GridMouseEventArgs) => {
649✔
1886
            if (args.kind !== groupHeaderKind || columnSelect !== "multi") {
3!
1887
                return;
×
UNCOV
1888
            }
×
1889
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
3!
1890
            const [col] = args.location;
3✔
1891
            const selectedColumns = gridSelection.columns;
3✔
1892

3✔
1893
            if (col < rowMarkerOffset) return;
3!
1894

3✔
1895
            const needle = mangledCols[col];
3✔
1896
            let start = col;
3✔
1897
            let end = col;
3✔
1898
            for (let i = col - 1; i >= rowMarkerOffset; i--) {
3✔
1899
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
3!
1900
                start--;
3✔
1901
            }
3✔
1902

3✔
1903
            for (let i = col + 1; i < mangledCols.length; i++) {
3✔
1904
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
27!
1905
                end++;
27✔
1906
            }
27✔
1907

3✔
1908
            focus();
3✔
1909

3✔
1910
            if (isMultiKey) {
3✔
1911
                if (selectedColumns.hasAll([start, end + 1])) {
2✔
1912
                    let newVal = selectedColumns;
1✔
1913
                    for (let index = start; index <= end; index++) {
1✔
1914
                        newVal = newVal.remove(index);
11✔
1915
                    }
11✔
1916
                    setSelectedColumns(newVal, undefined, isMultiKey);
1✔
1917
                } else {
1✔
1918
                    setSelectedColumns(undefined, [start, end + 1], isMultiKey);
1✔
1919
                }
1✔
1920
            } else {
3✔
1921
                setSelectedColumns(CompactSelection.fromSingleSelection([start, end + 1]), undefined, isMultiKey);
1✔
1922
            }
1✔
1923
        },
3✔
1924
        [columnSelect, focus, gridSelection.columns, mangledCols, rowMarkerOffset, setSelectedColumns]
649✔
1925
    );
649✔
1926

649✔
1927
    const fillDown = React.useCallback(
649✔
1928
        (reverse: boolean) => {
649✔
1929
            if (gridSelection.current === undefined) return;
4!
1930
            const v: EditListItem[] = [];
4✔
1931
            const r = gridSelection.current.range;
4✔
1932
            for (let x = 0; x < r.width; x++) {
4✔
1933
                const fillCol = x + r.x;
5✔
1934
                const fillVal = getMangledCellContent([fillCol, reverse ? r.y + r.height - 1 : r.y]);
5!
1935
                if (isInnerOnlyCell(fillVal) || !isReadWriteCell(fillVal)) continue;
5!
1936
                for (let y = 1; y < r.height; y++) {
5✔
1937
                    const fillRow = reverse ? r.y + r.height - (y + 1) : y + r.y;
14!
1938
                    const target = [fillCol, fillRow] as const;
14✔
1939
                    v.push({
14✔
1940
                        location: target,
14✔
1941
                        value: { ...fillVal },
14✔
1942
                    });
14✔
1943
                }
14✔
1944
            }
5✔
1945

4✔
1946
            mangledOnCellsEdited(v);
4✔
1947

4✔
1948
            gridRef.current?.damage(
4✔
1949
                v.map(c => ({
4✔
1950
                    cell: c.location,
14✔
1951
                }))
4✔
1952
            );
4✔
1953
        },
4✔
1954
        [getMangledCellContent, gridSelection, mangledOnCellsEdited]
649✔
1955
    );
649✔
1956

649✔
1957
    const isPrevented = React.useRef(false);
649✔
1958

649✔
1959
    const normalSizeColumn = React.useCallback(
649✔
1960
        async (col: number, force: boolean = false): Promise<void> => {
649✔
1961
            if (
3✔
1962
                (mouseDownData.current?.wasDoubleClick === true || force) &&
3✔
1963
                getCellsForSelection !== undefined &&
2✔
1964
                onColumnResize !== undefined
2✔
1965
            ) {
3✔
1966
                const start = visibleRegionRef.current.y;
2✔
1967
                const end = visibleRegionRef.current.height;
2✔
1968
                let cells = getCellsForSelection(
2✔
1969
                    {
2✔
1970
                        x: col,
2✔
1971
                        y: start,
2✔
1972
                        width: 1,
2✔
1973
                        height: Math.min(end, rows - start),
2✔
1974
                    },
2✔
1975
                    abortControllerRef.current.signal
2✔
1976
                );
2✔
1977
                if (typeof cells !== "object") {
2!
1978
                    cells = await cells();
×
UNCOV
1979
                }
×
1980
                const inputCol = columns[col - rowMarkerOffset];
2✔
1981
                const offscreen = document.createElement("canvas");
2✔
1982
                const ctx = offscreen.getContext("2d", { alpha: false });
2✔
1983
                if (ctx !== null) {
2✔
1984
                    ctx.font = `${mergedTheme.baseFontStyle} ${mergedTheme.fontFamily}`;
2✔
1985
                    const newCol = measureColumn(
2✔
1986
                        ctx,
2✔
1987
                        mergedTheme,
2✔
1988
                        inputCol,
2✔
1989
                        0,
2✔
1990
                        cells,
2✔
1991
                        minColumnWidth,
2✔
1992
                        maxColumnWidth,
2✔
1993
                        false,
2✔
1994
                        getCellRenderer
2✔
1995
                    );
2✔
1996
                    onColumnResize?.(inputCol, newCol.width, col, newCol.width);
2✔
1997
                }
2✔
1998
            }
2✔
1999
        },
3✔
2000
        [
649✔
2001
            columns,
649✔
2002
            getCellsForSelection,
649✔
2003
            maxColumnWidth,
649✔
2004
            mergedTheme,
649✔
2005
            minColumnWidth,
649✔
2006
            onColumnResize,
649✔
2007
            rowMarkerOffset,
649✔
2008
            rows,
649✔
2009
            getCellRenderer,
649✔
2010
        ]
649✔
2011
    );
649✔
2012

649✔
2013
    const [scrollDir, setScrollDir] = React.useState<GridMouseEventArgs["scrollEdge"]>();
649✔
2014

649✔
2015
    const onMouseUp = React.useCallback(
649✔
2016
        (args: GridMouseEventArgs, isOutside: boolean) => {
649✔
2017
            const mouse = mouseState;
126✔
2018
            setMouseState(undefined);
126✔
2019
            setScrollDir(undefined);
126✔
2020
            isActivelyDraggingHeader.current = false;
126✔
2021

126✔
2022
            if (isOutside) return;
126✔
2023

124✔
2024
            if (mouse?.fillHandle === true && gridSelection.current !== undefined) {
126✔
2025
                fillDown(gridSelection.current.cell[1] !== gridSelection.current.range.y);
3✔
2026
                return;
3✔
2027
            }
3✔
2028

121✔
2029
            const [col, row] = args.location;
121✔
2030
            const [lastMouseDownCol, lastMouseDownRow] = lastMouseSelectLocation.current ?? [];
126✔
2031

126✔
2032
            const preventDefault = () => {
126✔
2033
                isPrevented.current = true;
×
UNCOV
2034
            };
×
2035

126✔
2036
            const handleMaybeClick = (a: GridMouseCellEventArgs): boolean => {
126✔
2037
                const isValidClick = a.isTouch || (lastMouseDownCol === col && lastMouseDownRow === row);
96✔
2038
                if (isValidClick) {
96✔
2039
                    onCellClicked?.([col - rowMarkerOffset, row], {
86✔
2040
                        ...a,
4✔
2041
                        preventDefault,
4✔
2042
                    });
4✔
2043
                }
86✔
2044
                if (a.button === 1) return !isPrevented.current;
96✔
2045
                if (!isPrevented.current) {
93✔
2046
                    const c = getMangledCellContent(args.location);
93✔
2047
                    const r = getCellRenderer(c);
93✔
2048
                    if (r !== undefined && r.onClick !== undefined && isValidClick) {
93✔
2049
                        const newVal = r.onClick({
20✔
2050
                            ...a,
20✔
2051
                            cell: c,
20✔
2052
                            posX: a.localEventX,
20✔
2053
                            posY: a.localEventY,
20✔
2054
                            bounds: a.bounds,
20✔
2055
                            theme: themeForCell(c, args.location),
20✔
2056
                            preventDefault,
20✔
2057
                        });
20✔
2058
                        if (newVal !== undefined && !isInnerOnlyCell(newVal) && isEditableGridCell(newVal)) {
20✔
2059
                            mangledOnCellsEdited([{ location: a.location, value: newVal }]);
4✔
2060
                            gridRef.current?.damage([
4✔
2061
                                {
4✔
2062
                                    cell: a.location,
4✔
2063
                                },
4✔
2064
                            ]);
4✔
2065
                        }
4✔
2066
                    }
20✔
2067
                    if (
93✔
2068
                        !isPrevented.current &&
93✔
2069
                        mouse?.previousSelection?.current?.cell !== undefined &&
93✔
2070
                        gridSelection.current !== undefined
20✔
2071
                    ) {
93✔
2072
                        const [selectedCol, selectedRow] = gridSelection.current.cell;
19✔
2073
                        const [prevCol, prevRow] = mouse.previousSelection.current.cell;
19✔
2074
                        if (col === selectedCol && col === prevCol && row === selectedRow && row === prevRow) {
19✔
2075
                            onCellActivated?.([col - rowMarkerOffset, row]);
3✔
2076
                            reselect(a.bounds, false);
3✔
2077
                            return true;
3✔
2078
                        }
3✔
2079
                    }
19✔
2080
                }
93✔
2081
                return false;
90✔
2082
            };
96✔
2083

126✔
2084
            const clickLocation = args.location[0] - rowMarkerOffset;
126✔
2085
            if (args.isTouch) {
126✔
2086
                const vr = visibleRegionRef.current;
4✔
2087
                const touchVr = touchDownArgs.current;
4✔
2088
                if (vr.x !== touchVr.x || vr.y !== touchVr.y) {
4!
UNCOV
2089
                    // we scrolled, abort
×
2090
                    return;
×
UNCOV
2091
                }
×
2092
                // take care of context menus first if long pressed item is already selected
4✔
2093
                if (args.isLongTouch === true) {
4!
UNCOV
2094
                    if (
×
UNCOV
2095
                        args.kind === "cell" &&
×
UNCOV
2096
                        gridSelection?.current?.cell[0] === col &&
×
UNCOV
2097
                        gridSelection?.current?.cell[1] === row
×
UNCOV
2098
                    ) {
×
2099
                        onCellContextMenu?.([clickLocation, args.location[1]], {
×
UNCOV
2100
                            ...args,
×
UNCOV
2101
                            preventDefault,
×
UNCOV
2102
                        });
×
2103
                        return;
×
UNCOV
2104
                    } else if (args.kind === "header" && gridSelection.columns.hasIndex(col)) {
×
2105
                        onHeaderContextMenu?.(clickLocation, { ...args, preventDefault });
×
2106
                        return;
×
UNCOV
2107
                    } else if (args.kind === groupHeaderKind) {
×
UNCOV
2108
                        if (clickLocation < 0) {
×
2109
                            return;
×
UNCOV
2110
                        }
×
UNCOV
2111

×
2112
                        onGroupHeaderContextMenu?.(clickLocation, { ...args, preventDefault });
×
2113
                        return;
×
UNCOV
2114
                    }
×
UNCOV
2115
                }
×
2116
                if (args.kind === "cell") {
4✔
2117
                    // click that cell
2✔
2118
                    if (!handleMaybeClick(args)) {
2✔
2119
                        handleSelect(args);
2✔
2120
                    }
2✔
2121
                } else if (args.kind === groupHeaderKind) {
2✔
2122
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
1✔
2123
                } else {
1✔
2124
                    if (args.kind === headerKind) {
1✔
2125
                        onHeaderClicked?.(clickLocation, {
1✔
2126
                            ...args,
1✔
2127
                            preventDefault,
1✔
2128
                        });
1✔
2129
                    }
1✔
2130
                    handleSelect(args);
1✔
2131
                }
1✔
2132
                return;
4✔
2133
            }
4✔
2134

117✔
2135
            if (args.kind === "header") {
126✔
2136
                if (clickLocation < 0) {
16✔
2137
                    return;
3✔
2138
                }
3✔
2139

13✔
2140
                if (args.isEdge) {
16✔
2141
                    void normalSizeColumn(col);
2✔
2142
                } else if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
16✔
2143
                    onHeaderClicked?.(clickLocation, { ...args, preventDefault });
5✔
2144
                }
5✔
2145
            }
16✔
2146

114✔
2147
            if (args.kind === groupHeaderKind) {
126✔
2148
                if (clickLocation < 0) {
3!
2149
                    return;
×
UNCOV
2150
                }
×
2151

3✔
2152
                if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
3✔
2153
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
3!
2154
                    if (!isPrevented.current) {
3✔
2155
                        handleGroupHeaderSelection(args);
3✔
2156
                    }
3✔
2157
                }
3✔
2158
            }
3✔
2159

114✔
2160
            if (args.kind === "cell" && (args.button === 0 || args.button === 1)) {
126✔
2161
                handleMaybeClick(args);
94✔
2162
            }
94✔
2163

114✔
2164
            lastMouseSelectLocation.current = undefined;
114✔
2165
        },
126✔
2166
        [
649✔
2167
            mouseState,
649✔
2168
            rowMarkerOffset,
649✔
2169
            gridSelection,
649✔
2170
            onCellClicked,
649✔
2171
            fillDown,
649✔
2172
            getMangledCellContent,
649✔
2173
            getCellRenderer,
649✔
2174
            themeForCell,
649✔
2175
            mangledOnCellsEdited,
649✔
2176
            onCellActivated,
649✔
2177
            reselect,
649✔
2178
            onCellContextMenu,
649✔
2179
            onHeaderContextMenu,
649✔
2180
            onGroupHeaderContextMenu,
649✔
2181
            handleSelect,
649✔
2182
            onGroupHeaderClicked,
649✔
2183
            normalSizeColumn,
649✔
2184
            onHeaderClicked,
649✔
2185
            handleGroupHeaderSelection,
649✔
2186
        ]
649✔
2187
    );
649✔
2188

649✔
2189
    const onMouseMoveImpl = React.useCallback(
649✔
2190
        (args: GridMouseEventArgs) => {
649✔
2191
            const a: GridMouseEventArgs = {
37✔
2192
                ...args,
37✔
2193
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
37✔
2194
            };
37✔
2195
            onMouseMove?.(a);
37✔
2196
            setScrollDir(cv => {
37✔
2197
                if (isActivelyDraggingHeader.current) return [args.scrollEdge[0], 0];
37✔
2198
                if (args.scrollEdge[0] === cv?.[0] && args.scrollEdge[1] === cv[1]) return cv;
37!
2199
                return mouseState === undefined || (mouseDownData.current?.location[0] ?? 0) < rowMarkerOffset
35!
2200
                    ? undefined
13✔
2201
                    : args.scrollEdge;
13✔
2202
            });
37✔
2203
        },
37✔
2204
        [mouseState, onMouseMove, rowMarkerOffset]
649✔
2205
    );
649✔
2206

649✔
2207
    useAutoscroll(scrollDir, scrollRef);
649✔
2208

649✔
2209
    const onHeaderMenuClickInner = React.useCallback(
649✔
2210
        (col: number, screenPosition: Rectangle) => {
649✔
2211
            onHeaderMenuClick?.(col - rowMarkerOffset, screenPosition);
1✔
2212
        },
1✔
2213
        [onHeaderMenuClick, rowMarkerOffset]
649✔
2214
    );
649✔
2215

649✔
2216
    const currentCell = gridSelection?.current?.cell;
649✔
2217
    const onVisibleRegionChangedImpl = React.useCallback(
649✔
2218
        (
649✔
2219
            region: Rectangle,
136✔
2220
            clientWidth: number,
136✔
2221
            clientHeight: number,
136✔
2222
            rightElWidth: number,
136✔
2223
            tx?: number,
136✔
2224
            ty?: number
136✔
2225
        ) => {
136✔
2226
            hasJustScrolled.current = false;
136✔
2227
            let selected = currentCell;
136✔
2228
            if (selected !== undefined) {
136✔
2229
                selected = [selected[0] - rowMarkerOffset, selected[1]];
10✔
2230
            }
10✔
2231
            const newRegion = {
136✔
2232
                x: region.x - rowMarkerOffset,
136✔
2233
                y: region.y,
136✔
2234
                width: region.width,
136✔
2235
                height: showTrailingBlankRow && region.y + region.height >= rows ? region.height - 1 : region.height,
136✔
2236
                tx,
136✔
2237
                ty,
136✔
2238
                extras: {
136✔
2239
                    selected,
136✔
2240
                    freezeRegion:
136✔
2241
                        freezeColumns === 0
136✔
2242
                            ? undefined
136!
UNCOV
2243
                            : {
×
UNCOV
2244
                                  x: 0,
×
UNCOV
2245
                                  y: region.y,
×
UNCOV
2246
                                  width: freezeColumns,
×
UNCOV
2247
                                  height: region.height,
×
UNCOV
2248
                              },
×
2249
                },
136✔
2250
            };
136✔
2251
            visibleRegionRef.current = newRegion;
136✔
2252
            setVisibleRegion(newRegion);
136✔
2253
            setClientSize([clientWidth, clientHeight, rightElWidth]);
136✔
2254
            onVisibleRegionChanged?.(newRegion, newRegion.tx, newRegion.ty, newRegion.extras);
136!
2255
        },
136✔
2256
        [
649✔
2257
            currentCell,
649✔
2258
            rowMarkerOffset,
649✔
2259
            showTrailingBlankRow,
649✔
2260
            rows,
649✔
2261
            freezeColumns,
649✔
2262
            setVisibleRegion,
649✔
2263
            onVisibleRegionChanged,
649✔
2264
        ]
649✔
2265
    );
649✔
2266

649✔
2267
    const onColumnMovedImpl = whenDefined(
649✔
2268
        onColumnMoved,
649✔
2269
        React.useCallback(
649✔
2270
            (startIndex: number, endIndex: number) => {
649✔
2271
                onColumnMoved?.(startIndex - rowMarkerOffset, endIndex - rowMarkerOffset);
1✔
2272
                if (columnSelect !== "none") {
1✔
2273
                    setSelectedColumns(CompactSelection.fromSingleSelection(endIndex), undefined, true);
1✔
2274
                }
1✔
2275
            },
1✔
2276
            [columnSelect, onColumnMoved, rowMarkerOffset, setSelectedColumns]
649✔
2277
        )
649✔
2278
    );
649✔
2279

649✔
2280
    const isActivelyDragging = React.useRef(false);
649✔
2281
    const onDragStartImpl = React.useCallback(
649✔
2282
        (args: GridDragEventArgs) => {
649✔
2283
            if (args.location[0] === 0 && rowMarkerOffset > 0) {
1!
2284
                args.preventDefault();
×
2285
                return;
×
UNCOV
2286
            }
×
2287
            onDragStart?.({
1✔
2288
                ...args,
1✔
2289
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
1✔
2290
            });
1✔
2291

1✔
2292
            if (!args.defaultPrevented()) {
1✔
2293
                isActivelyDragging.current = true;
1✔
2294
            }
1✔
2295
            setMouseState(undefined);
1✔
2296
        },
1✔
2297
        [onDragStart, rowMarkerOffset]
649✔
2298
    );
649✔
2299

649✔
2300
    const onDragEnd = React.useCallback(() => {
649✔
2301
        isActivelyDragging.current = false;
×
2302
    }, []);
649✔
2303

649✔
2304
    const onItemHoveredImpl = React.useCallback(
649✔
2305
        (args: GridMouseEventArgs) => {
649✔
2306
            if (mouseDownData?.current?.button !== undefined && mouseDownData.current.button >= 1) return;
32✔
2307
            if (
31✔
2308
                mouseState !== undefined &&
31✔
2309
                mouseDownData.current?.location[0] === 0 &&
18✔
2310
                args.location[0] === 0 &&
3✔
2311
                rowMarkerOffset === 1 &&
3✔
2312
                rowSelect === "multi" &&
3✔
2313
                mouseState.previousSelection &&
2✔
2314
                !mouseState.previousSelection.rows.hasIndex(mouseDownData.current.location[1]) &&
2✔
2315
                gridSelection.rows.hasIndex(mouseDownData.current.location[1])
2✔
2316
            ) {
32✔
2317
                const start = Math.min(mouseDownData.current.location[1], args.location[1]);
2✔
2318
                const end = Math.max(mouseDownData.current.location[1], args.location[1]) + 1;
2✔
2319
                setSelectedRows(CompactSelection.fromSingleSelection([start, end]), undefined, false);
2✔
2320
            }
2✔
2321
            if (
31✔
2322
                mouseState !== undefined &&
31✔
2323
                gridSelection.current !== undefined &&
18✔
2324
                !isActivelyDragging.current &&
16✔
2325
                (rangeSelect === "rect" || rangeSelect === "multi-rect")
16✔
2326
            ) {
32✔
2327
                const [selectedCol, selectedRow] = gridSelection.current.cell;
10✔
2328
                // eslint-disable-next-line prefer-const
10✔
2329
                let [col, row] = args.location;
10✔
2330

10✔
2331
                if (row < 0) {
10✔
2332
                    row = visibleRegionRef.current.y;
1✔
2333
                }
1✔
2334

10✔
2335
                const startedFromLastStickyRow = lastRowSticky && selectedRow === rows;
10✔
2336
                if (startedFromLastStickyRow) return;
10!
2337

10✔
2338
                const landedOnLastStickyRow = lastRowSticky && row === rows;
10✔
2339
                if (landedOnLastStickyRow) {
10✔
2340
                    if (args.kind === outOfBoundsKind) row--;
3✔
2341
                    else return;
1✔
2342
                }
3✔
2343

9✔
2344
                col = Math.max(col, rowMarkerOffset);
9✔
2345

9✔
2346
                const deltaX = col - selectedCol;
9✔
2347
                const deltaY = row - selectedRow;
9✔
2348

9✔
2349
                const newRange: Rectangle = {
9✔
2350
                    x: deltaX >= 0 ? selectedCol : col,
10!
2351
                    y: deltaY >= 0 ? selectedRow : row,
10✔
2352
                    width: Math.abs(deltaX) + 1,
10✔
2353
                    height: Math.abs(deltaY) + 1,
10✔
2354
                };
10✔
2355

10✔
2356
                setCurrent(
10✔
2357
                    {
10✔
2358
                        ...gridSelection.current,
10✔
2359
                        range: newRange,
10✔
2360
                    },
10✔
2361
                    true,
10✔
2362
                    false,
10✔
2363
                    "drag"
10✔
2364
                );
10✔
2365
            }
10✔
2366

30✔
2367
            onItemHovered?.({ ...args, location: [args.location[0] - rowMarkerOffset, args.location[1]] as any });
32✔
2368
        },
32✔
2369
        [
649✔
2370
            mouseState,
649✔
2371
            rowMarkerOffset,
649✔
2372
            rowSelect,
649✔
2373
            gridSelection,
649✔
2374
            rangeSelect,
649✔
2375
            onItemHovered,
649✔
2376
            setSelectedRows,
649✔
2377
            lastRowSticky,
649✔
2378
            rows,
649✔
2379
            setCurrent,
649✔
2380
        ]
649✔
2381
    );
649✔
2382

649✔
2383
    // 1 === move one
649✔
2384
    // 2 === move to end
649✔
2385
    const adjustSelection = React.useCallback(
649✔
2386
        (direction: [0 | 1 | -1 | 2 | -2, 0 | 1 | -1 | 2 | -2]) => {
649✔
2387
            if (gridSelection.current === undefined) return;
8!
2388

8✔
2389
            const [x, y] = direction;
8✔
2390
            const [col, row] = gridSelection.current.cell;
8✔
2391
            const old = gridSelection.current.range;
8✔
2392
            let left = old.x;
8✔
2393
            let right = old.x + old.width;
8✔
2394
            let top = old.y;
8✔
2395
            let bottom = old.y + old.height;
8✔
2396

8✔
2397
            // take care of vertical first in case new spans come in
8✔
2398
            if (y !== 0) {
8✔
2399
                switch (y) {
2✔
2400
                    case 2: {
2✔
2401
                        // go to end
1✔
2402
                        bottom = rows;
1✔
2403
                        top = row;
1✔
2404
                        scrollTo(0, bottom, "vertical");
1✔
2405

1✔
2406
                        break;
1✔
2407
                    }
1✔
2408
                    case -2: {
2!
UNCOV
2409
                        // go to start
×
2410
                        top = 0;
×
2411
                        bottom = row + 1;
×
2412
                        scrollTo(0, top, "vertical");
×
UNCOV
2413

×
2414
                        break;
×
UNCOV
2415
                    }
×
2416
                    case 1: {
2✔
2417
                        // motion down
1✔
2418
                        if (top < row) {
1!
2419
                            top++;
×
2420
                            scrollTo(0, top, "vertical");
×
2421
                        } else {
1✔
2422
                            bottom = Math.min(rows, bottom + 1);
1✔
2423
                            scrollTo(0, bottom, "vertical");
1✔
2424
                        }
1✔
2425

1✔
2426
                        break;
1✔
2427
                    }
1✔
2428
                    case -1: {
2!
UNCOV
2429
                        // motion up
×
UNCOV
2430
                        if (bottom > row + 1) {
×
2431
                            bottom--;
×
2432
                            scrollTo(0, bottom, "vertical");
×
UNCOV
2433
                        } else {
×
2434
                            top = Math.max(0, top - 1);
×
2435
                            scrollTo(0, top, "vertical");
×
UNCOV
2436
                        }
×
UNCOV
2437

×
2438
                        break;
×
UNCOV
2439
                    }
×
2440
                    default: {
2!
2441
                        assertNever(y);
×
UNCOV
2442
                    }
×
2443
                }
2✔
2444
            }
2✔
2445

8✔
2446
            if (x !== 0) {
8✔
2447
                if (x === 2) {
6✔
2448
                    right = mangledCols.length;
1✔
2449
                    left = col;
1✔
2450
                    scrollTo(right - 1 - rowMarkerOffset, 0, "horizontal");
1✔
2451
                } else if (x === -2) {
6!
2452
                    left = rowMarkerOffset;
×
2453
                    right = col + 1;
×
2454
                    scrollTo(left - rowMarkerOffset, 0, "horizontal");
×
2455
                } else {
5✔
2456
                    let disallowed: number[] = [];
5✔
2457
                    if (getCellsForSelection !== undefined) {
5✔
2458
                        const cells = getCellsForSelection(
5✔
2459
                            {
5✔
2460
                                x: left,
5✔
2461
                                y: top,
5✔
2462
                                width: right - left - rowMarkerOffset,
5✔
2463
                                height: bottom - top,
5✔
2464
                            },
5✔
2465
                            abortControllerRef.current.signal
5✔
2466
                        );
5✔
2467

5✔
2468
                        if (typeof cells === "object") {
5✔
2469
                            disallowed = getSpanStops(cells);
5✔
2470
                        }
5✔
2471
                    }
5✔
2472
                    if (x === 1) {
5✔
2473
                        // motion right
4✔
2474
                        let done = false;
4✔
2475
                        if (left < col) {
4!
UNCOV
2476
                            if (disallowed.length > 0) {
×
2477
                                const target = range(left + 1, col + 1).find(
×
2478
                                    n => !disallowed.includes(n - rowMarkerOffset)
×
UNCOV
2479
                                );
×
UNCOV
2480
                                if (target !== undefined) {
×
2481
                                    left = target;
×
2482
                                    done = true;
×
UNCOV
2483
                                }
×
UNCOV
2484
                            } else {
×
2485
                                left++;
×
2486
                                done = true;
×
UNCOV
2487
                            }
×
2488
                            if (done) scrollTo(left, 0, "horizontal");
×
UNCOV
2489
                        }
×
2490
                        if (!done) {
4✔
2491
                            right = Math.min(mangledCols.length, right + 1);
4✔
2492
                            scrollTo(right - 1 - rowMarkerOffset, 0, "horizontal");
4✔
2493
                        }
4✔
2494
                    } else if (x === -1) {
5✔
2495
                        // motion left
1✔
2496
                        let done = false;
1✔
2497
                        if (right > col + 1) {
1!
UNCOV
2498
                            if (disallowed.length > 0) {
×
2499
                                const target = range(right - 1, col, -1).find(
×
2500
                                    n => !disallowed.includes(n - rowMarkerOffset)
×
UNCOV
2501
                                );
×
UNCOV
2502
                                if (target !== undefined) {
×
2503
                                    right = target;
×
2504
                                    done = true;
×
UNCOV
2505
                                }
×
UNCOV
2506
                            } else {
×
2507
                                right--;
×
2508
                                done = true;
×
UNCOV
2509
                            }
×
2510
                            if (done) scrollTo(right - rowMarkerOffset, 0, "horizontal");
×
UNCOV
2511
                        }
×
2512
                        if (!done) {
1✔
2513
                            left = Math.max(rowMarkerOffset, left - 1);
1✔
2514
                            scrollTo(left - rowMarkerOffset, 0, "horizontal");
1✔
2515
                        }
1✔
2516
                    } else {
1!
2517
                        assertNever(x);
×
UNCOV
2518
                    }
×
2519
                }
5✔
2520
            }
6✔
2521

8✔
2522
            setCurrent(
8✔
2523
                {
8✔
2524
                    cell: gridSelection.current.cell,
8✔
2525
                    range: {
8✔
2526
                        x: left,
8✔
2527
                        y: top,
8✔
2528
                        width: right - left,
8✔
2529
                        height: bottom - top,
8✔
2530
                    },
8✔
2531
                },
8✔
2532
                true,
8✔
2533
                false,
8✔
2534
                "keyboard-select"
8✔
2535
            );
8✔
2536
        },
8✔
2537
        [getCellsForSelection, gridSelection, mangledCols.length, rowMarkerOffset, rows, scrollTo, setCurrent]
649✔
2538
    );
649✔
2539

649✔
2540
    const updateSelectedCell = React.useCallback(
649✔
2541
        (col: number, row: number, fromEditingTrailingRow: boolean, freeMove: boolean): boolean => {
649✔
2542
            const rowMax = mangledRows - (fromEditingTrailingRow ? 0 : 1);
53!
2543
            col = clamp(col, rowMarkerOffset, columns.length - 1 + rowMarkerOffset);
53✔
2544
            row = clamp(row, 0, rowMax);
53✔
2545

53✔
2546
            if (col === currentCell?.[0] && row === currentCell?.[1]) return false;
53✔
2547
            if (freeMove && gridSelection.current !== undefined) {
53✔
2548
                const newStack = [...gridSelection.current.rangeStack];
1✔
2549
                if (gridSelection.current.range.width > 1 || gridSelection.current.range.height > 1) {
1!
2550
                    newStack.push(gridSelection.current.range);
1✔
2551
                }
1✔
2552
                setGridSelection(
1✔
2553
                    {
1✔
2554
                        ...gridSelection,
1✔
2555
                        current: {
1✔
2556
                            cell: [col, row],
1✔
2557
                            range: { x: col, y: row, width: 1, height: 1 },
1✔
2558
                            rangeStack: newStack,
1✔
2559
                        },
1✔
2560
                    },
1✔
2561
                    true
1✔
2562
                );
1✔
2563
            } else {
53✔
2564
                setCurrent(
25✔
2565
                    {
25✔
2566
                        cell: [col, row],
25✔
2567
                        range: { x: col, y: row, width: 1, height: 1 },
25✔
2568
                    },
25✔
2569
                    true,
25✔
2570
                    false,
25✔
2571
                    "keyboard-nav"
25✔
2572
                );
25✔
2573
            }
25✔
2574

26✔
2575
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
53✔
2576
                lastSent.current = undefined;
2✔
2577
            }
2✔
2578

26✔
2579
            scrollTo(col - rowMarkerOffset, row);
26✔
2580

26✔
2581
            return true;
26✔
2582
        },
53✔
2583
        [
649✔
2584
            mangledRows,
649✔
2585
            rowMarkerOffset,
649✔
2586
            columns.length,
649✔
2587
            currentCell,
649✔
2588
            gridSelection,
649✔
2589
            scrollTo,
649✔
2590
            setGridSelection,
649✔
2591
            setCurrent,
649✔
2592
        ]
649✔
2593
    );
649✔
2594

649✔
2595
    const onFinishEditing = React.useCallback(
649✔
2596
        (newValue: GridCell | undefined, movement: readonly [-1 | 0 | 1, -1 | 0 | 1]) => {
649✔
2597
            if (overlay?.cell !== undefined && newValue !== undefined && isEditableGridCell(newValue)) {
7✔
2598
                mangledOnCellsEdited([{ location: overlay.cell, value: newValue }]);
4✔
2599
                window.requestAnimationFrame(() => {
4✔
2600
                    gridRef.current?.damage([
4✔
2601
                        {
4✔
2602
                            cell: overlay.cell,
4✔
2603
                        },
4✔
2604
                    ]);
4✔
2605
                });
4✔
2606
            }
4✔
2607
            focus(true);
7✔
2608
            setOverlay(undefined);
7✔
2609

7✔
2610
            const [movX, movY] = movement;
7✔
2611
            if (gridSelection.current !== undefined && (movX !== 0 || movY !== 0)) {
7✔
2612
                const isEditingTrailingRow =
3✔
2613
                    gridSelection.current.cell[1] === mangledRows - 1 && newValue !== undefined;
3!
2614
                updateSelectedCell(
3✔
2615
                    clamp(gridSelection.current.cell[0] + movX, 0, mangledCols.length - 1),
3✔
2616
                    clamp(gridSelection.current.cell[1] + movY, 0, mangledRows - 1),
3✔
2617
                    isEditingTrailingRow,
3✔
2618
                    false
3✔
2619
                );
3✔
2620
            }
3✔
2621
            onFinishedEditing?.(newValue, movement);
7✔
2622
        },
7✔
2623
        [
649✔
2624
            overlay?.cell,
649✔
2625
            focus,
649✔
2626
            gridSelection,
649✔
2627
            onFinishedEditing,
649✔
2628
            mangledOnCellsEdited,
649✔
2629
            mangledRows,
649✔
2630
            updateSelectedCell,
649✔
2631
            mangledCols.length,
649✔
2632
        ]
649✔
2633
    );
649✔
2634

649✔
2635
    const overlayID = React.useMemo(() => {
649✔
2636
        return `gdg-overlay-${idCounter++}`;
132✔
2637
    }, []);
649✔
2638

649✔
2639
    const deleteRange = React.useCallback(
649✔
2640
        (r: Rectangle) => {
649✔
2641
            focus();
8✔
2642
            const editList: EditListItem[] = [];
8✔
2643
            for (let x = r.x; x < r.x + r.width; x++) {
8✔
2644
                for (let y = r.y; y < r.y + r.height; y++) {
23✔
2645
                    const cellValue = getCellContent([x - rowMarkerOffset, y]);
1,066✔
2646
                    if (!cellValue.allowOverlay && cellValue.kind !== GridCellKind.Boolean) continue;
1,066✔
2647
                    let newVal: InnerGridCell | undefined = undefined;
1,042✔
2648
                    if (cellValue.kind === GridCellKind.Custom) {
1,066✔
2649
                        const toDelete = getCellRenderer(cellValue);
1✔
2650
                        const editor = toDelete?.provideEditor?.(cellValue);
1!
2651
                        if (toDelete?.onDelete !== undefined) {
1✔
2652
                            newVal = toDelete.onDelete(cellValue);
1✔
2653
                        } else if (isObjectEditorCallbackResult(editor)) {
1!
2654
                            newVal = editor?.deletedValue?.(cellValue);
×
UNCOV
2655
                        }
×
2656
                    } else if (
1✔
2657
                        (isEditableGridCell(cellValue) && cellValue.allowOverlay) ||
1,041✔
2658
                        cellValue.kind === GridCellKind.Boolean
1✔
2659
                    ) {
1,041✔
2660
                        const toDelete = getCellRenderer(cellValue);
1,041✔
2661
                        newVal = toDelete?.onDelete?.(cellValue);
1,041✔
2662
                    }
1,041✔
2663
                    if (newVal !== undefined && !isInnerOnlyCell(newVal) && isEditableGridCell(newVal)) {
1,066✔
2664
                        editList.push({ location: [x, y], value: newVal });
1,041✔
2665
                    }
1,041✔
2666
                }
1,066✔
2667
            }
23✔
2668
            mangledOnCellsEdited(editList);
8✔
2669
            gridRef.current?.damage(editList.map(x => ({ cell: x.location })));
8✔
2670
        },
8✔
2671
        [focus, getCellContent, getCellRenderer, mangledOnCellsEdited, rowMarkerOffset]
649✔
2672
    );
649✔
2673

649✔
2674
    const onKeyDown = React.useCallback(
649✔
2675
        (event: GridKeyEventArgs) => {
649✔
2676
            const fn = async () => {
61✔
2677
                let cancelled = false;
61✔
2678
                if (onKeyDownIn !== undefined) {
61✔
2679
                    onKeyDownIn({
1✔
2680
                        ...event,
1✔
2681
                        cancel: () => {
1✔
2682
                            cancelled = true;
×
UNCOV
2683
                        },
×
2684
                    });
1✔
2685
                }
1✔
2686

61✔
2687
                if (cancelled) return;
61!
2688

61✔
2689
                const cancel = () => {
61✔
2690
                    event.stopPropagation();
42✔
2691
                    event.preventDefault();
42✔
2692
                };
42✔
2693

61✔
2694
                const overlayOpen = overlay !== undefined;
61✔
2695
                const { altKey, shiftKey, metaKey, ctrlKey, key, bounds } = event;
61✔
2696
                const isOSX = browserIsOSX.value;
61✔
2697
                const isPrimaryKey = isOSX ? metaKey : ctrlKey;
61!
2698
                const isDeleteKey = key === "Delete" || (isOSX && key === "Backspace");
61!
2699
                const vr = visibleRegionRef.current;
61✔
2700
                const selectedColumns = gridSelection.columns;
61✔
2701
                const selectedRows = gridSelection.rows;
61✔
2702

61✔
2703
                if (key === "Escape") {
61✔
2704
                    if (overlayOpen) {
4✔
2705
                        setOverlay(undefined);
2✔
2706
                    } else if (keybindings.clear) {
2✔
2707
                        setGridSelection(emptyGridSelection, false);
2✔
2708
                        onSelectionCleared?.();
2!
2709
                    }
2✔
2710
                    return;
4✔
2711
                } else if (isHotkey("primary+a", event) && keybindings.selectAll) {
61✔
2712
                    if (!overlayOpen) {
1✔
2713
                        setGridSelection(
1✔
2714
                            {
1✔
2715
                                columns: CompactSelection.empty(),
1✔
2716
                                rows: CompactSelection.empty(),
1✔
2717
                                current: {
1✔
2718
                                    cell: gridSelection.current?.cell ?? [rowMarkerOffset, 0],
1!
2719
                                    range: {
1✔
2720
                                        x: rowMarkerOffset,
1✔
2721
                                        y: 0,
1✔
2722
                                        width: columnsIn.length,
1✔
2723
                                        height: rows,
1✔
2724
                                    },
1✔
2725
                                    rangeStack: [],
1✔
2726
                                },
1✔
2727
                            },
1✔
2728
                            false
1✔
2729
                        );
1✔
2730
                    } else {
1!
2731
                        const el = document.getElementById(overlayID);
×
UNCOV
2732
                        if (el !== null) {
×
2733
                            const s = window.getSelection();
×
2734
                            const r = document.createRange();
×
2735
                            r.selectNodeContents(el);
×
2736
                            s?.removeAllRanges();
×
2737
                            s?.addRange(r);
×
UNCOV
2738
                        }
×
UNCOV
2739
                    }
×
2740
                    cancel();
1✔
2741
                    return;
1✔
2742
                } else if (isHotkey("primary+f", event) && keybindings.search) {
57!
2743
                    cancel();
×
2744
                    searchInputRef?.current?.focus({ preventScroll: true });
×
2745
                    setShowSearchInner(true);
×
UNCOV
2746
                }
✔
2747

56✔
2748
                if (isDeleteKey) {
61✔
2749
                    const callbackResult = onDelete?.(gridSelection) ?? true;
8✔
2750
                    cancel();
8✔
2751
                    if (callbackResult !== false) {
8✔
2752
                        const toDelete = callbackResult === true ? gridSelection : callbackResult;
8✔
2753

8✔
2754
                        // delete order:
8✔
2755
                        // 1) primary range
8✔
2756
                        // 2) secondary ranges
8✔
2757
                        // 3) columns
8✔
2758
                        // 4) rows
8✔
2759

8✔
2760
                        if (toDelete.current !== undefined) {
8✔
2761
                            deleteRange(toDelete.current.range);
5✔
2762
                            for (const r of toDelete.current.rangeStack) {
5!
2763
                                deleteRange(r);
×
UNCOV
2764
                            }
×
2765
                        }
5✔
2766

8✔
2767
                        for (const r of toDelete.rows) {
8✔
2768
                            deleteRange({
1✔
2769
                                x: rowMarkerOffset,
1✔
2770
                                y: r,
1✔
2771
                                width: mangledCols.length - rowMarkerOffset,
1✔
2772
                                height: 1,
1✔
2773
                            });
1✔
2774
                        }
1✔
2775

8✔
2776
                        for (const col of toDelete.columns) {
8✔
2777
                            deleteRange({
1✔
2778
                                x: col,
1✔
2779
                                y: 0,
1✔
2780
                                width: 1,
1✔
2781
                                height: rows,
1✔
2782
                            });
1✔
2783
                        }
1✔
2784
                    }
8✔
2785
                    return;
8✔
2786
                }
8✔
2787

48✔
2788
                if (gridSelection.current === undefined) return;
48✔
2789
                let [col, row] = gridSelection.current.cell;
45✔
2790
                let freeMove = false;
45✔
2791

45✔
2792
                if (keybindings.selectColumn && isHotkey("ctrl+ ", event) && columnSelect !== "none") {
61✔
2793
                    if (selectedColumns.hasIndex(col)) {
2!
2794
                        setSelectedColumns(selectedColumns.remove(col), undefined, true);
×
2795
                    } else {
2✔
2796
                        if (columnSelect === "single") {
2!
2797
                            setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, true);
×
2798
                        } else {
2✔
2799
                            setSelectedColumns(undefined, col, true);
2✔
2800
                        }
2✔
2801
                    }
2✔
2802
                } else if (keybindings.selectRow && isHotkey("shift+ ", event) && rowSelect !== "none") {
61✔
2803
                    if (selectedRows.hasIndex(row)) {
2!
2804
                        setSelectedRows(selectedRows.remove(row), undefined, true);
×
2805
                    } else {
2✔
2806
                        if (rowSelect === "single") {
2!
2807
                            setSelectedRows(CompactSelection.fromSingleSelection(row), undefined, true);
×
2808
                        } else {
2✔
2809
                            setSelectedRows(undefined, row, true);
2✔
2810
                        }
2✔
2811
                    }
2✔
2812
                } else if (
2✔
2813
                    (isHotkey("Enter", event) || isHotkey(" ", event) || isHotkey("shift+Enter", event)) &&
41✔
2814
                    bounds !== undefined
8✔
2815
                ) {
41✔
2816
                    if (overlayOpen) {
8✔
2817
                        setOverlay(undefined);
2✔
2818
                        if (isHotkey("Enter", event)) {
2✔
2819
                            row++;
2✔
2820
                        } else if (isHotkey("shift+Enter", event)) {
2!
2821
                            row--;
×
UNCOV
2822
                        }
×
2823
                    } else if (row === rows && showTrailingBlankRow) {
8!
2824
                        window.setTimeout(() => {
×
2825
                            const customTargetColumn = getCustomNewRowTargetColumn(col);
×
2826
                            void appendRow(customTargetColumn ?? col);
×
UNCOV
2827
                        }, 0);
×
2828
                    } else {
6✔
2829
                        onCellActivated?.([col - rowMarkerOffset, row]);
6✔
2830
                        reselect(bounds, true);
6✔
2831
                        cancel();
6✔
2832
                    }
6✔
2833
                } else if (
8✔
2834
                    keybindings.downFill &&
33✔
2835
                    isHotkey("primary+_68", event) &&
1✔
2836
                    gridSelection.current.range.height > 1
1✔
2837
                ) {
33✔
2838
                    // ctrl/cmd + d
1✔
2839
                    fillDown(false);
1✔
2840
                    cancel();
1✔
2841
                } else if (
1✔
2842
                    keybindings.rightFill &&
32✔
2843
                    isHotkey("primary+_82", event) &&
1✔
2844
                    gridSelection.current.range.width > 1
1✔
2845
                ) {
32✔
2846
                    // ctrl/cmd + r
1✔
2847
                    const editList: EditListItem[] = [];
1✔
2848
                    const r = gridSelection.current.range;
1✔
2849
                    for (let y = 0; y < r.height; y++) {
1✔
2850
                        const fillRow = y + r.y;
5✔
2851
                        const fillVal = getMangledCellContent([r.x, fillRow]);
5✔
2852
                        if (isInnerOnlyCell(fillVal) || !isReadWriteCell(fillVal)) continue;
5!
2853
                        for (let x = 1; x < r.width; x++) {
5✔
2854
                            const fillCol = x + r.x;
5✔
2855
                            const target = [fillCol, fillRow] as const;
5✔
2856
                            editList.push({
5✔
2857
                                location: target,
5✔
2858
                                value: { ...fillVal },
5✔
2859
                            });
5✔
2860
                        }
5✔
2861
                    }
5✔
2862
                    mangledOnCellsEdited(editList);
1✔
2863
                    gridRef.current?.damage(
1✔
2864
                        editList.map(c => ({
1✔
2865
                            cell: c.location,
5✔
2866
                        }))
1✔
2867
                    );
1✔
2868
                    cancel();
1✔
2869
                } else if (keybindings.pageDown && isHotkey("PageDown", event)) {
32!
2870
                    row += Math.max(1, visibleRegionRef.current.height - 4); // partial cell accounting
×
2871
                    cancel();
×
2872
                } else if (keybindings.pageUp && isHotkey("PageUp", event)) {
31!
2873
                    row -= Math.max(1, visibleRegionRef.current.height - 4); // partial cell accounting
×
2874
                    cancel();
×
2875
                } else if (keybindings.first && isHotkey("primary+Home", event)) {
31!
2876
                    setOverlay(undefined);
×
2877
                    row = 0;
×
2878
                    col = 0;
×
2879
                } else if (keybindings.last && isHotkey("primary+End", event)) {
31!
2880
                    setOverlay(undefined);
×
2881
                    row = Number.MAX_SAFE_INTEGER;
×
2882
                    col = Number.MAX_SAFE_INTEGER;
×
2883
                } else if (keybindings.first && isHotkey("primary+shift+Home", event)) {
31!
2884
                    setOverlay(undefined);
×
2885
                    adjustSelection([-2, -2]);
×
2886
                } else if (keybindings.last && isHotkey("primary+shift+End", event)) {
31!
2887
                    setOverlay(undefined);
×
2888
                    adjustSelection([2, 2]);
×
UNCOV
2889
                    // eslint-disable-next-line unicorn/prefer-switch
×
2890
                } else if (key === "ArrowDown") {
31✔
2891
                    if (ctrlKey && altKey) {
8!
2892
                        return;
×
UNCOV
2893
                    }
×
2894
                    setOverlay(undefined);
8✔
2895
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
8!
2896
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
2✔
2897
                        adjustSelection([0, isPrimaryKey && !altKey ? 2 : 1]);
2✔
2898
                    } else {
8✔
2899
                        if (altKey && !isPrimaryKey) {
6!
2900
                            freeMove = true;
×
UNCOV
2901
                        }
×
2902
                        if (isPrimaryKey && !altKey) {
6✔
2903
                            row = rows - 1;
1✔
2904
                        } else {
6✔
2905
                            row += 1;
5✔
2906
                        }
5✔
2907
                    }
6✔
2908
                } else if (key === "ArrowUp" || key === "Home") {
31✔
2909
                    const asPrimary = key === "Home" || isPrimaryKey;
2✔
2910
                    setOverlay(undefined);
2✔
2911
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
2!
UNCOV
2912
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
×
2913
                        adjustSelection([0, asPrimary && !altKey ? -2 : -1]);
×
2914
                    } else {
2✔
2915
                        if (altKey && !asPrimary) {
2!
2916
                            freeMove = true;
×
UNCOV
2917
                        }
×
2918
                        row += asPrimary && !altKey ? Number.MIN_SAFE_INTEGER : -1;
2✔
2919
                    }
2✔
2920
                } else if (key === "ArrowRight" || key === "End") {
23✔
2921
                    const asPrimary = key === "End" || isPrimaryKey;
8✔
2922
                    setOverlay(undefined);
8✔
2923
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
8!
2924
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
5✔
2925
                        adjustSelection([asPrimary && !altKey ? 2 : 1, 0]);
5✔
2926
                    } else {
8✔
2927
                        if (altKey && !asPrimary) {
3!
2928
                            freeMove = true;
×
UNCOV
2929
                        }
×
2930
                        col += asPrimary && !altKey ? Number.MAX_SAFE_INTEGER : 1;
3✔
2931
                    }
3✔
2932
                } else if (key === "ArrowLeft") {
21✔
2933
                    setOverlay(undefined);
4✔
2934
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
4!
2935
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
1✔
2936
                        adjustSelection([isPrimaryKey && !altKey ? -2 : -1, 0]);
1!
2937
                    } else {
4✔
2938
                        if (altKey && !isPrimaryKey) {
3✔
2939
                            freeMove = true;
1✔
2940
                        }
1✔
2941
                        col += isPrimaryKey && !altKey ? Number.MIN_SAFE_INTEGER : -1;
3✔
2942
                    }
3✔
2943
                } else if (key === "Tab") {
13✔
2944
                    setOverlay(undefined);
2✔
2945
                    if (shiftKey) {
2✔
2946
                        col--;
1✔
2947
                    } else {
1✔
2948
                        col++;
1✔
2949
                    }
1✔
2950
                } else if (
2✔
2951
                    !metaKey &&
7✔
2952
                    !ctrlKey &&
7✔
2953
                    gridSelection.current !== undefined &&
7✔
2954
                    key.length === 1 &&
7✔
2955
                    /[ -~]/g.test(key) &&
7✔
2956
                    bounds !== undefined &&
7✔
2957
                    isReadWriteCell(getCellContent([col - rowMarkerOffset, Math.max(0, Math.min(row, rows - 1))]))
7✔
2958
                ) {
7✔
2959
                    if (
7✔
2960
                        (!lastRowSticky || row !== rows) &&
7✔
2961
                        (vr.y > row || row > vr.y + vr.height || vr.x > col || col > vr.x + vr.width)
7✔
2962
                    ) {
7!
2963
                        return;
×
UNCOV
2964
                    }
×
2965
                    reselect(bounds, true, key);
7✔
2966
                    cancel();
7✔
2967
                }
7✔
2968

45✔
2969
                const moved = updateSelectedCell(col, row, false, freeMove);
45✔
2970
                if (moved) {
61✔
2971
                    cancel();
18✔
2972
                }
18✔
2973
            };
61✔
2974
            void fn();
61✔
2975
        },
61✔
2976
        [
649✔
2977
            onKeyDownIn,
649✔
2978
            deleteRange,
649✔
2979
            overlay,
649✔
2980
            gridSelection,
649✔
2981
            keybindings.selectAll,
649✔
2982
            keybindings.search,
649✔
2983
            keybindings.selectColumn,
649✔
2984
            keybindings.selectRow,
649✔
2985
            keybindings.downFill,
649✔
2986
            keybindings.rightFill,
649✔
2987
            keybindings.pageDown,
649✔
2988
            keybindings.pageUp,
649✔
2989
            keybindings.first,
649✔
2990
            keybindings.last,
649✔
2991
            keybindings.clear,
649✔
2992
            columnSelect,
649✔
2993
            rowSelect,
649✔
2994
            getCellContent,
649✔
2995
            rowMarkerOffset,
649✔
2996
            updateSelectedCell,
649✔
2997
            setGridSelection,
649✔
2998
            onSelectionCleared,
649✔
2999
            columnsIn.length,
649✔
3000
            rows,
649✔
3001
            overlayID,
649✔
3002
            mangledOnCellsEdited,
649✔
3003
            onDelete,
649✔
3004
            mangledCols.length,
649✔
3005
            setSelectedColumns,
649✔
3006
            setSelectedRows,
649✔
3007
            showTrailingBlankRow,
649✔
3008
            getCustomNewRowTargetColumn,
649✔
3009
            appendRow,
649✔
3010
            onCellActivated,
649✔
3011
            reselect,
649✔
3012
            fillDown,
649✔
3013
            getMangledCellContent,
649✔
3014
            adjustSelection,
649✔
3015
            rangeSelect,
649✔
3016
            lastRowSticky,
649✔
3017
        ]
649✔
3018
    );
649✔
3019

649✔
3020
    const onContextMenu = React.useCallback(
649✔
3021
        (args: GridMouseEventArgs, preventDefault: () => void) => {
649✔
3022
            const adjustedCol = args.location[0] - rowMarkerOffset;
7✔
3023
            if (args.kind === "header") {
7!
3024
                onHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
UNCOV
3025
            }
×
3026

7✔
3027
            if (args.kind === groupHeaderKind) {
7!
UNCOV
3028
                if (adjustedCol < 0) {
×
3029
                    return;
×
UNCOV
3030
                }
×
3031
                onGroupHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
UNCOV
3032
            }
×
3033

7✔
3034
            if (args.kind === "cell") {
7✔
3035
                const [col, row] = args.location;
7✔
3036
                onCellContextMenu?.([adjustedCol, row], {
7✔
3037
                    ...args,
7✔
3038
                    preventDefault,
7✔
3039
                });
7✔
3040

7✔
3041
                if (!gridSelectionHasItem(gridSelection, args.location)) {
7✔
3042
                    updateSelectedCell(col, row, false, false);
3✔
3043
                }
3✔
3044
            }
7✔
3045
        },
7✔
3046
        [
649✔
3047
            gridSelection,
649✔
3048
            onCellContextMenu,
649✔
3049
            onGroupHeaderContextMenu,
649✔
3050
            onHeaderContextMenu,
649✔
3051
            rowMarkerOffset,
649✔
3052
            updateSelectedCell,
649✔
3053
        ]
649✔
3054
    );
649✔
3055

649✔
3056
    const onPasteInternal = React.useCallback(
649✔
3057
        async (e?: ClipboardEvent) => {
649✔
3058
            if (!keybindings.paste) return;
6!
3059
            function pasteToCell(
6✔
3060
                inner: InnerGridCell,
51✔
3061
                target: Item,
51✔
3062
                rawValue: string | boolean | string[] | number | boolean | BooleanEmpty | BooleanIndeterminate,
51✔
3063
                formatted?: string | string[]
51✔
3064
            ): EditListItem | undefined {
51✔
3065
                const stringifiedRawValue =
51✔
3066
                    typeof rawValue === "object" ? rawValue?.join("\n") ?? "" : rawValue?.toString() ?? "";
51!
3067

51✔
3068
                if (!isInnerOnlyCell(inner) && isReadWriteCell(inner) && inner.readonly !== true) {
51✔
3069
                    const coerced = coercePasteValue?.(stringifiedRawValue, inner);
51!
3070
                    if (coerced !== undefined && isEditableGridCell(coerced)) {
51!
UNCOV
3071
                        if (process.env.NODE_ENV !== "production" && coerced.kind !== inner.kind) {
×
UNCOV
3072
                            // eslint-disable-next-line no-console
×
3073
                            console.warn("Coercion should not change cell kind.");
×
UNCOV
3074
                        }
×
3075
                        return {
×
UNCOV
3076
                            location: target,
×
UNCOV
3077
                            value: coerced,
×
UNCOV
3078
                        };
×
UNCOV
3079
                    }
×
3080
                    const r = getCellRenderer(inner);
51✔
3081
                    if (r === undefined) return undefined;
51!
3082
                    if (r.kind === GridCellKind.Custom) {
51✔
3083
                        assert(inner.kind === GridCellKind.Custom);
1✔
3084
                        const newVal = (r as unknown as CustomRenderer<CustomCell<any>>).onPaste?.(
1✔
3085
                            stringifiedRawValue,
1✔
3086
                            inner.data
1✔
3087
                        );
1✔
3088
                        if (newVal === undefined) return undefined;
1!
3089
                        return {
×
UNCOV
3090
                            location: target,
×
UNCOV
3091
                            value: {
×
UNCOV
3092
                                ...inner,
×
UNCOV
3093
                                data: newVal,
×
UNCOV
3094
                            },
×
UNCOV
3095
                        };
×
3096
                    } else {
51✔
3097
                        const newVal = r.onPaste?.(stringifiedRawValue, inner, {
50✔
3098
                            formatted,
50✔
3099
                            formattedString: typeof formatted === "string" ? formatted : formatted?.join("\n"),
50!
3100
                            rawValue,
50✔
3101
                        });
50✔
3102
                        if (newVal === undefined) return undefined;
50✔
3103
                        assert(newVal.kind === inner.kind);
36✔
3104
                        return {
36✔
3105
                            location: target,
36✔
3106
                            value: newVal,
36✔
3107
                        };
36✔
3108
                    }
36✔
3109
                }
51!
3110
                return undefined;
×
3111
            }
51✔
3112

6✔
3113
            const selectedColumns = gridSelection.columns;
6✔
3114
            const selectedRows = gridSelection.rows;
6✔
3115
            const focused =
6✔
3116
                scrollRef.current?.contains(document.activeElement) === true ||
6✔
3117
                canvasRef.current?.contains(document.activeElement) === true;
6✔
3118

6✔
3119
            let target = gridSelection.current?.cell;
6✔
3120
            if (target === undefined && selectedColumns.length === 1) {
6!
3121
                target = [selectedColumns.first() ?? 0, 0];
×
UNCOV
3122
            }
×
3123
            if (target === undefined && selectedRows.length === 1) {
6!
3124
                target = [rowMarkerOffset, selectedRows.first() ?? 0];
×
UNCOV
3125
            }
×
3126

6✔
3127
            if (focused && target !== undefined) {
6✔
3128
                let data: CopyBuffer | undefined;
5✔
3129
                let text: string | undefined;
5✔
3130

5✔
3131
                const textPlain = "text/plain";
5✔
3132
                const textHtml = "text/html";
5✔
3133

5✔
3134
                if (navigator.clipboard.read !== undefined) {
5!
3135
                    const clipboardContent = await navigator.clipboard.read();
×
UNCOV
3136

×
UNCOV
3137
                    for (const item of clipboardContent) {
×
UNCOV
3138
                        if (item.types.includes(textHtml)) {
×
3139
                            const htmlBlob = await item.getType(textHtml);
×
3140
                            const html = await htmlBlob.text();
×
3141
                            const decoded = decodeHTML(html);
×
UNCOV
3142
                            if (decoded !== undefined) {
×
3143
                                data = decoded;
×
3144
                                break;
×
UNCOV
3145
                            }
×
UNCOV
3146
                        }
×
UNCOV
3147
                        if (item.types.includes(textPlain)) {
×
UNCOV
3148
                            // eslint-disable-next-line unicorn/no-await-expression-member
×
3149
                            text = await (await item.getType(textPlain)).text();
×
UNCOV
3150
                        }
×
UNCOV
3151
                    }
×
3152
                } else if (navigator.clipboard.readText !== undefined) {
5✔
3153
                    text = await navigator.clipboard.readText();
5✔
3154
                } else if (e !== undefined && e?.clipboardData !== null) {
5!
UNCOV
3155
                    if (e.clipboardData.types.includes(textHtml)) {
×
3156
                        const html = e.clipboardData.getData(textHtml);
×
3157
                        data = decodeHTML(html);
×
UNCOV
3158
                    }
×
UNCOV
3159
                    if (data === undefined && e.clipboardData.types.includes(textPlain)) {
×
3160
                        text = e.clipboardData.getData(textPlain);
×
UNCOV
3161
                    }
×
UNCOV
3162
                } else {
×
3163
                    return; // I didn't want to read that paste value anyway
×
UNCOV
3164
                }
×
3165

5✔
3166
                const [gridCol, gridRow] = target;
5✔
3167

5✔
3168
                const editList: EditListItem[] = [];
5✔
3169
                do {
5✔
3170
                    if (onPaste === undefined) {
5✔
3171
                        const cellData = getMangledCellContent(target);
2✔
3172
                        const rawValue = text ?? data?.map(r => r.map(cb => cb.rawValue).join("\t")).join("\t") ?? "";
2!
3173
                        const newVal = pasteToCell(cellData, target, rawValue, undefined);
2✔
3174
                        if (newVal !== undefined) {
2✔
3175
                            editList.push(newVal);
1✔
3176
                        }
1✔
3177
                        break;
2✔
3178
                    }
2✔
3179

3✔
3180
                    if (data === undefined) {
3✔
3181
                        if (text === undefined) return;
3!
3182
                        data = unquote(text);
3✔
3183
                    }
3✔
3184

3✔
3185
                    if (
3✔
3186
                        onPaste === false ||
3✔
3187
                        (typeof onPaste === "function" &&
3✔
3188
                            onPaste?.(
2✔
3189
                                [target[0] - rowMarkerOffset, target[1]],
2✔
3190
                                data.map(r => r.map(cb => cb.rawValue?.toString() ?? ""))
2!
3191
                            ) !== true)
2✔
3192
                    ) {
5!
3193
                        return;
×
UNCOV
3194
                    }
✔
3195

3✔
3196
                    for (const [row, dataRow] of data.entries()) {
5✔
3197
                        if (row + gridRow >= rows) break;
21!
3198
                        for (const [col, dataItem] of dataRow.entries()) {
21✔
3199
                            const index = [col + gridCol, row + gridRow] as const;
63✔
3200
                            const [writeCol, writeRow] = index;
63✔
3201
                            if (writeCol >= mangledCols.length) continue;
63✔
3202
                            if (writeRow >= mangledRows) continue;
49!
3203
                            const cellData = getMangledCellContent(index);
49✔
3204
                            const newVal = pasteToCell(cellData, index, dataItem.rawValue, dataItem.formatted);
49✔
3205
                            if (newVal !== undefined) {
63✔
3206
                                editList.push(newVal);
35✔
3207
                            }
35✔
3208
                        }
63✔
3209
                    }
21✔
3210
                    // eslint-disable-next-line no-constant-condition
3✔
3211
                } while (false);
5✔
3212

5✔
3213
                mangledOnCellsEdited(editList);
5✔
3214

5✔
3215
                gridRef.current?.damage(
5✔
3216
                    editList.map(c => ({
5✔
3217
                        cell: c.location,
36✔
3218
                    }))
5✔
3219
                );
5✔
3220
            }
5✔
3221
        },
6✔
3222
        [
649✔
3223
            coercePasteValue,
649✔
3224
            getCellRenderer,
649✔
3225
            getMangledCellContent,
649✔
3226
            gridSelection,
649✔
3227
            keybindings.paste,
649✔
3228
            mangledCols.length,
649✔
3229
            mangledOnCellsEdited,
649✔
3230
            mangledRows,
649✔
3231
            onPaste,
649✔
3232
            rowMarkerOffset,
649✔
3233
            rows,
649✔
3234
        ]
649✔
3235
    );
649✔
3236

649✔
3237
    useEventListener("paste", onPasteInternal, window, false, true);
649✔
3238

649✔
3239
    // While this function is async, we deeply prefer not to await if we don't have to. This will lead to unpacking
649✔
3240
    // promises in rather awkward ways when possible to avoid awaiting. We have to use fallback copy mechanisms when
649✔
3241
    // an await has happened.
649✔
3242
    const onCopy = React.useCallback(
649✔
3243
        async (e?: ClipboardEvent, ignoreFocus?: boolean) => {
649✔
3244
            if (!keybindings.copy) return;
6!
3245
            const focused =
6✔
3246
                ignoreFocus === true ||
6✔
3247
                scrollRef.current?.contains(document.activeElement) === true ||
5✔
3248
                canvasRef.current?.contains(document.activeElement) === true;
5✔
3249

6✔
3250
            const selectedColumns = gridSelection.columns;
6✔
3251
            const selectedRows = gridSelection.rows;
6✔
3252

6✔
3253
            const copyToClipboardWithHeaders = (
6✔
3254
                cells: readonly (readonly GridCell[])[],
5✔
3255
                columnIndexes: readonly number[]
5✔
3256
            ) => {
5✔
3257
                if (!copyHeaders) {
5✔
3258
                    copyToClipboard(cells, columnIndexes, e);
5✔
3259
                } else {
5!
3260
                    const headers = columnIndexes.map(index => ({
×
UNCOV
3261
                        kind: GridCellKind.Text,
×
UNCOV
3262
                        data: columnsIn[index].title,
×
UNCOV
3263
                        displayData: columnsIn[index].title,
×
UNCOV
3264
                        allowOverlay: false,
×
UNCOV
3265
                    })) as GridCell[];
×
3266
                    copyToClipboard([headers, ...cells], columnIndexes, e);
×
UNCOV
3267
                }
×
3268
            };
5✔
3269

6✔
3270
            if (focused && getCellsForSelection !== undefined) {
6✔
3271
                if (gridSelection.current !== undefined) {
6✔
3272
                    let thunk = getCellsForSelection(gridSelection.current.range, abortControllerRef.current.signal);
3✔
3273
                    if (typeof thunk !== "object") {
3!
3274
                        thunk = await thunk();
×
UNCOV
3275
                    }
×
3276
                    copyToClipboardWithHeaders(
3✔
3277
                        thunk,
3✔
3278
                        range(
3✔
3279
                            gridSelection.current.range.x - rowMarkerOffset,
3✔
3280
                            gridSelection.current.range.x + gridSelection.current.range.width - rowMarkerOffset
3✔
3281
                        )
3✔
3282
                    );
3✔
3283
                } else if (selectedRows !== undefined && selectedRows.length > 0) {
3✔
3284
                    const toCopy = [...selectedRows];
1✔
3285
                    const cells = toCopy.map(rowIndex => {
1✔
3286
                        const thunk = getCellsForSelection(
1✔
3287
                            {
1✔
3288
                                x: rowMarkerOffset,
1✔
3289
                                y: rowIndex,
1✔
3290
                                width: columnsIn.length,
1✔
3291
                                height: 1,
1✔
3292
                            },
1✔
3293
                            abortControllerRef.current.signal
1✔
3294
                        );
1✔
3295
                        if (typeof thunk === "object") {
1✔
3296
                            return thunk[0];
1✔
3297
                        }
1!
3298
                        return thunk().then(v => v[0]);
×
3299
                    });
1✔
3300
                    if (cells.some(x => x instanceof Promise)) {
1!
3301
                        const settled = await Promise.all(cells);
×
3302
                        copyToClipboardWithHeaders(settled, range(columnsIn.length));
×
3303
                    } else {
1✔
3304
                        copyToClipboardWithHeaders(cells as (readonly GridCell[])[], range(columnsIn.length));
1✔
3305
                    }
1✔
3306
                } else if (selectedColumns.length > 0) {
3✔
3307
                    const results: (readonly (readonly GridCell[])[])[] = [];
1✔
3308
                    const cols: number[] = [];
1✔
3309
                    for (const col of selectedColumns) {
1✔
3310
                        let thunk = getCellsForSelection(
3✔
3311
                            {
3✔
3312
                                x: col,
3✔
3313
                                y: 0,
3✔
3314
                                width: 1,
3✔
3315
                                height: rows,
3✔
3316
                            },
3✔
3317
                            abortControllerRef.current.signal
3✔
3318
                        );
3✔
3319
                        if (typeof thunk !== "object") {
3!
3320
                            thunk = await thunk();
×
UNCOV
3321
                        }
×
3322
                        results.push(thunk);
3✔
3323
                        cols.push(col - rowMarkerOffset);
3✔
3324
                    }
3✔
3325
                    if (results.length === 1) {
1!
3326
                        copyToClipboardWithHeaders(results[0], cols);
×
3327
                    } else {
1✔
3328
                        // FIXME: this is dumb
1✔
3329
                        const toCopy = results.reduce((pv, cv) => pv.map((row, index) => [...row, ...cv[index]]));
1✔
3330
                        copyToClipboardWithHeaders(toCopy, cols);
1✔
3331
                    }
1✔
3332
                }
1✔
3333
            }
6✔
3334
        },
6✔
3335
        [columnsIn, getCellsForSelection, gridSelection, keybindings.copy, rowMarkerOffset, rows, copyHeaders]
649✔
3336
    );
649✔
3337

649✔
3338
    useEventListener("copy", onCopy, window, false, false);
649✔
3339

649✔
3340
    const onCut = React.useCallback(
649✔
3341
        async (e?: ClipboardEvent) => {
649✔
3342
            if (!keybindings.cut) return;
1!
3343
            const focused =
1✔
3344
                scrollRef.current?.contains(document.activeElement) === true ||
1✔
3345
                canvasRef.current?.contains(document.activeElement) === true;
1✔
3346

1✔
3347
            if (!focused) return;
1!
3348
            await onCopy(e);
1✔
3349
            if (gridSelection.current !== undefined) {
1✔
3350
                deleteRange(gridSelection.current.range);
1✔
3351
            }
1✔
3352
        },
1✔
3353
        [deleteRange, gridSelection, keybindings.cut, onCopy]
649✔
3354
    );
649✔
3355

649✔
3356
    useEventListener("cut", onCut, window, false, false);
649✔
3357

649✔
3358
    const onSearchResultsChanged = React.useCallback(
649✔
3359
        (results: readonly Item[], navIndex: number) => {
649✔
3360
            if (onSearchResultsChangedIn !== undefined) {
7!
UNCOV
3361
                if (rowMarkerOffset !== 0) {
×
3362
                    results = results.map(item => [item[0] - rowMarkerOffset, item[1]]);
×
UNCOV
3363
                }
×
3364
                onSearchResultsChangedIn(results, navIndex);
×
3365
                return;
×
UNCOV
3366
            }
×
3367
            if (results.length === 0 || navIndex === -1) return;
7✔
3368

2✔
3369
            const [col, row] = results[navIndex];
2✔
3370
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
7!
3371
                return;
×
UNCOV
3372
            }
✔
3373
            lastSent.current = [col, row];
2✔
3374
            updateSelectedCell(col, row, false, false);
2✔
3375
        },
7✔
3376
        [onSearchResultsChangedIn, rowMarkerOffset, updateSelectedCell]
649✔
3377
    );
649✔
3378

649✔
3379
    // this effects purpose in life is to scroll the newly selected cell into view when and ONLY when that cell
649✔
3380
    // is from an external gridSelection change. Also note we want the unmangled out selection because scrollTo
649✔
3381
    // expects unmangled indexes
649✔
3382
    const [outCol, outRow] = gridSelectionOuter?.current?.cell ?? [];
649✔
3383
    const scrollToRef = React.useRef(scrollTo);
649✔
3384
    scrollToRef.current = scrollTo;
649✔
3385
    React.useLayoutEffect(() => {
649✔
3386
        if (
205✔
3387
            !hasJustScrolled.current &&
205✔
3388
            outCol !== undefined &&
205✔
3389
            outRow !== undefined &&
76✔
3390
            (outCol !== expectedExternalGridSelection.current?.current?.cell[0] ||
76✔
3391
                outRow !== expectedExternalGridSelection.current?.current?.cell[1])
76✔
3392
        ) {
205!
3393
            scrollToRef.current(outCol, outRow);
×
UNCOV
3394
        }
×
3395
        hasJustScrolled.current = false; //only allow skipping a single scroll
205✔
3396
    }, [outCol, outRow]);
649✔
3397

649✔
3398
    const selectionOutOfBounds =
649✔
3399
        gridSelection.current !== undefined &&
649✔
3400
        (gridSelection.current.cell[0] >= mangledCols.length || gridSelection.current.cell[1] >= mangledRows);
301✔
3401
    React.useLayoutEffect(() => {
649✔
3402
        if (selectionOutOfBounds) {
135✔
3403
            setGridSelection(emptyGridSelection, false);
1✔
3404
        }
1✔
3405
    }, [selectionOutOfBounds, setGridSelection]);
649✔
3406

649✔
3407
    const disabledRows = React.useMemo(() => {
649✔
3408
        if (showTrailingBlankRow === true && trailingRowOptions?.tint === true) {
134✔
3409
            return CompactSelection.fromSingleSelection(mangledRows - 1);
131✔
3410
        }
131✔
3411
        return CompactSelection.empty();
3✔
3412
    }, [mangledRows, showTrailingBlankRow, trailingRowOptions?.tint]);
649✔
3413

649✔
3414
    const mangledVerticalBorder = React.useCallback(
649✔
3415
        (col: number) => {
649✔
3416
            return typeof verticalBorder === "boolean"
7,135!
UNCOV
3417
                ? verticalBorder
×
3418
                : verticalBorder?.(col - rowMarkerOffset) ?? true;
7,135!
3419
        },
7,135✔
3420
        [rowMarkerOffset, verticalBorder]
649✔
3421
    );
649✔
3422

649✔
3423
    const renameGroupNode = React.useMemo(() => {
649✔
3424
        if (renameGroup === undefined || canvasRef.current === null) return null;
135✔
3425
        const { bounds, group } = renameGroup;
2✔
3426
        const canvasBounds = canvasRef.current.getBoundingClientRect();
2✔
3427
        return (
2✔
3428
            <GroupRename
2✔
3429
                bounds={bounds}
2✔
3430
                group={group}
2✔
3431
                canvasBounds={canvasBounds}
2✔
3432
                onClose={() => setRenameGroup(undefined)}
2✔
3433
                onFinish={newVal => {
2✔
3434
                    setRenameGroup(undefined);
1✔
3435
                    onGroupHeaderRenamed?.(group, newVal);
1✔
3436
                }}
1✔
3437
            />
2✔
3438
        );
135✔
3439
    }, [onGroupHeaderRenamed, renameGroup]);
649✔
3440

649✔
3441
    const mangledFreezeColumns = Math.min(mangledCols.length, freezeColumns + (hasRowMarkers ? 1 : 0));
649✔
3442

649✔
3443
    React.useImperativeHandle(
649✔
3444
        forwardedRef,
649✔
3445
        () => ({
649✔
3446
            appendRow: (col: number, openOverlay?: boolean) => appendRow(col + rowMarkerOffset, openOverlay),
26✔
3447
            updateCells: damageList => {
26✔
3448
                if (rowMarkerOffset !== 0) {
2✔
3449
                    damageList = damageList.map(x => ({ cell: [x.cell[0] + rowMarkerOffset, x.cell[1]] }));
1✔
3450
                }
1✔
3451
                return gridRef.current?.damage(damageList);
2✔
3452
            },
2✔
3453
            getBounds: (col, row) => {
26✔
UNCOV
3454
                if (canvasRef?.current === null || scrollRef?.current === null) {
×
NEW
3455
                    return undefined;
×
UNCOV
3456
                }
×
UNCOV
3457

×
UNCOV
3458
                if (col === undefined && row === undefined) {
×
UNCOV
3459
                    // Return the bounds of the entire scroll area:
×
NEW
3460
                    const rect = canvasRef.current.getBoundingClientRect();
×
NEW
3461
                    const scale = rect.width / scrollRef.current.clientWidth;
×
NEW
3462
                    return {
×
NEW
3463
                        x: rect.x - scrollRef.current.scrollLeft * scale,
×
NEW
3464
                        y: rect.y - scrollRef.current.scrollTop * scale,
×
NEW
3465
                        width: scrollRef.current.scrollWidth * scale,
×
NEW
3466
                        height: scrollRef.current.scrollHeight * scale,
×
NEW
3467
                    };
×
3468
                }
×
NEW
3469
                return gridRef.current?.getBounds(col ?? 0 + rowMarkerOffset, row);
×
UNCOV
3470
            },
×
3471
            focus: () => gridRef.current?.focus(),
26✔
3472
            emit: async e => {
26✔
3473
                switch (e) {
5✔
3474
                    case "delete":
5✔
3475
                        onKeyDown({
1✔
3476
                            bounds: undefined,
1✔
3477
                            cancel: () => undefined,
1✔
3478
                            stopPropagation: () => undefined,
1✔
3479
                            preventDefault: () => undefined,
1✔
3480
                            ctrlKey: false,
1✔
3481
                            key: "Delete",
1✔
3482
                            keyCode: 46,
1✔
3483
                            metaKey: false,
1✔
3484
                            shiftKey: false,
1✔
3485
                            altKey: false,
1✔
3486
                            rawEvent: undefined,
1✔
3487
                            location: undefined,
1✔
3488
                        });
1✔
3489
                        break;
1✔
3490
                    case "fill-right":
5✔
3491
                        onKeyDown({
1✔
3492
                            bounds: undefined,
1✔
3493
                            cancel: () => undefined,
1✔
3494
                            stopPropagation: () => undefined,
1✔
3495
                            preventDefault: () => undefined,
1✔
3496
                            ctrlKey: true,
1✔
3497
                            key: "r",
1✔
3498
                            keyCode: 82,
1✔
3499
                            metaKey: false,
1✔
3500
                            shiftKey: false,
1✔
3501
                            altKey: false,
1✔
3502
                            rawEvent: undefined,
1✔
3503
                            location: undefined,
1✔
3504
                        });
1✔
3505
                        break;
1✔
3506
                    case "fill-down":
5✔
3507
                        onKeyDown({
1✔
3508
                            bounds: undefined,
1✔
3509
                            cancel: () => undefined,
1✔
3510
                            stopPropagation: () => undefined,
1✔
3511
                            preventDefault: () => undefined,
1✔
3512
                            ctrlKey: true,
1✔
3513
                            key: "d",
1✔
3514
                            keyCode: 68,
1✔
3515
                            metaKey: false,
1✔
3516
                            shiftKey: false,
1✔
3517
                            altKey: false,
1✔
3518
                            rawEvent: undefined,
1✔
3519
                            location: undefined,
1✔
3520
                        });
1✔
3521
                        break;
1✔
3522
                    case "copy":
5✔
3523
                        await onCopy(undefined, true);
1✔
3524
                        break;
1✔
3525
                    case "paste":
5✔
3526
                        await onPasteInternal();
1✔
3527
                        break;
1✔
3528
                }
5✔
3529
            },
5✔
3530
            scrollTo,
26✔
3531
            remeasureColumns: cols => {
26✔
3532
                for (const col of cols) {
1✔
3533
                    void normalSizeColumn(col + rowMarkerOffset, true);
1✔
3534
                }
1✔
3535
            },
1✔
3536
        }),
26✔
3537
        [appendRow, normalSizeColumn, onCopy, onKeyDown, onPasteInternal, rowMarkerOffset, scrollTo]
649✔
3538
    );
649✔
3539

649✔
3540
    const [selCol, selRow] = currentCell ?? [];
649✔
3541
    const onCellFocused = React.useCallback(
649✔
3542
        (cell: Item) => {
649✔
3543
            const [col, row] = cell;
24✔
3544

24✔
3545
            if (row === -1) {
24!
UNCOV
3546
                if (columnSelect !== "none") {
×
3547
                    setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, false);
×
3548
                    focus();
×
UNCOV
3549
                }
×
3550
                return;
×
UNCOV
3551
            }
×
3552

24✔
3553
            if (selCol === col && selRow === row) return;
24✔
3554
            setCurrent(
1✔
3555
                {
1✔
3556
                    cell,
1✔
3557
                    range: { x: col, y: row, width: 1, height: 1 },
1✔
3558
                },
1✔
3559
                true,
1✔
3560
                false,
1✔
3561
                "keyboard-nav"
1✔
3562
            );
1✔
3563
            scrollTo(col, row);
1✔
3564
        },
24✔
3565
        [columnSelect, focus, scrollTo, selCol, selRow, setCurrent, setSelectedColumns]
649✔
3566
    );
649✔
3567

649✔
3568
    const [isFocused, setIsFocused] = React.useState(false);
649✔
3569
    const setIsFocusedDebounced = React.useRef(
649✔
3570
        debounce((val: boolean) => {
649✔
3571
            setIsFocused(val);
46✔
3572
        }, 5)
649✔
3573
    );
649✔
3574

649✔
3575
    const onCanvasFocused = React.useCallback(() => {
649✔
3576
        setIsFocusedDebounced.current(true);
57✔
3577

57✔
3578
        // check for mouse state, don't do anything if the user is clicked to focus.
57✔
3579
        if (
57✔
3580
            gridSelection.current === undefined &&
57✔
3581
            gridSelection.columns.length === 0 &&
6✔
3582
            gridSelection.rows.length === 0 &&
5✔
3583
            mouseState === undefined
5✔
3584
        ) {
57✔
3585
            setCurrent(
5✔
3586
                {
5✔
3587
                    cell: [rowMarkerOffset, cellYOffset],
5✔
3588
                    range: {
5✔
3589
                        x: rowMarkerOffset,
5✔
3590
                        y: cellYOffset,
5✔
3591
                        width: 1,
5✔
3592
                        height: 1,
5✔
3593
                    },
5✔
3594
                },
5✔
3595
                true,
5✔
3596
                false,
5✔
3597
                "keyboard-select"
5✔
3598
            );
5✔
3599
        }
5✔
3600
    }, [cellYOffset, gridSelection, mouseState, rowMarkerOffset, setCurrent]);
649✔
3601

649✔
3602
    const onFocusOut = React.useCallback(() => {
649✔
3603
        setIsFocusedDebounced.current(false);
27✔
3604
    }, []);
649✔
3605

649✔
3606
    const [idealWidth, idealHeight] = React.useMemo(() => {
649✔
3607
        let h: number;
147✔
3608
        const scrollbarWidth = experimental?.scrollbarWidthOverride ?? getScrollBarWidth();
147✔
3609
        const rowsCountWithTrailingRow = rows + (showTrailingBlankRow ? 1 : 0);
147!
3610
        if (typeof rowHeight === "number") {
147✔
3611
            h = totalHeaderHeight + rowsCountWithTrailingRow * rowHeight;
146✔
3612
        } else {
147✔
3613
            let avg = 0;
1✔
3614
            const toAverage = Math.min(rowsCountWithTrailingRow, 10);
1✔
3615
            for (let i = 0; i < toAverage; i++) {
1✔
3616
                avg += rowHeight(i);
10✔
3617
            }
10✔
3618
            avg = Math.floor(avg / toAverage);
1✔
3619

1✔
3620
            h = totalHeaderHeight + rowsCountWithTrailingRow * avg;
1✔
3621
        }
1✔
3622
        h += scrollbarWidth;
147✔
3623

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

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

649✔
3631
    return (
649✔
3632
        <ThemeContext.Provider value={mergedTheme}>
649✔
3633
            <DataEditorContainer
649✔
3634
                style={makeCSSStyle(mergedTheme)}
649✔
3635
                className={className}
649✔
3636
                inWidth={width ?? idealWidth}
649✔
3637
                inHeight={height ?? idealHeight}>
649✔
3638
                <DataGridSearch
649✔
3639
                    fillHandle={fillHandle}
649✔
3640
                    drawFocusRing={drawFocusRing}
649✔
3641
                    experimental={experimental}
649✔
3642
                    fixedShadowX={fixedShadowX}
649✔
3643
                    fixedShadowY={fixedShadowY}
649✔
3644
                    getRowThemeOverride={getRowThemeOverride}
649✔
3645
                    headerIcons={headerIcons}
649✔
3646
                    imageWindowLoader={imageWindowLoader}
649✔
3647
                    initialSize={initialSize}
649✔
3648
                    isDraggable={isDraggable}
649✔
3649
                    onDragLeave={onDragLeave}
649✔
3650
                    onRowMoved={onRowMoved}
649✔
3651
                    overscrollX={overscrollX}
649✔
3652
                    overscrollY={overscrollY}
649✔
3653
                    preventDiagonalScrolling={preventDiagonalScrolling}
649✔
3654
                    rightElement={rightElement}
649✔
3655
                    rightElementProps={rightElementProps}
649✔
3656
                    showMinimap={showMinimap}
649✔
3657
                    smoothScrollX={smoothScrollX}
649✔
3658
                    smoothScrollY={smoothScrollY}
649✔
3659
                    className={className}
649✔
3660
                    enableGroups={enableGroups}
649✔
3661
                    onCanvasFocused={onCanvasFocused}
649✔
3662
                    onCanvasBlur={onFocusOut}
649✔
3663
                    canvasRef={canvasRef}
649✔
3664
                    onContextMenu={onContextMenu}
649✔
3665
                    theme={mergedTheme}
649✔
3666
                    cellXOffset={cellXOffset}
649✔
3667
                    cellYOffset={cellYOffset}
649✔
3668
                    accessibilityHeight={visibleRegion.height}
649✔
3669
                    onDragEnd={onDragEnd}
649✔
3670
                    columns={mangledCols}
649✔
3671
                    drawCustomCell={drawCell}
649✔
3672
                    drawHeader={drawHeader}
649✔
3673
                    disabledRows={disabledRows}
649✔
3674
                    freezeColumns={mangledFreezeColumns}
649✔
3675
                    lockColumns={rowMarkerOffset}
649✔
3676
                    firstColAccessible={rowMarkerOffset === 0}
649✔
3677
                    getCellContent={getMangledCellContent}
649✔
3678
                    minColumnWidth={minColumnWidth}
649✔
3679
                    maxColumnWidth={maxColumnWidth}
649✔
3680
                    searchInputRef={searchInputRef}
649✔
3681
                    showSearch={showSearch}
649✔
3682
                    onSearchClose={onSearchClose}
649✔
3683
                    highlightRegions={highlightRegions}
649✔
3684
                    getCellsForSelection={getCellsForSelection}
649✔
3685
                    getGroupDetails={mangledGetGroupDetails}
649✔
3686
                    headerHeight={headerHeight}
649✔
3687
                    isFocused={isFocused}
649✔
3688
                    groupHeaderHeight={enableGroups ? groupHeaderHeight : 0}
649✔
3689
                    trailingRowType={
649✔
3690
                        !showTrailingBlankRow ? "none" : trailingRowOptions?.sticky === true ? "sticky" : "appended"
649!
3691
                    }
649✔
3692
                    onColumnResize={onColumnResize}
649✔
3693
                    onColumnResizeEnd={onColumnResizeEnd}
649✔
3694
                    onColumnResizeStart={onColumnResizeStart}
649✔
3695
                    onCellFocused={onCellFocused}
649✔
3696
                    onColumnMoved={onColumnMovedImpl}
649✔
3697
                    onDragStart={onDragStartImpl}
649✔
3698
                    onHeaderMenuClick={onHeaderMenuClickInner}
649✔
3699
                    onItemHovered={onItemHoveredImpl}
649✔
3700
                    isFilling={mouseState?.fillHandle === true}
649✔
3701
                    onMouseMove={onMouseMoveImpl}
649✔
3702
                    onKeyDown={onKeyDown}
649✔
3703
                    onKeyUp={onKeyUpIn}
649✔
3704
                    onMouseDown={onMouseDown}
649✔
3705
                    onMouseUp={onMouseUp}
649✔
3706
                    onDragOverCell={onDragOverCell}
649✔
3707
                    onDrop={onDrop}
649✔
3708
                    onSearchResultsChanged={onSearchResultsChanged}
649✔
3709
                    onVisibleRegionChanged={onVisibleRegionChangedImpl}
649✔
3710
                    clientSize={[clientSize[0], clientSize[1]]}
649✔
3711
                    rowHeight={rowHeight}
649✔
3712
                    searchResults={searchResults}
649✔
3713
                    searchValue={searchValue}
649✔
3714
                    onSearchValueChange={onSearchValueChange}
649✔
3715
                    rows={mangledRows}
649✔
3716
                    scrollRef={scrollRef}
649✔
3717
                    selection={gridSelection}
649✔
3718
                    translateX={visibleRegion.tx}
649✔
3719
                    translateY={visibleRegion.ty}
649✔
3720
                    verticalBorder={mangledVerticalBorder}
649✔
3721
                    gridRef={gridRef}
649✔
3722
                    getCellRenderer={getCellRenderer}
649✔
3723
                    scrollToEnd={scrollToEnd}
649✔
3724
                />
649✔
3725
                {renameGroupNode}
649✔
3726
                {overlay !== undefined && (
649✔
3727
                    <DataGridOverlayEditor
24✔
3728
                        {...overlay}
24✔
3729
                        validateCell={validateCell}
24✔
3730
                        id={overlayID}
24✔
3731
                        getCellRenderer={getCellRenderer}
24✔
3732
                        className={experimental?.isSubGrid === true ? "click-outside-ignore" : undefined}
24!
3733
                        provideEditor={provideEditor}
24✔
3734
                        imageEditorOverride={imageEditorOverride}
24✔
3735
                        onFinishEditing={onFinishEditing}
24✔
3736
                        markdownDivCreateNode={markdownDivCreateNode}
24✔
3737
                        isOutsideClick={isOutsideClick}
24✔
3738
                    />
24✔
3739
                )}
649✔
3740
            </DataEditorContainer>
649✔
3741
        </ThemeContext.Provider>
649✔
3742
    );
649✔
3743
};
649✔
3744

1✔
3745
/**
1✔
3746
 * The primary component of Glide Data Grid.
1✔
3747
 * @category DataEditor
1✔
3748
 * @param {DataEditorProps} props
1✔
3749
 */
1✔
3750
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