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

glideapps / glide-data-grid / 7310552296

23 Dec 2023 09:20PM UTC coverage: 90.561% (+4.1%) from 86.42%
7310552296

Pull #810

github

jassmith
Fix more tests
Pull Request #810: 6.0.0

2583 of 3235 branches covered (0.0%)

3296 of 3764 new or added lines in 62 files covered. (87.57%)

265 existing lines in 12 files now uncovered.

15715 of 17353 relevant lines covered (90.56%)

2976.27 hits per line

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

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

1✔
85
const DataGridOverlayEditor = React.lazy(
1✔
86
    async () => await import("../internal/data-grid-overlay-editor/data-grid-overlay-editor.js")
1✔
87
);
1✔
88

1✔
89
let idCounter = 0;
1✔
90

1✔
91
interface MouseState {
1✔
92
    readonly previousSelection?: GridSelection;
1✔
93
    readonly fillHandle?: boolean;
1✔
94
}
1✔
95

1✔
96
type Props = Partial<
1✔
97
    Omit<
1✔
98
        DataGridSearchProps,
1✔
99
        | "accessibilityHeight"
1✔
100
        | "canvasRef"
1✔
101
        | "cellXOffset"
1✔
102
        | "cellYOffset"
1✔
103
        | "className"
1✔
104
        | "clientSize"
1✔
105
        | "columns"
1✔
106
        | "disabledRows"
1✔
107
        | "enableGroups"
1✔
108
        | "firstColAccessible"
1✔
109
        | "firstColSticky"
1✔
110
        | "freezeColumns"
1✔
111
        | "getCellContent"
1✔
112
        | "getCellRenderer"
1✔
113
        | "getCellsForSelection"
1✔
114
        | "gridRef"
1✔
115
        | "groupHeaderHeight"
1✔
116
        | "headerHeight"
1✔
117
        | "isFilling"
1✔
118
        | "isFocused"
1✔
119
        | "imageWindowLoader"
1✔
120
        | "lockColumns"
1✔
121
        | "maxColumnWidth"
1✔
122
        | "minColumnWidth"
1✔
123
        | "nonGrowWidth"
1✔
124
        | "onCanvasBlur"
1✔
125
        | "onCanvasFocused"
1✔
126
        | "onCellFocused"
1✔
127
        | "onContextMenu"
1✔
128
        | "onDragEnd"
1✔
129
        | "onMouseDown"
1✔
130
        | "onMouseMove"
1✔
131
        | "onMouseUp"
1✔
132
        | "onVisibleRegionChanged"
1✔
133
        | "rowHeight"
1✔
134
        | "rows"
1✔
135
        | "scrollRef"
1✔
136
        | "searchInputRef"
1✔
137
        | "selectedColumns"
1✔
138
        | "selection"
1✔
139
        | "theme"
1✔
140
        | "trailingRowType"
1✔
141
        | "translateX"
1✔
142
        | "translateY"
1✔
143
        | "verticalBorder"
1✔
144
    >
1✔
145
>;
1✔
146

1✔
147
type EmitEvents = "copy" | "paste" | "delete" | "fill-right" | "fill-down";
1✔
148

1✔
149
function getSpanStops(cells: readonly (readonly GridCell[])[]): number[] {
5✔
150
    return uniq(
5✔
151
        flatten(
5✔
152
            flatten(cells)
5✔
153
                .filter(c => c.span !== undefined)
5✔
154
                .map(c => range((c.span?.[0] ?? 0) + 1, (c.span?.[1] ?? 0) + 1))
5✔
155
        )
5✔
156
    );
5✔
157
}
5✔
158

1✔
159
function shiftSelection(input: GridSelection, offset: number): GridSelection {
283✔
160
    if (input === undefined || offset === 0 || (input.columns.length === 0 && input.current === undefined))
283✔
161
        return input;
283✔
162

35✔
163
    return {
35✔
164
        current:
35✔
165
            input.current === undefined
35✔
166
                ? undefined
1✔
167
                : {
34✔
168
                      cell: [input.current.cell[0] + offset, input.current.cell[1]],
34✔
169
                      range: {
34✔
170
                          ...input.current.range,
34✔
171
                          x: input.current.range.x + offset,
34✔
172
                      },
34✔
173
                      rangeStack: input.current.rangeStack.map(r => ({
34✔
UNCOV
174
                          ...r,
×
UNCOV
175
                          x: r.x + offset,
×
176
                      })),
34✔
177
                  },
34✔
178
        rows: input.rows,
283✔
179
        columns: input.columns.offset(offset),
283✔
180
    };
283✔
181
}
283✔
182

1✔
183
export interface Keybinds {
1✔
184
    readonly selectAll: boolean;
1✔
185
    readonly selectRow: boolean;
1✔
186
    readonly selectColumn: boolean;
1✔
187
    readonly downFill: boolean;
1✔
188
    readonly rightFill: boolean;
1✔
189
    readonly pageUp: boolean;
1✔
190
    readonly pageDown: boolean;
1✔
191
    readonly clear: boolean;
1✔
192
    readonly copy: boolean;
1✔
193
    readonly paste: boolean;
1✔
194
    readonly cut: boolean;
1✔
195
    readonly search: boolean;
1✔
196
    readonly first: boolean;
1✔
197
    readonly last: boolean;
1✔
198
}
1✔
199

1✔
200
const keybindingDefaults: Keybinds = {
1✔
201
    selectAll: true,
1✔
202
    selectRow: true,
1✔
203
    selectColumn: true,
1✔
204
    downFill: false,
1✔
205
    rightFill: false,
1✔
206
    pageUp: true,
1✔
207
    pageDown: true,
1✔
208
    clear: true,
1✔
209
    copy: true,
1✔
210
    paste: true,
1✔
211
    cut: true,
1✔
212
    search: false,
1✔
213
    first: true,
1✔
214
    last: true,
1✔
215
};
1✔
216

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

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

1✔
294
    /** The columns to display in the data grid.
1✔
295
     * @group Data
1✔
296
     */
1✔
297
    readonly columns: readonly GridColumn[];
1✔
298

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

1✔
325
    /**
1✔
326
     * The number of rows in the grid.
1✔
327
     * @group Data
1✔
328
     */
1✔
329
    readonly rows: number;
1✔
330

1✔
331
    /** Determines if row markers should be automatically added to the grid.
1✔
332
     * Interactive row markers allow the user to select a row.
1✔
333
     *
1✔
334
     * - "clickable-number" renders a number that can be clicked to
1✔
335
     *   select the row
1✔
336
     * - "both" causes the row marker to show up as a number but
1✔
337
     *   reveal a checkbox when the marker is hovered.
1✔
338
     *
1✔
339
     * @defaultValue `none`
1✔
340
     * @group Style
1✔
341
     */
1✔
342
    readonly rowMarkers?: "checkbox" | "number" | "clickable-number" | "checkbox-visible" | "both" | "none";
1✔
343
    /**
1✔
344
     * Sets the width of row markers in pixels, if unset row markers will automatically size.
1✔
345
     * @group Style
1✔
346
     */
1✔
347
    readonly rowMarkerWidth?: number;
1✔
348
    /** Changes the starting index for row markers.
1✔
349
     * @defaultValue 1
1✔
350
     * @group Style
1✔
351
     */
1✔
352
    readonly rowMarkerStartIndex?: number;
1✔
353

1✔
354
    /** Changes the theme of the row marker column
1✔
355
     * @group Style
1✔
356
     */
1✔
357
    readonly rowMarkerTheme?: Partial<Theme>;
1✔
358

1✔
359
    /** Sets the width of the data grid.
1✔
360
     * @group Style
1✔
361
     */
1✔
362
    readonly width?: number | string;
1✔
363
    /** Sets the height of the data grid.
1✔
364
     * @group Style
1✔
365
     */
1✔
366
    readonly height?: number | string;
1✔
367
    /** Custom classname for data grid wrapper.
1✔
368
     * @group Style
1✔
369
     */
1✔
370
    readonly className?: string;
1✔
371

1✔
372
    /** If set to `default`, `gridSelection` will be coerced to always include full spans.
1✔
373
     * @group Selection
1✔
374
     * @defaultValue `default`
1✔
375
     */
1✔
376
    readonly spanRangeBehavior?: "default" | "allowPartial";
1✔
377

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

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

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

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

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

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

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

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

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

1✔
541
    /**
1✔
542
     * Add table headers to copied data.
1✔
543
     * @group Editing
1✔
544
     * @defaultValue `false`
1✔
545
     */
1✔
546
    readonly copyHeaders?: boolean;
1✔
547

1✔
548
    /**
1✔
549
     * Determins which keybindings are enabled.
1✔
550
     * @group Editing
1✔
551
     * @defaultValue is
1✔
552

1✔
553
            {
1✔
554
                selectAll: true,
1✔
555
                selectRow: true,
1✔
556
                selectColumn: true,
1✔
557
                downFill: false,
1✔
558
                rightFill: false,
1✔
559
                pageUp: false,
1✔
560
                pageDown: false,
1✔
561
                clear: true,
1✔
562
                copy: true,
1✔
563
                paste: true,
1✔
564
                search: false,
1✔
565
                first: true,
1✔
566
                last: true,
1✔
567
            }
1✔
568
     */
1✔
569
    readonly keybindings?: Partial<Keybinds>;
1✔
570

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

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

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

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

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

1✔
628
    readonly renderers?: readonly InternalCellRenderer<InnerGridCell>[];
1✔
629

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

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

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

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

1✔
656
type ScrollToFn = (
1✔
657
    col: number | { amount: number; unit: "cell" | "px" },
1✔
658
    row: number | { amount: number; unit: "cell" | "px" },
1✔
659
    dir?: "horizontal" | "vertical" | "both",
1✔
660
    paddingX?: number,
1✔
661
    paddingY?: number,
1✔
662
    options?: {
1✔
663
        hAlign?: "start" | "center" | "end";
1✔
664
        vAlign?: "start" | "center" | "end";
1✔
665
    }
1✔
666
) => void;
1✔
667

1✔
668
/** @category DataEditor */
1✔
669
export interface DataEditorRef {
1✔
670
    /**
1✔
671
     * Programatically appends a row.
1✔
672
     * @param col The column index to focus in the new row.
1✔
673
     * @returns A promise which waits for the append to complete.
1✔
674
     */
1✔
675
    appendRow: (col: number, openOverlay?: boolean) => Promise<void>;
1✔
676
    /**
1✔
677
     * Triggers cells to redraw.
1✔
678
     */
1✔
679
    updateCells: DataGridRef["damage"];
1✔
680
    /**
1✔
681
     * Gets the screen space bounds of the requested item.
1✔
682
     */
1✔
683
    getBounds: DataGridRef["getBounds"];
1✔
684
    /**
1✔
685
     * Triggers the data grid to focus itself or the correct accessibility element.
1✔
686
     */
1✔
687
    focus: DataGridRef["focus"];
1✔
688
    /**
1✔
689
     * Generic API for emitting events as if they had been triggered via user interaction.
1✔
690
     */
1✔
691
    emit: (eventName: EmitEvents) => Promise<void>;
1✔
692
    /**
1✔
693
     * Scrolls to the desired cell or location in the grid.
1✔
694
     */
1✔
695
    scrollTo: ScrollToFn;
1✔
696
    /**
1✔
697
     * Causes the columns in the selection to have their natural size recomputed and re-emitted as a resize event.
1✔
698
     */
1✔
699
    remeasureColumns: (cols: CompactSelection) => void;
1✔
700
}
1✔
701

1✔
702
const loadingCell: GridCell = {
1✔
703
    kind: GridCellKind.Loading,
1✔
704
    allowOverlay: false,
1✔
705
};
1✔
706

1✔
707
const emptyGridSelection: GridSelection = {
1✔
708
    columns: CompactSelection.empty(),
1✔
709
    rows: CompactSelection.empty(),
1✔
710
    current: undefined,
1✔
711
};
1✔
712

1✔
713
const DataEditorImpl: React.ForwardRefRenderFunction<DataEditorRef, DataEditorProps> = (p, forwardedRef) => {
1✔
714
    const [gridSelectionInner, setGridSelectionInner] = React.useState<GridSelection>(emptyGridSelection);
652✔
715
    const [overlay, setOverlay] = React.useState<{
652✔
716
        target: Rectangle;
652✔
717
        content: GridCell;
652✔
718
        theme: FullTheme;
652✔
719
        initialValue: string | undefined;
652✔
720
        cell: Item;
652✔
721
        highlight: boolean;
652✔
722
        forceEditMode: boolean;
652✔
723
    }>();
652✔
724
    const searchInputRef = React.useRef<HTMLInputElement | null>(null);
652✔
725
    const canvasRef = React.useRef<HTMLCanvasElement | null>(null);
652✔
726
    const [mouseState, setMouseState] = React.useState<MouseState>();
652✔
727
    const scrollRef = React.useRef<HTMLDivElement | null>(null);
652✔
728
    const lastSent = React.useRef<[number, number]>();
652✔
729

652✔
730
    const safeWindow = typeof window === "undefined" ? null : window;
652!
731

652✔
732
    const {
652✔
733
        rowMarkers = "none",
652✔
734
        rowMarkerWidth: rowMarkerWidthRaw,
652✔
735
        imageEditorOverride,
652✔
736
        getRowThemeOverride,
652✔
737
        markdownDivCreateNode,
652✔
738
        width,
652✔
739
        height,
652✔
740
        columns: columnsIn,
652✔
741
        rows,
652✔
742
        getCellContent,
652✔
743
        onCellClicked,
652✔
744
        onCellActivated,
652✔
745
        onFillPattern,
652✔
746
        onFinishedEditing,
652✔
747
        coercePasteValue,
652✔
748
        drawHeader: drawHeaderIn,
652✔
749
        drawCell: drawCellIn,
652✔
750
        onHeaderClicked,
652✔
751
        onColumnProposeMove,
652✔
752
        spanRangeBehavior = "default",
652✔
753
        onGroupHeaderClicked,
652✔
754
        onCellContextMenu,
652✔
755
        className,
652✔
756
        onHeaderContextMenu,
652✔
757
        getCellsForSelection: getCellsForSelectionIn,
652✔
758
        onGroupHeaderContextMenu,
652✔
759
        onGroupHeaderRenamed,
652✔
760
        onCellEdited,
652✔
761
        onCellsEdited,
652✔
762
        onSearchResultsChanged: onSearchResultsChangedIn,
652✔
763
        searchResults,
652✔
764
        onSearchValueChange,
652✔
765
        searchValue,
652✔
766
        onKeyDown: onKeyDownIn,
652✔
767
        onKeyUp: onKeyUpIn,
652✔
768
        keybindings: keybindingsIn,
652✔
769
        onRowAppended,
652✔
770
        onColumnMoved,
652✔
771
        validateCell: validateCellIn,
652✔
772
        highlightRegions: highlightRegionsIn,
652✔
773
        rangeSelect = "rect",
652✔
774
        columnSelect = "multi",
652✔
775
        rowSelect = "multi",
652✔
776
        rangeSelectionBlending = "exclusive",
652✔
777
        columnSelectionBlending = "exclusive",
652✔
778
        rowSelectionBlending = "exclusive",
652✔
779
        onDelete: onDeleteIn,
652✔
780
        onDragStart,
652✔
781
        onMouseMove,
652✔
782
        onPaste,
652✔
783
        copyHeaders = false,
652✔
784
        freezeColumns = 0,
652✔
785
        rowSelectionMode = "auto",
652✔
786
        rowMarkerStartIndex = 1,
652✔
787
        rowMarkerTheme,
652✔
788
        onHeaderMenuClick,
652✔
789
        getGroupDetails,
652✔
790
        onSearchClose: onSearchCloseIn,
652✔
791
        onItemHovered,
652✔
792
        onSelectionCleared,
652✔
793
        showSearch: showSearchIn,
652✔
794
        onVisibleRegionChanged,
652✔
795
        gridSelection: gridSelectionOuter,
652✔
796
        onGridSelectionChange,
652✔
797
        minColumnWidth: minColumnWidthIn = 50,
652✔
798
        maxColumnWidth: maxColumnWidthIn = 500,
652✔
799
        maxColumnAutoWidth: maxColumnAutoWidthIn,
652✔
800
        provideEditor,
652✔
801
        trailingRowOptions,
652✔
802
        allowedFillDirections = "orthogonal",
652✔
803
        scrollOffsetX,
652✔
804
        scrollOffsetY,
652✔
805
        verticalBorder,
652✔
806
        onDragOverCell,
652✔
807
        onDrop,
652✔
808
        onColumnResize: onColumnResizeIn,
652✔
809
        onColumnResizeEnd: onColumnResizeEndIn,
652✔
810
        onColumnResizeStart: onColumnResizeStartIn,
652✔
811
        customRenderers: additionalRenderers,
652✔
812
        fillHandle,
652✔
813
        drawFocusRing,
652✔
814
        experimental,
652✔
815
        fixedShadowX,
652✔
816
        fixedShadowY,
652✔
817
        headerIcons,
652✔
818
        imageWindowLoader,
652✔
819
        initialSize,
652✔
820
        isDraggable,
652✔
821
        onDragLeave,
652✔
822
        onRowMoved,
652✔
823
        overscrollX: overscrollXIn,
652✔
824
        overscrollY: overscrollYIn,
652✔
825
        preventDiagonalScrolling,
652✔
826
        rightElement,
652✔
827
        rightElementProps,
652✔
828
        smoothScrollX,
652✔
829
        smoothScrollY,
652✔
830
        scaleToRem = false,
652✔
831
        rowHeight: rowHeightIn = 34,
652✔
832
        headerHeight: headerHeightIn = 36,
652✔
833
        groupHeaderHeight: groupHeaderHeightIn = headerHeightIn,
652✔
834
        theme: themeIn,
652✔
835
        isOutsideClick,
652✔
836
        renderers,
652✔
837
    } = p;
652✔
838

652✔
839
    const minColumnWidth = Math.max(minColumnWidthIn, 20);
652✔
840
    const maxColumnWidth = Math.max(maxColumnWidthIn, minColumnWidth);
652✔
841
    const maxColumnAutoWidth = Math.max(maxColumnAutoWidthIn ?? maxColumnWidth, minColumnWidth);
652✔
842

652✔
843
    const docStyle = React.useMemo(() => {
652✔
844
        if (typeof window === "undefined") return { fontSize: "16px" };
133!
845
        return window.getComputedStyle(document.documentElement);
133✔
846
    }, []);
652✔
847

652✔
848
    const fontSizeStr = docStyle.fontSize;
652✔
849

652✔
850
    const remSize = React.useMemo(() => Number.parseFloat(fontSizeStr), [fontSizeStr]);
652✔
851

652✔
852
    const { rowHeight, headerHeight, groupHeaderHeight, theme, overscrollX, overscrollY } = useRemAdjuster({
652✔
853
        groupHeaderHeight: groupHeaderHeightIn,
652✔
854
        headerHeight: headerHeightIn,
652✔
855
        overscrollX: overscrollXIn,
652✔
856
        overscrollY: overscrollYIn,
652✔
857
        remSize,
652✔
858
        rowHeight: rowHeightIn,
652✔
859
        scaleToRem,
652✔
860
        theme: themeIn,
652✔
861
    });
652✔
862

652✔
863
    const keybindings = React.useMemo(() => {
652✔
864
        return keybindingsIn === undefined
133✔
865
            ? keybindingDefaults
130✔
866
            : {
3✔
867
                  ...keybindingDefaults,
3✔
868
                  ...keybindingsIn,
3✔
869
              };
3✔
870
    }, [keybindingsIn]);
652✔
871

652✔
872
    const rowMarkerWidth = rowMarkerWidthRaw ?? (rows > 10_000 ? 48 : rows > 1000 ? 44 : rows > 100 ? 36 : 32);
652!
873
    const hasRowMarkers = rowMarkers !== "none";
652✔
874
    const rowMarkerOffset = hasRowMarkers ? 1 : 0;
652✔
875
    const showTrailingBlankRow = onRowAppended !== undefined;
652✔
876
    const lastRowSticky = trailingRowOptions?.sticky === true;
652✔
877

652✔
878
    const [showSearchInner, setShowSearchInner] = React.useState(false);
652✔
879
    const showSearch = showSearchIn ?? showSearchInner;
652✔
880

652✔
881
    const onSearchClose = React.useCallback(() => {
652✔
882
        if (onSearchCloseIn !== undefined) {
2✔
883
            onSearchCloseIn();
2✔
884
        } else {
2!
885
            setShowSearchInner(false);
×
UNCOV
886
        }
×
887
    }, [onSearchCloseIn]);
652✔
888

652✔
889
    const gridSelectionOuterMangled: GridSelection | undefined = React.useMemo((): GridSelection | undefined => {
652✔
890
        return gridSelectionOuter === undefined ? undefined : shiftSelection(gridSelectionOuter, rowMarkerOffset);
258✔
891
    }, [gridSelectionOuter, rowMarkerOffset]);
652✔
892
    const gridSelection = gridSelectionOuterMangled ?? gridSelectionInner;
652✔
893

652✔
894
    const abortControllerRef = React.useRef(new AbortController());
652✔
895
    React.useEffect(() => {
652✔
896
        return () => {
133✔
897
            // eslint-disable-next-line react-hooks/exhaustive-deps
133✔
898
            abortControllerRef?.current.abort();
133✔
899
        };
133✔
900
    }, []);
652✔
901

652✔
902
    const [getCellsForSelection, getCellsForSeletionDirect] = useCellsForSelection(
652✔
903
        getCellsForSelectionIn,
652✔
904
        getCellContent,
652✔
905
        rowMarkerOffset,
652✔
906
        abortControllerRef.current,
652✔
907
        rows
652✔
908
    );
652✔
909

652✔
910
    const validateCell = React.useCallback<NonNullable<typeof validateCellIn>>(
652✔
911
        (cell, newValue, prevValue) => {
652✔
912
            if (validateCellIn === undefined) return true;
12✔
913
            const item: Item = [cell[0] - rowMarkerOffset, cell[1]];
1✔
914
            return validateCellIn?.(item, newValue, prevValue);
1✔
915
        },
12✔
916
        [rowMarkerOffset, validateCellIn]
652✔
917
    );
652✔
918

652✔
919
    const expectedExternalGridSelection = React.useRef<GridSelection | undefined>(gridSelectionOuter);
652✔
920
    const setGridSelection = React.useCallback(
652✔
921
        (newVal: GridSelection, expand: boolean): void => {
652✔
922
            if (expand) {
168✔
923
                newVal = expandSelection(
126✔
924
                    newVal,
126✔
925
                    getCellsForSelection,
126✔
926
                    rowMarkerOffset,
126✔
927
                    spanRangeBehavior,
126✔
928
                    abortControllerRef.current
126✔
929
                );
126✔
930
            }
126✔
931
            if (onGridSelectionChange !== undefined) {
168✔
932
                expectedExternalGridSelection.current = shiftSelection(newVal, -rowMarkerOffset);
129✔
933
                onGridSelectionChange(expectedExternalGridSelection.current);
129✔
934
            } else {
168✔
935
                setGridSelectionInner(newVal);
39✔
936
            }
39✔
937
        },
168✔
938
        [onGridSelectionChange, getCellsForSelection, rowMarkerOffset, spanRangeBehavior]
652✔
939
    );
652✔
940

652✔
941
    const onColumnResize = whenDefined(
652✔
942
        onColumnResizeIn,
652✔
943
        React.useCallback<NonNullable<typeof onColumnResizeIn>>(
652✔
944
            (_, w, ind, wg) => {
652✔
945
                onColumnResizeIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
11✔
946
            },
11✔
947
            [onColumnResizeIn, rowMarkerOffset, columnsIn]
652✔
948
        )
652✔
949
    );
652✔
950

652✔
951
    const onColumnResizeEnd = whenDefined(
652✔
952
        onColumnResizeEndIn,
652✔
953
        React.useCallback<NonNullable<typeof onColumnResizeEndIn>>(
652✔
954
            (_, w, ind, wg) => {
652✔
955
                onColumnResizeEndIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
2✔
956
            },
2✔
957
            [onColumnResizeEndIn, rowMarkerOffset, columnsIn]
652✔
958
        )
652✔
959
    );
652✔
960

652✔
961
    const onColumnResizeStart = whenDefined(
652✔
962
        onColumnResizeStartIn,
652✔
963
        React.useCallback<NonNullable<typeof onColumnResizeStartIn>>(
652✔
964
            (_, w, ind, wg) => {
652✔
965
                onColumnResizeStartIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
×
UNCOV
966
            },
×
967
            [onColumnResizeStartIn, rowMarkerOffset, columnsIn]
652✔
968
        )
652✔
969
    );
652✔
970

652✔
971
    const drawHeader = whenDefined(
652✔
972
        drawHeaderIn,
652✔
973
        React.useCallback<NonNullable<typeof drawHeaderIn>>(
652✔
974
            (args, draw) => {
652✔
NEW
975
                return drawHeaderIn?.({ ...args, columnIndex: args.columnIndex - rowMarkerOffset }, draw) ?? false;
×
UNCOV
976
            },
×
977
            [drawHeaderIn, rowMarkerOffset]
652✔
978
        )
652✔
979
    );
652✔
980

652✔
981
    const drawCell = whenDefined(
652✔
982
        drawCellIn,
652✔
983
        React.useCallback<NonNullable<typeof drawCellIn>>(
652✔
984
            (args, draw) => {
652✔
NEW
985
                return drawCellIn?.({ ...args, col: args.col - rowMarkerOffset }, draw) ?? false;
×
NEW
986
            },
×
987
            [drawCellIn, rowMarkerOffset]
652✔
988
        )
652✔
989
    );
652✔
990

652✔
991
    const onDelete = React.useCallback<NonNullable<DataEditorProps["onDelete"]>>(
652✔
992
        sel => {
652✔
993
            if (onDeleteIn !== undefined) {
9✔
994
                const result = onDeleteIn(shiftSelection(sel, -rowMarkerOffset));
5✔
995
                if (typeof result === "boolean") {
5!
996
                    return result;
×
UNCOV
997
                }
×
998
                return shiftSelection(result, rowMarkerOffset);
5✔
999
            }
5✔
1000
            return true;
4✔
1001
        },
9✔
1002
        [onDeleteIn, rowMarkerOffset]
652✔
1003
    );
652✔
1004

652✔
1005
    const [setCurrent, setSelectedRows, setSelectedColumns] = useSelectionBehavior(
652✔
1006
        gridSelection,
652✔
1007
        setGridSelection,
652✔
1008
        rangeSelectionBlending,
652✔
1009
        columnSelectionBlending,
652✔
1010
        rowSelectionBlending,
652✔
1011
        rangeSelect
652✔
1012
    );
652✔
1013

652✔
1014
    const mergedTheme = React.useMemo(() => {
652✔
1015
        return mergeAndRealizeTheme(getDataEditorTheme(), theme);
133✔
1016
    }, [theme]);
652✔
1017

652✔
1018
    const [clientSize, setClientSize] = React.useState<readonly [number, number, number]>([10, 10, 0]);
652✔
1019

652✔
1020
    const rendererMap = React.useMemo(() => {
652✔
1021
        if (renderers === undefined) return {};
133!
1022
        const result: Partial<Record<InnerGridCellKind | GridCellKind, InternalCellRenderer<InnerGridCell>>> = {};
133✔
1023
        for (const r of renderers) {
133✔
1024
            result[r.kind] = r;
1,729✔
1025
        }
1,729✔
1026
        return result;
133✔
1027
    }, [renderers]);
652✔
1028

652✔
1029
    const getCellRenderer: <T extends InnerGridCell>(cell: T) => CellRenderer<T> | undefined = React.useCallback(
652✔
1030
        <T extends InnerGridCell>(cell: T) => {
652✔
1031
            if (cell.kind !== GridCellKind.Custom) {
132,392✔
1032
                return rendererMap[cell.kind] as unknown as CellRenderer<T>;
128,662✔
1033
            }
128,662✔
1034
            return additionalRenderers?.find(x => x.isMatch(cell)) as CellRenderer<T>;
132,392✔
1035
        },
132,392✔
1036
        [additionalRenderers, rendererMap]
652✔
1037
    );
652✔
1038

652✔
1039
    const { sizedColumns: columns, nonGrowWidth } = useColumnSizer(
652✔
1040
        columnsIn,
652✔
1041
        rows,
652✔
1042
        getCellsForSeletionDirect,
652✔
1043
        clientSize[0] - (rowMarkerOffset === 0 ? 0 : rowMarkerWidth) - clientSize[2],
652✔
1044
        minColumnWidth,
652✔
1045
        maxColumnAutoWidth,
652✔
1046
        mergedTheme,
652✔
1047
        getCellRenderer,
652✔
1048
        abortControllerRef.current
652✔
1049
    );
652✔
1050

652✔
1051
    const enableGroups = React.useMemo(() => {
652✔
1052
        return columns.some(c => c.group !== undefined);
133✔
1053
    }, [columns]);
652✔
1054

652✔
1055
    const totalHeaderHeight = enableGroups ? headerHeight + groupHeaderHeight : headerHeight;
652✔
1056

652✔
1057
    const numSelectedRows = gridSelection.rows.length;
652✔
1058
    const rowMarkerHeader =
652✔
1059
        rowMarkers === "none"
652✔
1060
            ? ""
521✔
1061
            : numSelectedRows === 0
130✔
1062
            ? headerCellUnheckedMarker
86✔
1063
            : numSelectedRows === rows
44✔
1064
            ? headerCellCheckedMarker
6✔
1065
            : headerCellIndeterminateMarker;
38✔
1066

652✔
1067
    const mangledCols = React.useMemo(() => {
652✔
1068
        if (rowMarkers === "none") return columns;
147✔
1069
        return [
45✔
1070
            {
45✔
1071
                title: rowMarkerHeader,
45✔
1072
                width: rowMarkerWidth,
45✔
1073
                icon: undefined,
45✔
1074
                hasMenu: false,
45✔
1075
                style: "normal" as const,
45✔
1076
                themeOverride: rowMarkerTheme,
45✔
1077
            },
45✔
1078
            ...columns,
45✔
1079
        ];
45✔
1080
    }, [columns, rowMarkerWidth, rowMarkers, rowMarkerHeader, rowMarkerTheme]);
652✔
1081

652✔
1082
    const [visibleRegionY, visibleRegionTy] = React.useMemo(() => {
652✔
1083
        return [
133✔
1084
            scrollOffsetY !== undefined && typeof rowHeight === "number" ? Math.floor(scrollOffsetY / rowHeight) : 0,
133!
1085
            scrollOffsetY !== undefined && typeof rowHeight === "number" ? -(scrollOffsetY % rowHeight) : 0,
133!
1086
        ];
133✔
1087
    }, [scrollOffsetY, rowHeight]);
652✔
1088

652✔
1089
    type VisibleRegion = Rectangle & {
652✔
1090
        /** value in px */
652✔
1091
        tx?: number;
652✔
1092
        /** value in px */
652✔
1093
        ty?: number;
652✔
1094
        extras?: {
652✔
1095
            selected?: Item;
652✔
1096
            freezeRegion?: Rectangle;
652✔
1097
        };
652✔
1098
    };
652✔
1099

652✔
1100
    const visibleRegionRef = React.useRef<VisibleRegion>({
652✔
1101
        height: 1,
652✔
1102
        width: 1,
652✔
1103
        x: 0,
652✔
1104
        y: 0,
652✔
1105
    });
652✔
1106
    const visibleRegionInput = React.useMemo<VisibleRegion>(
652✔
1107
        () => ({
652✔
1108
            x: visibleRegionRef.current.x,
133✔
1109
            y: visibleRegionY,
133✔
1110
            width: visibleRegionRef.current.width ?? 1,
133!
1111
            height: visibleRegionRef.current.height ?? 1,
133!
1112
            // tx: 'TODO',
133✔
1113
            ty: visibleRegionTy,
133✔
1114
        }),
133✔
1115
        [visibleRegionTy, visibleRegionY]
652✔
1116
    );
652✔
1117

652✔
1118
    const hasJustScrolled = React.useRef(false);
652✔
1119

652✔
1120
    const [visibleRegion, setVisibleRegion, empty] = useStateWithReactiveInput<VisibleRegion>(visibleRegionInput);
652✔
1121

652✔
1122
    const vScrollReady = (visibleRegion.height ?? 1) > 1;
652!
1123
    React.useLayoutEffect(() => {
652✔
1124
        if (scrollOffsetY !== undefined && scrollRef.current !== null && vScrollReady) {
266!
1125
            if (scrollRef.current.scrollTop === scrollOffsetY) return;
×
1126
            scrollRef.current.scrollTop = scrollOffsetY;
×
UNCOV
1127
            if (scrollRef.current.scrollTop !== scrollOffsetY) {
×
1128
                empty();
×
UNCOV
1129
            }
×
1130
            hasJustScrolled.current = true;
×
UNCOV
1131
        }
×
1132
    }, [scrollOffsetY, vScrollReady, empty]);
652✔
1133

652✔
1134
    const hScrollReady = (visibleRegion.width ?? 1) > 1;
652!
1135
    React.useLayoutEffect(() => {
652✔
1136
        if (scrollOffsetX !== undefined && scrollRef.current !== null && hScrollReady) {
266!
1137
            if (scrollRef.current.scrollLeft === scrollOffsetX) return;
×
1138
            scrollRef.current.scrollLeft = scrollOffsetX;
×
UNCOV
1139
            if (scrollRef.current.scrollLeft !== scrollOffsetX) {
×
1140
                empty();
×
UNCOV
1141
            }
×
1142
            hasJustScrolled.current = true;
×
UNCOV
1143
        }
×
1144
    }, [scrollOffsetX, hScrollReady, empty]);
652✔
1145

652✔
1146
    const cellXOffset = visibleRegion.x + rowMarkerOffset;
652✔
1147
    const cellYOffset = visibleRegion.y;
652✔
1148

652✔
1149
    const gridRef = React.useRef<DataGridRef | null>(null);
652✔
1150

652✔
1151
    const focus = React.useCallback((immediate?: boolean) => {
652✔
1152
        if (immediate === true) {
121✔
1153
            gridRef.current?.focus();
7✔
1154
        } else {
121✔
1155
            window.requestAnimationFrame(() => {
114✔
1156
                gridRef.current?.focus();
113✔
1157
            });
114✔
1158
        }
114✔
1159
    }, []);
652✔
1160

652✔
1161
    const mangledRows = showTrailingBlankRow ? rows + 1 : rows;
652!
1162

652✔
1163
    const mangledOnCellsEdited = React.useCallback<NonNullable<typeof onCellsEdited>>(
652✔
1164
        (items: readonly EditListItem[]) => {
652✔
1165
            const mangledItems =
27✔
1166
                rowMarkerOffset === 0
27✔
1167
                    ? items
22✔
1168
                    : items.map(x => ({
5✔
1169
                          ...x,
29✔
1170
                          location: [x.location[0] - rowMarkerOffset, x.location[1]] as const,
29✔
1171
                      }));
5✔
1172
            const r = onCellsEdited?.(mangledItems);
27✔
1173

27✔
1174
            if (r !== true) {
27✔
1175
                for (const i of mangledItems) onCellEdited?.(i.location, i.value);
26✔
1176
            }
26✔
1177

27✔
1178
            return r;
27✔
1179
        },
27✔
1180
        [onCellEdited, onCellsEdited, rowMarkerOffset]
652✔
1181
    );
652✔
1182

652✔
1183
    const [fillHighlightRegion, setFillHighlightRegion] = React.useState<Rectangle | undefined>();
652✔
1184

652✔
1185
    // this will generally be undefined triggering the memo less often
652✔
1186
    const highlightRange =
652✔
1187
        gridSelection.current !== undefined &&
652✔
1188
        gridSelection.current.range.width * gridSelection.current.range.height > 1
303✔
1189
            ? gridSelection.current.range
41✔
1190
            : undefined;
610✔
1191
    const highlightRegions = React.useMemo(() => {
652✔
1192
        if (
168✔
1193
            (highlightRegionsIn === undefined || highlightRegionsIn.length === 0) &&
168✔
1194
            highlightRange === undefined &&
167✔
1195
            fillHighlightRegion === undefined
140✔
1196
        )
168✔
1197
            return undefined;
168✔
1198

33✔
1199
        const regions: Highlight[] = [];
33✔
1200

33✔
1201
        if (highlightRegionsIn !== undefined) {
162✔
1202
            for (const r of highlightRegionsIn) {
1✔
1203
                const maxWidth = mangledCols.length - r.range.x - rowMarkerOffset;
1✔
1204
                if (maxWidth > 0) {
1✔
1205
                    regions.push({
1✔
1206
                        color: r.color,
1✔
1207
                        range: {
1✔
1208
                            ...r.range,
1✔
1209
                            x: r.range.x + rowMarkerOffset,
1✔
1210
                            width: Math.min(maxWidth, r.range.width),
1✔
1211
                        },
1✔
1212
                        style: r.style,
1✔
1213
                    });
1✔
1214
                }
1✔
1215
            }
1✔
1216
        }
1✔
1217

33✔
1218
        if (fillHighlightRegion !== undefined) {
162✔
1219
            regions.push({
5✔
1220
                color: withAlpha(mergedTheme.accentColor, 0),
5✔
1221
                range: fillHighlightRegion,
5✔
1222
                style: "dashed",
5✔
1223
            });
5✔
1224
        }
5✔
1225

33✔
1226
        if (highlightRange !== undefined) {
162✔
1227
            regions.push({
27✔
1228
                color: withAlpha(mergedTheme.accentColor, 0.5),
27✔
1229
                range: highlightRange,
27✔
1230
                style: "solid-outline",
27✔
1231
            });
27✔
1232
        }
27✔
1233

33✔
1234
        return regions.length > 0 ? regions : undefined;
168!
1235
    }, [
652✔
1236
        fillHighlightRegion,
652✔
1237
        highlightRange,
652✔
1238
        highlightRegionsIn,
652✔
1239
        mangledCols.length,
652✔
1240
        mergedTheme.accentColor,
652✔
1241
        rowMarkerOffset,
652✔
1242
    ]);
652✔
1243

652✔
1244
    const mangledColsRef = React.useRef(mangledCols);
652✔
1245
    mangledColsRef.current = mangledCols;
652✔
1246
    const getMangledCellContent = React.useCallback(
652✔
1247
        ([col, row]: Item, forceStrict: boolean = false): InnerGridCell => {
652✔
1248
            const isTrailing = showTrailingBlankRow && row === mangledRows - 1;
133,493✔
1249
            const isRowMarkerCol = col === 0 && hasRowMarkers;
133,493✔
1250
            if (isRowMarkerCol) {
133,493✔
1251
                if (isTrailing) {
2,186✔
1252
                    return loadingCell;
98✔
1253
                }
98✔
1254
                return {
2,088✔
1255
                    kind: InnerGridCellKind.Marker,
2,088✔
1256
                    allowOverlay: false,
2,088✔
1257
                    checked: gridSelection?.rows.hasIndex(row) === true,
2,186✔
1258
                    markerKind: rowMarkers === "clickable-number" ? "number" : rowMarkers,
2,186!
1259
                    row: rowMarkerStartIndex + row,
2,186✔
1260
                    drawHandle: onRowMoved !== undefined,
2,186✔
1261
                    cursor: rowMarkers === "clickable-number" ? "pointer" : undefined,
2,186!
1262
                };
2,186✔
1263
            } else if (isTrailing) {
133,493✔
1264
                //If the grid is empty, we will return text
3,759✔
1265
                const isFirst = col === rowMarkerOffset;
3,759✔
1266

3,759✔
1267
                const maybeFirstColumnHint = isFirst ? trailingRowOptions?.hint ?? "" : "";
3,759✔
1268
                const c = mangledColsRef.current[col];
3,759✔
1269

3,759✔
1270
                if (c?.trailingRowOptions?.disabled === true) {
3,759!
1271
                    return loadingCell;
×
1272
                } else {
3,759✔
1273
                    const hint = c?.trailingRowOptions?.hint ?? maybeFirstColumnHint;
3,759!
1274
                    const icon = c?.trailingRowOptions?.addIcon ?? trailingRowOptions?.addIcon;
3,759!
1275
                    return {
3,759✔
1276
                        kind: InnerGridCellKind.NewRow,
3,759✔
1277
                        hint,
3,759✔
1278
                        allowOverlay: false,
3,759✔
1279
                        icon,
3,759✔
1280
                    };
3,759✔
1281
                }
3,759✔
1282
            } else {
131,307✔
1283
                const outerCol = col - rowMarkerOffset;
127,548✔
1284
                if (forceStrict || experimental?.strict === true) {
127,548✔
1285
                    const vr = visibleRegionRef.current;
22,021✔
1286
                    const isOutsideMainArea =
22,021✔
1287
                        vr.x > outerCol ||
22,021✔
1288
                        outerCol > vr.x + vr.width ||
22,021✔
1289
                        vr.y > row ||
22,021✔
1290
                        row > vr.y + vr.height ||
22,021✔
1291
                        row >= rowsRef.current;
22,021✔
1292
                    const isSelected = outerCol === vr.extras?.selected?.[0] && row === vr.extras?.selected[1];
22,021!
1293
                    const isOutsideFreezeArea =
22,021✔
1294
                        vr.extras?.freezeRegion === undefined ||
22,021!
UNCOV
1295
                        vr.extras.freezeRegion.x > outerCol ||
×
UNCOV
1296
                        outerCol > vr.extras.freezeRegion.x + vr.extras.freezeRegion.width ||
×
UNCOV
1297
                        vr.extras.freezeRegion.y > row ||
×
UNCOV
1298
                        row > vr.extras.freezeRegion.y + vr.extras.freezeRegion.height;
×
1299
                    if (isOutsideMainArea && !isSelected && isOutsideFreezeArea) {
22,021!
NEW
1300
                        return loadingCell;
×
UNCOV
1301
                    }
×
1302
                }
22,021✔
1303
                let result = getCellContent([outerCol, row]);
127,548✔
1304
                if (rowMarkerOffset !== 0 && result.span !== undefined) {
127,548!
1305
                    result = {
×
UNCOV
1306
                        ...result,
×
UNCOV
1307
                        span: [result.span[0] + rowMarkerOffset, result.span[1] + rowMarkerOffset],
×
UNCOV
1308
                    };
×
UNCOV
1309
                }
×
1310
                return result;
127,548✔
1311
            }
127,548✔
1312
        },
133,493✔
1313
        [
652✔
1314
            showTrailingBlankRow,
652✔
1315
            mangledRows,
652✔
1316
            hasRowMarkers,
652✔
1317
            gridSelection?.rows,
652✔
1318
            onRowMoved,
652✔
1319
            rowMarkers,
652✔
1320
            rowMarkerOffset,
652✔
1321
            trailingRowOptions?.hint,
652✔
1322
            trailingRowOptions?.addIcon,
652✔
1323
            experimental?.strict,
652✔
1324
            getCellContent,
652✔
1325
            rowMarkerStartIndex,
652✔
1326
        ]
652✔
1327
    );
652✔
1328

652✔
1329
    const mangledGetGroupDetails = React.useCallback<NonNullable<DataEditorProps["getGroupDetails"]>>(
652✔
1330
        group => {
652✔
1331
            let result = getGroupDetails?.(group) ?? { name: group };
8,046✔
1332
            if (onGroupHeaderRenamed !== undefined && group !== "") {
8,046✔
1333
                result = {
91✔
1334
                    icon: result.icon,
91✔
1335
                    name: result.name,
91✔
1336
                    overrideTheme: result.overrideTheme,
91✔
1337
                    actions: [
91✔
1338
                        ...(result.actions ?? []),
91✔
1339
                        {
91✔
1340
                            title: "Rename",
91✔
1341
                            icon: "renameIcon",
91✔
1342
                            onClick: e =>
91✔
1343
                                setRenameGroup({
2✔
1344
                                    group: result.name,
2✔
1345
                                    bounds: e.bounds,
2✔
1346
                                }),
2✔
1347
                        },
91✔
1348
                    ],
91✔
1349
                };
91✔
1350
            }
91✔
1351
            return result;
8,046✔
1352
        },
8,046✔
1353
        [getGroupDetails, onGroupHeaderRenamed]
652✔
1354
    );
652✔
1355

652✔
1356
    const setOverlaySimple = React.useCallback(
652✔
1357
        (val: Omit<NonNullable<typeof overlay>, "theme">) => {
652✔
1358
            const [col, row] = val.cell;
16✔
1359
            const column = mangledCols[col];
16✔
1360
            const groupTheme =
16✔
1361
                column?.group !== undefined ? mangledGetGroupDetails(column.group)?.overrideTheme : undefined;
16!
1362
            const colTheme = column?.themeOverride;
16✔
1363
            const rowTheme = getRowThemeOverride?.(row);
16!
1364

16✔
1365
            setOverlay({
16✔
1366
                ...val,
16✔
1367
                theme: mergeAndRealizeTheme(mergedTheme, groupTheme, colTheme, rowTheme, val.content.themeOverride),
16✔
1368
            });
16✔
1369
        },
16✔
1370
        [getRowThemeOverride, mangledCols, mangledGetGroupDetails, mergedTheme]
652✔
1371
    );
652✔
1372

652✔
1373
    const reselect = React.useCallback(
652✔
1374
        (bounds: Rectangle, fromKeyboard: boolean, initialValue?: string) => {
652✔
1375
            if (gridSelection.current === undefined) return;
16!
1376

16✔
1377
            const [col, row] = gridSelection.current.cell;
16✔
1378
            const c = getMangledCellContent([col, row]);
16✔
1379
            if (c.kind !== GridCellKind.Boolean && c.allowOverlay) {
16✔
1380
                let content = c;
15✔
1381
                if (initialValue !== undefined) {
15✔
1382
                    switch (content.kind) {
7✔
1383
                        case GridCellKind.Number: {
7!
1384
                            const d = maybe(() => (initialValue === "-" ? -0 : Number.parseFloat(initialValue)), 0);
×
1385
                            content = {
×
UNCOV
1386
                                ...content,
×
UNCOV
1387
                                data: Number.isNaN(d) ? 0 : d,
×
UNCOV
1388
                            };
×
1389
                            break;
×
UNCOV
1390
                        }
×
1391
                        case GridCellKind.Text:
7✔
1392
                        case GridCellKind.Markdown:
7✔
1393
                        case GridCellKind.Uri:
7✔
1394
                            content = {
7✔
1395
                                ...content,
7✔
1396
                                data: initialValue,
7✔
1397
                            };
7✔
1398
                            break;
7✔
1399
                    }
7✔
1400
                }
7✔
1401

15✔
1402
                setOverlaySimple({
15✔
1403
                    target: bounds,
15✔
1404
                    content,
15✔
1405
                    initialValue,
15✔
1406
                    cell: [col, row],
15✔
1407
                    highlight: initialValue === undefined,
15✔
1408
                    forceEditMode: initialValue !== undefined,
15✔
1409
                });
15✔
1410
            } else if (c.kind === GridCellKind.Boolean && fromKeyboard && c.readonly !== true) {
16!
1411
                mangledOnCellsEdited([
×
UNCOV
1412
                    {
×
UNCOV
1413
                        location: gridSelection.current.cell,
×
UNCOV
1414
                        value: {
×
UNCOV
1415
                            ...c,
×
UNCOV
1416
                            data: toggleBoolean(c.data),
×
UNCOV
1417
                        },
×
UNCOV
1418
                    },
×
UNCOV
1419
                ]);
×
1420
                gridRef.current?.damage([{ cell: gridSelection.current.cell }]);
×
UNCOV
1421
            }
×
1422
        },
16✔
1423
        [getMangledCellContent, gridSelection, mangledOnCellsEdited, setOverlaySimple]
652✔
1424
    );
652✔
1425

652✔
1426
    const focusOnRowFromTrailingBlankRow = React.useCallback(
652✔
1427
        (col: number, row: number) => {
652✔
1428
            const bounds = gridRef.current?.getBounds(col, row);
1✔
1429
            if (bounds === undefined || scrollRef.current === null) {
1!
1430
                return;
×
UNCOV
1431
            }
×
1432

1✔
1433
            const content = getMangledCellContent([col, row]);
1✔
1434
            if (!content.allowOverlay) {
1!
1435
                return;
×
UNCOV
1436
            }
×
1437

1✔
1438
            setOverlaySimple({
1✔
1439
                target: bounds,
1✔
1440
                content,
1✔
1441
                initialValue: undefined,
1✔
1442
                highlight: true,
1✔
1443
                cell: [col, row],
1✔
1444
                forceEditMode: true,
1✔
1445
            });
1✔
1446
        },
1✔
1447
        [getMangledCellContent, setOverlaySimple]
652✔
1448
    );
652✔
1449

652✔
1450
    const scrollTo = React.useCallback<ScrollToFn>(
652✔
1451
        (col, row, dir = "both", paddingX = 0, paddingY = 0, options = undefined): void => {
652✔
1452
            if (scrollRef.current !== null) {
43✔
1453
                const grid = gridRef.current;
43✔
1454
                const canvas = canvasRef.current;
43✔
1455

43✔
1456
                const trueCol = typeof col !== "number" ? (col.unit === "cell" ? col.amount : undefined) : col;
43!
1457
                const trueRow = typeof row !== "number" ? (row.unit === "cell" ? row.amount : undefined) : row;
43!
1458
                const desiredX = typeof col !== "number" && col.unit === "px" ? col.amount : undefined;
43!
1459
                const desiredY = typeof row !== "number" && row.unit === "px" ? row.amount : undefined;
43✔
1460
                if (grid !== null && canvas !== null) {
43✔
1461
                    let targetRect: Rectangle = {
43✔
1462
                        x: 0,
43✔
1463
                        y: 0,
43✔
1464
                        width: 0,
43✔
1465
                        height: 0,
43✔
1466
                    };
43✔
1467

43✔
1468
                    let scrollX = 0;
43✔
1469
                    let scrollY = 0;
43✔
1470

43✔
1471
                    if (trueCol !== undefined || trueRow !== undefined) {
43!
1472
                        targetRect = grid.getBounds((trueCol ?? 0) + rowMarkerOffset, trueRow ?? 0) ?? targetRect;
43!
1473
                        if (targetRect.width === 0 || targetRect.height === 0) return;
43!
1474
                    }
43✔
1475

43✔
1476
                    const scrollBounds = canvas.getBoundingClientRect();
43✔
1477
                    const scale = scrollBounds.width / canvas.offsetWidth;
43✔
1478

43✔
1479
                    if (desiredX !== undefined) {
43!
1480
                        targetRect = {
×
UNCOV
1481
                            ...targetRect,
×
UNCOV
1482
                            x: desiredX - scrollBounds.left - scrollRef.current.scrollLeft,
×
UNCOV
1483
                            width: 1,
×
UNCOV
1484
                        };
×
UNCOV
1485
                    }
×
1486
                    if (desiredY !== undefined) {
43✔
1487
                        targetRect = {
4✔
1488
                            ...targetRect,
4✔
1489
                            y: desiredY + scrollBounds.top - scrollRef.current.scrollTop,
4✔
1490
                            height: 1,
4✔
1491
                        };
4✔
1492
                    }
4✔
1493

43✔
1494
                    if (targetRect !== undefined) {
43✔
1495
                        const bounds = {
43✔
1496
                            x: targetRect.x - paddingX,
43✔
1497
                            y: targetRect.y - paddingY,
43✔
1498
                            width: targetRect.width + 2 * paddingX,
43✔
1499
                            height: targetRect.height + 2 * paddingY,
43✔
1500
                        };
43✔
1501

43✔
1502
                        let frozenWidth = 0;
43✔
1503
                        for (let i = 0; i < freezeColumns; i++) {
43!
1504
                            frozenWidth += columns[i].width;
×
UNCOV
1505
                        }
×
1506
                        let trailingRowHeight = 0;
43✔
1507
                        if (lastRowSticky) {
43✔
1508
                            trailingRowHeight = typeof rowHeight === "number" ? rowHeight : rowHeight(rows);
43!
1509
                        }
43✔
1510

43✔
1511
                        // scrollBounds is already scaled
43✔
1512
                        let sLeft = frozenWidth * scale + scrollBounds.left + rowMarkerOffset * rowMarkerWidth * scale;
43✔
1513
                        let sRight = scrollBounds.right;
43✔
1514
                        let sTop = scrollBounds.top + totalHeaderHeight * scale;
43✔
1515
                        let sBottom = scrollBounds.bottom - trailingRowHeight * scale;
43✔
1516

43✔
1517
                        const minx = targetRect.width + paddingX * 2;
43✔
1518
                        switch (options?.hAlign) {
43✔
1519
                            case "start":
43!
1520
                                sRight = sLeft + minx;
×
1521
                                break;
×
1522
                            case "end":
43!
1523
                                sLeft = sRight - minx;
×
1524
                                break;
×
1525
                            case "center":
43!
1526
                                sLeft = Math.floor((sLeft + sRight) / 2) - minx / 2;
×
1527
                                sRight = sLeft + minx;
×
1528
                                break;
×
1529
                        }
43✔
1530

43✔
1531
                        const miny = targetRect.height + paddingY * 2;
43✔
1532
                        switch (options?.vAlign) {
43✔
1533
                            case "start":
43✔
1534
                                sBottom = sTop + miny;
1✔
1535
                                break;
1✔
1536
                            case "end":
43✔
1537
                                sTop = sBottom - miny;
1✔
1538
                                break;
1✔
1539
                            case "center":
43✔
1540
                                sTop = Math.floor((sTop + sBottom) / 2) - miny / 2;
1✔
1541
                                sBottom = sTop + miny;
1✔
1542
                                break;
1✔
1543
                        }
43✔
1544

43✔
1545
                        if (sLeft > bounds.x) {
43!
1546
                            scrollX = bounds.x - sLeft;
×
1547
                        } else if (sRight < bounds.x + bounds.width) {
43✔
1548
                            scrollX = bounds.x + bounds.width - sRight;
4✔
1549
                        }
4✔
1550

43✔
1551
                        if (sTop > bounds.y) {
43!
1552
                            scrollY = bounds.y - sTop;
×
1553
                        } else if (sBottom < bounds.y + bounds.height) {
43✔
1554
                            scrollY = bounds.y + bounds.height - sBottom;
12✔
1555
                        }
12✔
1556

43✔
1557
                        if (dir === "vertical" || (typeof col === "number" && col < freezeColumns)) {
43✔
1558
                            scrollX = 0;
2✔
1559
                        } else if (dir === "horizontal") {
43✔
1560
                            scrollY = 0;
6✔
1561
                        }
6✔
1562

43✔
1563
                        if (scrollX !== 0 || scrollY !== 0) {
43✔
1564
                            // Remove scaling as scrollTo method is unaffected by transform scale.
15✔
1565
                            if (scale !== 1) {
15!
1566
                                scrollX /= scale;
×
1567
                                scrollY /= scale;
×
UNCOV
1568
                            }
×
1569
                            scrollRef.current.scrollTo(
15✔
1570
                                scrollX + scrollRef.current.scrollLeft,
15✔
1571
                                scrollY + scrollRef.current.scrollTop
15✔
1572
                            );
15✔
1573
                        }
15✔
1574
                    }
43✔
1575
                }
43✔
1576
            }
43✔
1577
        },
43✔
1578
        [rowMarkerOffset, rowMarkerWidth, totalHeaderHeight, lastRowSticky, freezeColumns, columns, rowHeight, rows]
652✔
1579
    );
652✔
1580

652✔
1581
    const focusCallback = React.useRef(focusOnRowFromTrailingBlankRow);
652✔
1582
    const getCellContentRef = React.useRef(getCellContent);
652✔
1583
    const rowsRef = React.useRef(rows);
652✔
1584
    focusCallback.current = focusOnRowFromTrailingBlankRow;
652✔
1585
    getCellContentRef.current = getCellContent;
652✔
1586
    rowsRef.current = rows;
652✔
1587
    const appendRow = React.useCallback(
652✔
1588
        async (col: number, openOverlay: boolean = true): Promise<void> => {
652✔
1589
            const c = mangledCols[col];
1✔
1590
            if (c?.trailingRowOptions?.disabled === true) {
1!
1591
                return;
×
UNCOV
1592
            }
×
1593
            const appendResult = onRowAppended?.();
1✔
1594

1✔
1595
            let r: "top" | "bottom" | number | undefined = undefined;
1✔
1596
            let bottom = true;
1✔
1597
            if (appendResult !== undefined) {
1!
1598
                r = await appendResult;
×
1599
                if (r === "top") bottom = false;
×
1600
                if (typeof r === "number") bottom = false;
×
UNCOV
1601
            }
×
1602

1✔
1603
            let backoff = 0;
1✔
1604
            const doFocus = () => {
1✔
1605
                if (rowsRef.current <= rows) {
2✔
1606
                    if (backoff < 500) {
1✔
1607
                        window.setTimeout(doFocus, backoff);
1✔
1608
                    }
1✔
1609
                    backoff = 50 + backoff * 2;
1✔
1610
                    return;
1✔
1611
                }
1✔
1612

1✔
1613
                const row = typeof r === "number" ? r : bottom ? rows : 0;
2!
1614
                scrollTo(col - rowMarkerOffset, row);
2✔
1615
                setCurrent(
2✔
1616
                    {
2✔
1617
                        cell: [col, row],
2✔
1618
                        range: {
2✔
1619
                            x: col,
2✔
1620
                            y: row,
2✔
1621
                            width: 1,
2✔
1622
                            height: 1,
2✔
1623
                        },
2✔
1624
                    },
2✔
1625
                    false,
2✔
1626
                    false,
2✔
1627
                    "edit"
2✔
1628
                );
2✔
1629

2✔
1630
                const cell = getCellContentRef.current([col - rowMarkerOffset, row]);
2✔
1631
                if (cell.allowOverlay && isReadWriteCell(cell) && cell.readonly !== true && openOverlay) {
2✔
1632
                    // wait for scroll to have a chance to process
1✔
1633
                    window.setTimeout(() => {
1✔
1634
                        focusCallback.current(col, row);
1✔
1635
                    }, 0);
1✔
1636
                }
1✔
1637
            };
2✔
1638
            // Queue up to allow the consumer to react to the event and let us check if they did
1✔
1639
            doFocus();
1✔
1640
        },
1✔
1641
        [mangledCols, onRowAppended, rowMarkerOffset, rows, scrollTo, setCurrent]
652✔
1642
    );
652✔
1643

652✔
1644
    const getCustomNewRowTargetColumn = React.useCallback(
652✔
1645
        (col: number): number | undefined => {
652✔
1646
            const customTargetColumn =
1✔
1647
                columns[col]?.trailingRowOptions?.targetColumn ?? trailingRowOptions?.targetColumn;
1!
1648

1✔
1649
            if (typeof customTargetColumn === "number") {
1!
1650
                const customTargetOffset = hasRowMarkers ? 1 : 0;
×
1651
                return customTargetColumn + customTargetOffset;
×
UNCOV
1652
            }
×
1653

1✔
1654
            if (typeof customTargetColumn === "object") {
1!
1655
                const maybeIndex = columnsIn.indexOf(customTargetColumn);
×
UNCOV
1656
                if (maybeIndex >= 0) {
×
1657
                    const customTargetOffset = hasRowMarkers ? 1 : 0;
×
1658
                    return maybeIndex + customTargetOffset;
×
UNCOV
1659
                }
×
UNCOV
1660
            }
×
1661

1✔
1662
            return undefined;
1✔
1663
        },
1✔
1664
        [columns, columnsIn, hasRowMarkers, trailingRowOptions?.targetColumn]
652✔
1665
    );
652✔
1666

652✔
1667
    const lastSelectedRowRef = React.useRef<number>();
652✔
1668
    const lastSelectedColRef = React.useRef<number>();
652✔
1669

652✔
1670
    const themeForCell = React.useCallback(
652✔
1671
        (cell: InnerGridCell, pos: Item): FullTheme => {
652✔
1672
            const [col, row] = pos;
20✔
1673
            return mergeAndRealizeTheme(
20✔
1674
                mergedTheme,
20✔
1675
                mangledCols[col]?.themeOverride,
20✔
1676
                getRowThemeOverride?.(row),
20!
1677
                cell.themeOverride
20✔
1678
            );
20✔
1679
        },
20✔
1680
        [getRowThemeOverride, mangledCols, mergedTheme]
652✔
1681
    );
652✔
1682

652✔
1683
    const handleSelect = React.useCallback(
652✔
1684
        (args: GridMouseEventArgs) => {
652✔
1685
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
111!
1686
            const isMultiRow = isMultiKey && rowSelect === "multi";
111✔
1687
            const isMultiCol = isMultiKey && columnSelect === "multi";
111✔
1688
            const [col, row] = args.location;
111✔
1689
            const selectedColumns = gridSelection.columns;
111✔
1690
            const selectedRows = gridSelection.rows;
111✔
1691
            const [cellCol, cellRow] = gridSelection.current?.cell ?? [];
111✔
1692
            // eslint-disable-next-line unicorn/prefer-switch
111✔
1693
            if (args.kind === "cell") {
111✔
1694
                lastSelectedColRef.current = undefined;
95✔
1695

95✔
1696
                lastMouseSelectLocation.current = [col, row];
95✔
1697

95✔
1698
                if (col === 0 && hasRowMarkers) {
95✔
1699
                    if (
15✔
1700
                        (showTrailingBlankRow === true && row === rows) ||
15✔
1701
                        rowMarkers === "number" ||
15✔
1702
                        rowSelect === "none"
14✔
1703
                    )
15✔
1704
                        return;
15✔
1705

14✔
1706
                    const markerCell = getMangledCellContent(args.location);
14✔
1707
                    if (markerCell.kind !== InnerGridCellKind.Marker) {
15!
1708
                        return;
×
UNCOV
1709
                    }
✔
1710

14✔
1711
                    if (onRowMoved !== undefined) {
15!
1712
                        const renderer = getCellRenderer(markerCell);
×
1713
                        assert(renderer?.kind === InnerGridCellKind.Marker);
×
1714
                        const postClick = renderer?.onClick?.({
×
UNCOV
1715
                            ...args,
×
UNCOV
1716
                            cell: markerCell,
×
UNCOV
1717
                            posX: args.localEventX,
×
UNCOV
1718
                            posY: args.localEventY,
×
UNCOV
1719
                            bounds: args.bounds,
×
UNCOV
1720
                            theme: themeForCell(markerCell, args.location),
×
1721
                            preventDefault: () => undefined,
×
UNCOV
1722
                        }) as MarkerCell | undefined;
×
1723
                        if (postClick === undefined || postClick.checked === markerCell.checked) return;
×
UNCOV
1724
                    }
✔
1725

14✔
1726
                    setOverlay(undefined);
14✔
1727
                    focus();
14✔
1728
                    const isSelected = selectedRows.hasIndex(row);
14✔
1729

14✔
1730
                    const lastHighlighted = lastSelectedRowRef.current;
14✔
1731
                    if (
14✔
1732
                        rowSelect === "multi" &&
14✔
1733
                        (args.shiftKey || args.isLongTouch === true) &&
8✔
1734
                        lastHighlighted !== undefined &&
1✔
1735
                        selectedRows.hasIndex(lastHighlighted)
1✔
1736
                    ) {
15✔
1737
                        const newSlice: Slice = [Math.min(lastHighlighted, row), Math.max(lastHighlighted, row) + 1];
1✔
1738

1✔
1739
                        if (isMultiRow || rowSelectionMode === "multi") {
1!
1740
                            setSelectedRows(undefined, newSlice, true);
×
1741
                        } else {
1✔
1742
                            setSelectedRows(CompactSelection.fromSingleSelection(newSlice), undefined, isMultiRow);
1✔
1743
                        }
1✔
1744
                    } else if (isMultiRow || args.isTouch || rowSelectionMode === "multi") {
15✔
1745
                        if (isSelected) {
3✔
1746
                            setSelectedRows(selectedRows.remove(row), undefined, true);
1✔
1747
                        } else {
2✔
1748
                            setSelectedRows(undefined, row, true);
2✔
1749
                            lastSelectedRowRef.current = row;
2✔
1750
                        }
2✔
1751
                    } else if (isSelected && selectedRows.length === 1) {
13✔
1752
                        setSelectedRows(CompactSelection.empty(), undefined, isMultiKey);
1✔
1753
                    } else {
10✔
1754
                        setSelectedRows(CompactSelection.fromSingleSelection(row), undefined, isMultiKey);
9✔
1755
                        lastSelectedRowRef.current = row;
9✔
1756
                    }
9✔
1757
                } else if (col >= rowMarkerOffset && showTrailingBlankRow && row === rows) {
95✔
1758
                    const customTargetColumn = getCustomNewRowTargetColumn(col);
1✔
1759
                    void appendRow(customTargetColumn ?? col);
1✔
1760
                } else {
80✔
1761
                    if (cellCol !== col || cellRow !== row) {
79✔
1762
                        const cell = getMangledCellContent(args.location);
76✔
1763
                        const renderer = getCellRenderer(cell);
76✔
1764

76✔
1765
                        if (renderer?.onSelect !== undefined) {
76!
1766
                            let prevented = false;
×
1767
                            renderer.onSelect({
×
UNCOV
1768
                                ...args,
×
UNCOV
1769
                                cell,
×
UNCOV
1770
                                posX: args.localEventX,
×
UNCOV
1771
                                posY: args.localEventY,
×
UNCOV
1772
                                bounds: args.bounds,
×
1773
                                preventDefault: () => (prevented = true),
×
UNCOV
1774
                                theme: themeForCell(cell, args.location),
×
UNCOV
1775
                            });
×
UNCOV
1776
                            if (prevented) {
×
1777
                                return;
×
UNCOV
1778
                            }
×
UNCOV
1779
                        }
×
1780
                        const isLastStickyRow = lastRowSticky && row === rows;
76✔
1781

76✔
1782
                        const startedFromLastSticky =
76✔
1783
                            lastRowSticky && gridSelection !== undefined && gridSelection.current?.cell[1] === rows;
76✔
1784

76✔
1785
                        if (
76✔
1786
                            (args.shiftKey || args.isLongTouch === true) &&
76✔
1787
                            cellCol !== undefined &&
6✔
1788
                            cellRow !== undefined &&
6✔
1789
                            gridSelection.current !== undefined &&
6✔
1790
                            !startedFromLastSticky
6✔
1791
                        ) {
76✔
1792
                            if (isLastStickyRow) {
6!
UNCOV
1793
                                // If we're making a selection and shift click in to the last sticky row,
×
UNCOV
1794
                                // just drop the event. Don't kill the selection.
×
1795
                                return;
×
UNCOV
1796
                            }
×
1797

6✔
1798
                            const left = Math.min(col, cellCol);
6✔
1799
                            const right = Math.max(col, cellCol);
6✔
1800
                            const top = Math.min(row, cellRow);
6✔
1801
                            const bottom = Math.max(row, cellRow);
6✔
1802
                            setCurrent(
6✔
1803
                                {
6✔
1804
                                    ...gridSelection.current,
6✔
1805
                                    range: {
6✔
1806
                                        x: left,
6✔
1807
                                        y: top,
6✔
1808
                                        width: right - left + 1,
6✔
1809
                                        height: bottom - top + 1,
6✔
1810
                                    },
6✔
1811
                                },
6✔
1812
                                true,
6✔
1813
                                isMultiKey,
6✔
1814
                                "click"
6✔
1815
                            );
6✔
1816
                            lastSelectedRowRef.current = undefined;
6✔
1817
                            focus();
6✔
1818
                        } else {
76✔
1819
                            setCurrent(
70✔
1820
                                {
70✔
1821
                                    cell: [col, row],
70✔
1822
                                    range: { x: col, y: row, width: 1, height: 1 },
70✔
1823
                                },
70✔
1824
                                true,
70✔
1825
                                isMultiKey,
70✔
1826
                                "click"
70✔
1827
                            );
70✔
1828
                            lastSelectedRowRef.current = undefined;
70✔
1829
                            setOverlay(undefined);
70✔
1830
                            focus();
70✔
1831
                        }
70✔
1832
                    }
76✔
1833
                }
79✔
1834
            } else if (args.kind === "header") {
111✔
1835
                lastMouseSelectLocation.current = [col, row];
12✔
1836
                setOverlay(undefined);
12✔
1837
                if (hasRowMarkers && col === 0) {
12✔
1838
                    lastSelectedRowRef.current = undefined;
4✔
1839
                    lastSelectedColRef.current = undefined;
4✔
1840
                    if (rowSelect === "multi") {
4✔
1841
                        if (selectedRows.length !== rows) {
4✔
1842
                            setSelectedRows(CompactSelection.fromSingleSelection([0, rows]), undefined, isMultiKey);
3✔
1843
                        } else {
4✔
1844
                            setSelectedRows(CompactSelection.empty(), undefined, isMultiKey);
1✔
1845
                        }
1✔
1846
                        focus();
4✔
1847
                    }
4✔
1848
                } else {
12✔
1849
                    const lastCol = lastSelectedColRef.current;
8✔
1850
                    if (
8✔
1851
                        columnSelect === "multi" &&
8✔
1852
                        (args.shiftKey || args.isLongTouch === true) &&
7!
UNCOV
1853
                        lastCol !== undefined &&
×
UNCOV
1854
                        selectedColumns.hasIndex(lastCol)
×
1855
                    ) {
8!
1856
                        const newSlice: Slice = [Math.min(lastCol, col), Math.max(lastCol, col) + 1];
×
UNCOV
1857

×
UNCOV
1858
                        if (isMultiCol) {
×
1859
                            setSelectedColumns(undefined, newSlice, isMultiKey);
×
UNCOV
1860
                        } else {
×
1861
                            setSelectedColumns(CompactSelection.fromSingleSelection(newSlice), undefined, isMultiKey);
×
UNCOV
1862
                        }
×
1863
                    } else if (isMultiCol) {
8✔
1864
                        if (selectedColumns.hasIndex(col)) {
1!
1865
                            setSelectedColumns(selectedColumns.remove(col), undefined, isMultiKey);
×
1866
                        } else {
1✔
1867
                            setSelectedColumns(undefined, col, isMultiKey);
1✔
1868
                        }
1✔
1869
                        lastSelectedColRef.current = col;
1✔
1870
                    } else if (columnSelect !== "none") {
8✔
1871
                        setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, isMultiKey);
7✔
1872
                        lastSelectedColRef.current = col;
7✔
1873
                    }
7✔
1874
                    lastSelectedRowRef.current = undefined;
8✔
1875
                    focus();
8✔
1876
                }
8✔
1877
            } else if (args.kind === groupHeaderKind) {
16✔
1878
                lastMouseSelectLocation.current = [col, row];
3✔
1879
            } else if (args.kind === outOfBoundsKind && !args.isMaybeScrollbar) {
4✔
1880
                setGridSelection(emptyGridSelection, false);
1✔
1881
                setOverlay(undefined);
1✔
1882
                focus();
1✔
1883
                onSelectionCleared?.();
1!
1884
                lastSelectedRowRef.current = undefined;
1✔
1885
                lastSelectedColRef.current = undefined;
1✔
1886
            }
1✔
1887
        },
111✔
1888
        [
652✔
1889
            appendRow,
652✔
1890
            columnSelect,
652✔
1891
            focus,
652✔
1892
            getCellRenderer,
652✔
1893
            getCustomNewRowTargetColumn,
652✔
1894
            getMangledCellContent,
652✔
1895
            gridSelection,
652✔
1896
            hasRowMarkers,
652✔
1897
            lastRowSticky,
652✔
1898
            onSelectionCleared,
652✔
1899
            onRowMoved,
652✔
1900
            rowMarkerOffset,
652✔
1901
            rowMarkers,
652✔
1902
            rowSelect,
652✔
1903
            rowSelectionMode,
652✔
1904
            rows,
652✔
1905
            setCurrent,
652✔
1906
            setGridSelection,
652✔
1907
            setSelectedColumns,
652✔
1908
            setSelectedRows,
652✔
1909
            showTrailingBlankRow,
652✔
1910
            themeForCell,
652✔
1911
        ]
652✔
1912
    );
652✔
1913
    const isActivelyDraggingHeader = React.useRef(false);
652✔
1914
    const lastMouseSelectLocation = React.useRef<readonly [number, number]>();
652✔
1915
    const touchDownArgs = React.useRef(visibleRegion);
652✔
1916
    const mouseDownData = React.useRef<{
652✔
1917
        wasDoubleClick: boolean;
652✔
1918
        time: number;
652✔
1919
        button: number;
652✔
1920
        location: Item;
652✔
1921
    }>();
652✔
1922
    const onMouseDown = React.useCallback(
652✔
1923
        (args: GridMouseEventArgs) => {
652✔
1924
            isPrevented.current = false;
128✔
1925
            touchDownArgs.current = visibleRegionRef.current;
128✔
1926
            if (args.button !== 0 && args.button !== 1) {
128✔
1927
                mouseDownData.current = undefined;
1✔
1928
                return;
1✔
1929
            }
1✔
1930

127✔
1931
            const time = performance.now();
127✔
1932
            const wasDoubleClick = time - (mouseDownData.current?.time ?? -1000) < 250;
128✔
1933
            mouseDownData.current = {
128✔
1934
                wasDoubleClick,
128✔
1935
                button: args.button,
128✔
1936
                time,
128✔
1937
                location: args.location,
128✔
1938
            };
128✔
1939

128✔
1940
            if (args?.kind === "header") {
128✔
1941
                isActivelyDraggingHeader.current = true;
18✔
1942
            }
18✔
1943

127✔
1944
            const fh = args.kind === "cell" && args.isFillHandle;
128✔
1945

128✔
1946
            if (!fh && args.kind !== "cell" && args.isEdge) return;
128✔
1947

120✔
1948
            setMouseState({
120✔
1949
                previousSelection: gridSelection,
120✔
1950
                fillHandle: fh,
120✔
1951
            });
120✔
1952
            lastMouseSelectLocation.current = undefined;
120✔
1953

120✔
1954
            if (!args.isTouch && args.button === 0 && !fh) {
128✔
1955
                handleSelect(args);
108✔
1956
            } else if (!args.isTouch && args.button === 1) {
128✔
1957
                lastMouseSelectLocation.current = args.location;
4✔
1958
            }
4✔
1959
        },
128✔
1960
        [gridSelection, handleSelect]
652✔
1961
    );
652✔
1962

652✔
1963
    const [renameGroup, setRenameGroup] = React.useState<{
652✔
1964
        group: string;
652✔
1965
        bounds: Rectangle;
652✔
1966
    }>();
652✔
1967

652✔
1968
    const handleGroupHeaderSelection = React.useCallback(
652✔
1969
        (args: GridMouseEventArgs) => {
652✔
1970
            if (args.kind !== groupHeaderKind || columnSelect !== "multi") {
3!
1971
                return;
×
UNCOV
1972
            }
×
1973
            const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey;
3!
1974
            const [col] = args.location;
3✔
1975
            const selectedColumns = gridSelection.columns;
3✔
1976

3✔
1977
            if (col < rowMarkerOffset) return;
3!
1978

3✔
1979
            const needle = mangledCols[col];
3✔
1980
            let start = col;
3✔
1981
            let end = col;
3✔
1982
            for (let i = col - 1; i >= rowMarkerOffset; i--) {
3✔
1983
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
3!
1984
                start--;
3✔
1985
            }
3✔
1986

3✔
1987
            for (let i = col + 1; i < mangledCols.length; i++) {
3✔
1988
                if (!isGroupEqual(needle.group, mangledCols[i].group)) break;
27!
1989
                end++;
27✔
1990
            }
27✔
1991

3✔
1992
            focus();
3✔
1993

3✔
1994
            if (isMultiKey) {
3✔
1995
                if (selectedColumns.hasAll([start, end + 1])) {
2✔
1996
                    let newVal = selectedColumns;
1✔
1997
                    for (let index = start; index <= end; index++) {
1✔
1998
                        newVal = newVal.remove(index);
11✔
1999
                    }
11✔
2000
                    setSelectedColumns(newVal, undefined, isMultiKey);
1✔
2001
                } else {
1✔
2002
                    setSelectedColumns(undefined, [start, end + 1], isMultiKey);
1✔
2003
                }
1✔
2004
            } else {
3✔
2005
                setSelectedColumns(CompactSelection.fromSingleSelection([start, end + 1]), undefined, isMultiKey);
1✔
2006
            }
1✔
2007
        },
3✔
2008
        [columnSelect, focus, gridSelection.columns, mangledCols, rowMarkerOffset, setSelectedColumns]
652✔
2009
    );
652✔
2010

652✔
2011
    const fillDown = React.useCallback(
652✔
2012
        (reverse: boolean) => {
652✔
2013
            if (gridSelection.current === undefined) return;
1!
2014
            const v: EditListItem[] = [];
1✔
2015
            const r = gridSelection.current.range;
1✔
2016
            for (let x = 0; x < r.width; x++) {
1✔
2017
                const fillCol = x + r.x;
2✔
2018
                const fillVal = getMangledCellContent([fillCol, reverse ? r.y + r.height - 1 : r.y]);
2!
2019
                if (isInnerOnlyCell(fillVal) || !isReadWriteCell(fillVal)) continue;
2!
2020
                for (let y = 1; y < r.height; y++) {
2✔
2021
                    const fillRow = reverse ? r.y + r.height - (y + 1) : y + r.y;
8!
2022
                    const target = [fillCol, fillRow] as const;
8✔
2023
                    v.push({
8✔
2024
                        location: target,
8✔
2025
                        value: { ...fillVal },
8✔
2026
                    });
8✔
2027
                }
8✔
2028
            }
2✔
2029

1✔
2030
            mangledOnCellsEdited(v);
1✔
2031

1✔
2032
            gridRef.current?.damage(
1✔
2033
                v.map(c => ({
1✔
2034
                    cell: c.location,
8✔
2035
                }))
1✔
2036
            );
1✔
2037
        },
1✔
2038
        [getMangledCellContent, gridSelection, mangledOnCellsEdited]
652✔
2039
    );
652✔
2040

652✔
2041
    const isPrevented = React.useRef(false);
652✔
2042

652✔
2043
    const normalSizeColumn = React.useCallback(
652✔
2044
        async (col: number, force: boolean = false): Promise<void> => {
652✔
2045
            if (
3✔
2046
                (mouseDownData.current?.wasDoubleClick === true || force) &&
3✔
2047
                getCellsForSelection !== undefined &&
2✔
2048
                onColumnResize !== undefined
2✔
2049
            ) {
3✔
2050
                const start = visibleRegionRef.current.y;
2✔
2051
                const end = visibleRegionRef.current.height;
2✔
2052
                let cells = getCellsForSelection(
2✔
2053
                    {
2✔
2054
                        x: col,
2✔
2055
                        y: start,
2✔
2056
                        width: 1,
2✔
2057
                        height: Math.min(end, rows - start),
2✔
2058
                    },
2✔
2059
                    abortControllerRef.current.signal
2✔
2060
                );
2✔
2061
                if (typeof cells !== "object") {
2!
2062
                    cells = await cells();
×
UNCOV
2063
                }
×
2064
                const inputCol = columns[col - rowMarkerOffset];
2✔
2065
                const offscreen = document.createElement("canvas");
2✔
2066
                const ctx = offscreen.getContext("2d", { alpha: false });
2✔
2067
                if (ctx !== null) {
2✔
2068
                    ctx.font = mergedTheme.baseFontFull;
2✔
2069
                    const newCol = measureColumn(
2✔
2070
                        ctx,
2✔
2071
                        mergedTheme,
2✔
2072
                        inputCol,
2✔
2073
                        0,
2✔
2074
                        cells,
2✔
2075
                        minColumnWidth,
2✔
2076
                        maxColumnWidth,
2✔
2077
                        false,
2✔
2078
                        getCellRenderer
2✔
2079
                    );
2✔
2080
                    onColumnResize?.(inputCol, newCol.width, col, newCol.width);
2✔
2081
                }
2✔
2082
            }
2✔
2083
        },
3✔
2084
        [
652✔
2085
            columns,
652✔
2086
            getCellsForSelection,
652✔
2087
            maxColumnWidth,
652✔
2088
            mergedTheme,
652✔
2089
            minColumnWidth,
652✔
2090
            onColumnResize,
652✔
2091
            rowMarkerOffset,
652✔
2092
            rows,
652✔
2093
            getCellRenderer,
652✔
2094
        ]
652✔
2095
    );
652✔
2096

652✔
2097
    const [scrollDir, setScrollDir] = React.useState<GridMouseEventArgs["scrollEdge"]>();
652✔
2098

652✔
2099
    const fillPattern = React.useCallback(
652✔
2100
        async (previousSelection: GridSelection, currentSelection: GridSelection) => {
652✔
2101
            const patternRange = previousSelection.current?.range;
4✔
2102

4✔
2103
            if (
4✔
2104
                patternRange === undefined ||
4✔
2105
                getCellsForSelection === undefined ||
4✔
2106
                currentSelection.current === undefined
4✔
2107
            ) {
4!
NEW
2108
                return;
×
NEW
2109
            }
×
2110
            const currentRange = currentSelection.current.range;
4✔
2111

4✔
2112
            if (onFillPattern !== undefined) {
4!
NEW
2113
                let canceled = false;
×
NEW
2114
                onFillPattern({
×
NEW
2115
                    fillDestination: { ...currentRange, x: currentRange.x - rowMarkerOffset },
×
NEW
2116
                    patternSource: { ...patternRange, x: patternRange.x - rowMarkerOffset },
×
NEW
2117
                    preventDefault: () => (canceled = true),
×
NEW
2118
                });
×
NEW
2119
                if (canceled) return;
×
NEW
2120
            }
×
2121

4✔
2122
            let cells = getCellsForSelection(patternRange, abortControllerRef.current.signal);
4✔
2123
            if (typeof cells !== "object") cells = await cells();
4!
2124

4✔
2125
            const pattern = cells;
4✔
2126

4✔
2127
            // loop through all cells in currentSelection.current.range
4✔
2128
            const editItemList: EditListItem[] = [];
4✔
2129
            for (let x = 0; x < currentRange.width; x++) {
4✔
2130
                for (let y = 0; y < currentRange.height; y++) {
4✔
2131
                    const cell: Item = [currentRange.x + x, currentRange.y + y];
15✔
2132
                    if (itemIsInRect(cell, patternRange)) continue;
15✔
2133
                    const patternCell = pattern[y % patternRange.height][x % patternRange.width];
11✔
2134
                    if (isInnerOnlyCell(patternCell) || !isReadWriteCell(patternCell)) continue;
15!
2135
                    editItemList.push({
11✔
2136
                        location: cell,
11✔
2137
                        value: { ...patternCell },
11✔
2138
                    });
11✔
2139
                }
11✔
2140
            }
4✔
2141
            mangledOnCellsEdited(editItemList);
4✔
2142

4✔
2143
            gridRef.current?.damage(
4✔
2144
                editItemList.map(c => ({
4✔
2145
                    cell: c.location,
11✔
2146
                }))
4✔
2147
            );
4✔
2148
        },
4✔
2149
        [getCellsForSelection, mangledOnCellsEdited, onFillPattern, rowMarkerOffset]
652✔
2150
    );
652✔
2151

652✔
2152
    const onMouseUp = React.useCallback(
652✔
2153
        (args: GridMouseEventArgs, isOutside: boolean) => {
652✔
2154
            const mouse = mouseState;
127✔
2155
            setMouseState(undefined);
127✔
2156
            setFillHighlightRegion(undefined);
127✔
2157
            setScrollDir(undefined);
127✔
2158
            isActivelyDraggingHeader.current = false;
127✔
2159

127✔
2160
            if (isOutside) return;
127✔
2161

126✔
2162
            if (
126✔
2163
                mouse?.fillHandle === true &&
127✔
2164
                gridSelection.current !== undefined &&
4✔
2165
                mouse.previousSelection?.current !== undefined
4✔
2166
            ) {
127✔
2167
                if (fillHighlightRegion === undefined) return;
4!
2168
                const newRange = {
4✔
2169
                    ...gridSelection,
4✔
2170
                    current: {
4✔
2171
                        ...gridSelection.current,
4✔
2172
                        range: combineRects(mouse.previousSelection.current.range, fillHighlightRegion),
4✔
2173
                    },
4✔
2174
                };
4✔
2175
                void fillPattern(mouse.previousSelection, newRange);
4✔
2176
                setGridSelection(newRange, true);
4✔
2177
                return;
4✔
2178
            }
4✔
2179

122✔
2180
            const [col, row] = args.location;
122✔
2181
            const [lastMouseDownCol, lastMouseDownRow] = lastMouseSelectLocation.current ?? [];
127✔
2182

127✔
2183
            const preventDefault = () => {
127✔
2184
                isPrevented.current = true;
×
UNCOV
2185
            };
×
2186

127✔
2187
            const handleMaybeClick = (a: GridMouseCellEventArgs): boolean => {
127✔
2188
                const isValidClick = a.isTouch || (lastMouseDownCol === col && lastMouseDownRow === row);
97✔
2189
                if (isValidClick) {
97✔
2190
                    onCellClicked?.([col - rowMarkerOffset, row], {
87✔
2191
                        ...a,
4✔
2192
                        preventDefault,
4✔
2193
                    });
4✔
2194
                }
87✔
2195
                if (a.button === 1) return !isPrevented.current;
97✔
2196
                if (!isPrevented.current) {
94✔
2197
                    const c = getMangledCellContent(args.location);
94✔
2198
                    const r = getCellRenderer(c);
94✔
2199
                    if (r !== undefined && r.onClick !== undefined && isValidClick) {
94✔
2200
                        const newVal = r.onClick({
20✔
2201
                            ...a,
20✔
2202
                            cell: c,
20✔
2203
                            posX: a.localEventX,
20✔
2204
                            posY: a.localEventY,
20✔
2205
                            bounds: a.bounds,
20✔
2206
                            theme: themeForCell(c, args.location),
20✔
2207
                            preventDefault,
20✔
2208
                        });
20✔
2209
                        if (newVal !== undefined && !isInnerOnlyCell(newVal) && isEditableGridCell(newVal)) {
20✔
2210
                            mangledOnCellsEdited([{ location: a.location, value: newVal }]);
4✔
2211
                            gridRef.current?.damage([
4✔
2212
                                {
4✔
2213
                                    cell: a.location,
4✔
2214
                                },
4✔
2215
                            ]);
4✔
2216
                        }
4✔
2217
                    }
20✔
2218
                    if (
94✔
2219
                        !isPrevented.current &&
94✔
2220
                        mouse?.previousSelection?.current?.cell !== undefined &&
94✔
2221
                        gridSelection.current !== undefined
20✔
2222
                    ) {
94✔
2223
                        const [selectedCol, selectedRow] = gridSelection.current.cell;
19✔
2224
                        const [prevCol, prevRow] = mouse.previousSelection.current.cell;
19✔
2225
                        if (col === selectedCol && col === prevCol && row === selectedRow && row === prevRow) {
19✔
2226
                            onCellActivated?.([col - rowMarkerOffset, row]);
3✔
2227
                            reselect(a.bounds, false);
3✔
2228
                            return true;
3✔
2229
                        }
3✔
2230
                    }
19✔
2231
                }
94✔
2232
                return false;
91✔
2233
            };
97✔
2234

127✔
2235
            const clickLocation = args.location[0] - rowMarkerOffset;
127✔
2236
            if (args.isTouch) {
127✔
2237
                const vr = visibleRegionRef.current;
4✔
2238
                const touchVr = touchDownArgs.current;
4✔
2239
                if (vr.x !== touchVr.x || vr.y !== touchVr.y) {
4!
UNCOV
2240
                    // we scrolled, abort
×
2241
                    return;
×
UNCOV
2242
                }
×
2243
                // take care of context menus first if long pressed item is already selected
4✔
2244
                if (args.isLongTouch === true) {
4!
NEW
2245
                    if (args.kind === "cell" && itemsAreEqual(gridSelection.current?.cell, args.location)) {
×
UNCOV
2246
                        onCellContextMenu?.([clickLocation, args.location[1]], {
×
UNCOV
2247
                            ...args,
×
UNCOV
2248
                            preventDefault,
×
UNCOV
2249
                        });
×
2250
                        return;
×
UNCOV
2251
                    } else if (args.kind === "header" && gridSelection.columns.hasIndex(col)) {
×
2252
                        onHeaderContextMenu?.(clickLocation, { ...args, preventDefault });
×
2253
                        return;
×
UNCOV
2254
                    } else if (args.kind === groupHeaderKind) {
×
UNCOV
2255
                        if (clickLocation < 0) {
×
2256
                            return;
×
UNCOV
2257
                        }
×
UNCOV
2258

×
2259
                        onGroupHeaderContextMenu?.(clickLocation, { ...args, preventDefault });
×
2260
                        return;
×
UNCOV
2261
                    }
×
UNCOV
2262
                }
×
2263
                if (args.kind === "cell") {
4✔
2264
                    // click that cell
2✔
2265
                    if (!handleMaybeClick(args)) {
2✔
2266
                        handleSelect(args);
2✔
2267
                    }
2✔
2268
                } else if (args.kind === groupHeaderKind) {
2✔
2269
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
1✔
2270
                } else {
1✔
2271
                    if (args.kind === headerKind) {
1✔
2272
                        onHeaderClicked?.(clickLocation, {
1✔
2273
                            ...args,
1✔
2274
                            preventDefault,
1✔
2275
                        });
1✔
2276
                    }
1✔
2277
                    handleSelect(args);
1✔
2278
                }
1✔
2279
                return;
4✔
2280
            }
4✔
2281

118✔
2282
            if (args.kind === "header") {
127✔
2283
                if (clickLocation < 0) {
16✔
2284
                    return;
3✔
2285
                }
3✔
2286

13✔
2287
                if (args.isEdge) {
16✔
2288
                    void normalSizeColumn(col);
2✔
2289
                } else if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
16✔
2290
                    onHeaderClicked?.(clickLocation, { ...args, preventDefault });
5✔
2291
                }
5✔
2292
            }
16✔
2293

115✔
2294
            if (args.kind === groupHeaderKind) {
127✔
2295
                if (clickLocation < 0) {
3!
2296
                    return;
×
UNCOV
2297
                }
×
2298

3✔
2299
                if (args.button === 0 && col === lastMouseDownCol && row === lastMouseDownRow) {
3✔
2300
                    onGroupHeaderClicked?.(clickLocation, { ...args, preventDefault });
3!
2301
                    if (!isPrevented.current) {
3✔
2302
                        handleGroupHeaderSelection(args);
3✔
2303
                    }
3✔
2304
                }
3✔
2305
            }
3✔
2306

115✔
2307
            if (args.kind === "cell" && (args.button === 0 || args.button === 1)) {
127✔
2308
                handleMaybeClick(args);
95✔
2309
            }
95✔
2310

115✔
2311
            lastMouseSelectLocation.current = undefined;
115✔
2312
        },
127✔
2313
        [
652✔
2314
            mouseState,
652✔
2315
            gridSelection,
652✔
2316
            rowMarkerOffset,
652✔
2317
            fillHighlightRegion,
652✔
2318
            fillPattern,
652✔
2319
            setGridSelection,
652✔
2320
            onCellClicked,
652✔
2321
            getMangledCellContent,
652✔
2322
            getCellRenderer,
652✔
2323
            themeForCell,
652✔
2324
            mangledOnCellsEdited,
652✔
2325
            onCellActivated,
652✔
2326
            reselect,
652✔
2327
            onCellContextMenu,
652✔
2328
            onHeaderContextMenu,
652✔
2329
            onGroupHeaderContextMenu,
652✔
2330
            handleSelect,
652✔
2331
            onGroupHeaderClicked,
652✔
2332
            onHeaderClicked,
652✔
2333
            normalSizeColumn,
652✔
2334
            handleGroupHeaderSelection,
652✔
2335
        ]
652✔
2336
    );
652✔
2337

652✔
2338
    const onMouseMoveImpl = React.useCallback(
652✔
2339
        (args: GridMouseEventArgs) => {
652✔
2340
            const a: GridMouseEventArgs = {
38✔
2341
                ...args,
38✔
2342
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
38✔
2343
            };
38✔
2344
            onMouseMove?.(a);
38✔
2345
            setScrollDir(cv => {
38✔
2346
                if (isActivelyDraggingHeader.current) return [args.scrollEdge[0], 0];
38✔
2347
                if (args.scrollEdge[0] === cv?.[0] && args.scrollEdge[1] === cv[1]) return cv;
38✔
2348
                return mouseState === undefined || (mouseDownData.current?.location[0] ?? 0) < rowMarkerOffset
36!
2349
                    ? undefined
13✔
2350
                    : args.scrollEdge;
13✔
2351
            });
38✔
2352
        },
38✔
2353
        [mouseState, onMouseMove, rowMarkerOffset]
652✔
2354
    );
652✔
2355

652✔
2356
    const onHeaderMenuClickInner = React.useCallback(
652✔
2357
        (col: number, screenPosition: Rectangle) => {
652✔
2358
            onHeaderMenuClick?.(col - rowMarkerOffset, screenPosition);
1✔
2359
        },
1✔
2360
        [onHeaderMenuClick, rowMarkerOffset]
652✔
2361
    );
652✔
2362

652✔
2363
    const currentCell = gridSelection?.current?.cell;
652✔
2364
    const onVisibleRegionChangedImpl = React.useCallback(
652✔
2365
        (
652✔
2366
            region: Rectangle,
137✔
2367
            clientWidth: number,
137✔
2368
            clientHeight: number,
137✔
2369
            rightElWidth: number,
137✔
2370
            tx: number,
137✔
2371
            ty: number
137✔
2372
        ) => {
137✔
2373
            hasJustScrolled.current = false;
137✔
2374
            let selected = currentCell;
137✔
2375
            if (selected !== undefined) {
137✔
2376
                selected = [selected[0] - rowMarkerOffset, selected[1]];
10✔
2377
            }
10✔
2378
            const newRegion = {
137✔
2379
                x: region.x - rowMarkerOffset,
137✔
2380
                y: region.y,
137✔
2381
                width: region.width,
137✔
2382
                height: showTrailingBlankRow && region.y + region.height >= rows ? region.height - 1 : region.height,
137✔
2383
                tx,
137✔
2384
                ty,
137✔
2385
                extras: {
137✔
2386
                    selected,
137✔
2387
                    freezeRegion:
137✔
2388
                        freezeColumns === 0
137✔
2389
                            ? undefined
137!
UNCOV
2390
                            : {
×
UNCOV
2391
                                  x: 0,
×
UNCOV
2392
                                  y: region.y,
×
UNCOV
2393
                                  width: freezeColumns,
×
UNCOV
2394
                                  height: region.height,
×
UNCOV
2395
                              },
×
2396
                },
137✔
2397
            };
137✔
2398
            visibleRegionRef.current = newRegion;
137✔
2399
            setVisibleRegion(newRegion);
137✔
2400
            setClientSize([clientWidth, clientHeight, rightElWidth]);
137✔
2401
            onVisibleRegionChanged?.(newRegion, newRegion.tx, newRegion.ty, newRegion.extras);
137!
2402
        },
137✔
2403
        [
652✔
2404
            currentCell,
652✔
2405
            rowMarkerOffset,
652✔
2406
            showTrailingBlankRow,
652✔
2407
            rows,
652✔
2408
            freezeColumns,
652✔
2409
            setVisibleRegion,
652✔
2410
            onVisibleRegionChanged,
652✔
2411
        ]
652✔
2412
    );
652✔
2413

652✔
2414
    const onColumnMovedImpl = whenDefined(
652✔
2415
        onColumnMoved,
652✔
2416
        React.useCallback(
652✔
2417
            (startIndex: number, endIndex: number) => {
652✔
2418
                onColumnMoved?.(startIndex - rowMarkerOffset, endIndex - rowMarkerOffset);
1✔
2419
                if (columnSelect !== "none") {
1✔
2420
                    setSelectedColumns(CompactSelection.fromSingleSelection(endIndex), undefined, true);
1✔
2421
                }
1✔
2422
            },
1✔
2423
            [columnSelect, onColumnMoved, rowMarkerOffset, setSelectedColumns]
652✔
2424
        )
652✔
2425
    );
652✔
2426

652✔
2427
    const isActivelyDragging = React.useRef(false);
652✔
2428
    const onDragStartImpl = React.useCallback(
652✔
2429
        (args: GridDragEventArgs) => {
652✔
2430
            if (args.location[0] === 0 && rowMarkerOffset > 0) {
1!
2431
                args.preventDefault();
×
2432
                return;
×
UNCOV
2433
            }
×
2434
            onDragStart?.({
1✔
2435
                ...args,
1✔
2436
                location: [args.location[0] - rowMarkerOffset, args.location[1]] as any,
1✔
2437
            });
1✔
2438

1✔
2439
            if (!args.defaultPrevented()) {
1✔
2440
                isActivelyDragging.current = true;
1✔
2441
            }
1✔
2442
            setMouseState(undefined);
1✔
2443
        },
1✔
2444
        [onDragStart, rowMarkerOffset]
652✔
2445
    );
652✔
2446

652✔
2447
    const onDragEnd = React.useCallback(() => {
652✔
2448
        isActivelyDragging.current = false;
×
2449
    }, []);
652✔
2450

652✔
2451
    const hoveredRef = React.useRef<GridMouseEventArgs>();
652✔
2452
    const onItemHoveredImpl = React.useCallback(
652✔
2453
        (args: GridMouseEventArgs) => {
652✔
2454
            if (mouseEventArgsAreEqual(args, hoveredRef.current)) return;
33!
2455
            hoveredRef.current = args;
33✔
2456
            if (mouseDownData?.current?.button !== undefined && mouseDownData.current.button >= 1) return;
33✔
2457
            if (
32✔
2458
                mouseState !== undefined &&
32✔
2459
                mouseDownData.current?.location[0] === 0 &&
19✔
2460
                args.location[0] === 0 &&
3✔
2461
                rowMarkerOffset === 1 &&
3✔
2462
                rowSelect === "multi" &&
3✔
2463
                mouseState.previousSelection &&
2✔
2464
                !mouseState.previousSelection.rows.hasIndex(mouseDownData.current.location[1]) &&
2✔
2465
                gridSelection.rows.hasIndex(mouseDownData.current.location[1])
2✔
2466
            ) {
33✔
2467
                const start = Math.min(mouseDownData.current.location[1], args.location[1]);
2✔
2468
                const end = Math.max(mouseDownData.current.location[1], args.location[1]) + 1;
2✔
2469
                setSelectedRows(CompactSelection.fromSingleSelection([start, end]), undefined, false);
2✔
2470
            }
2✔
2471
            if (
32✔
2472
                mouseState !== undefined &&
32✔
2473
                gridSelection.current !== undefined &&
19✔
2474
                !isActivelyDragging.current &&
17✔
2475
                !isActivelyDraggingHeader.current &&
17✔
2476
                (rangeSelect === "rect" || rangeSelect === "multi-rect")
15✔
2477
            ) {
33✔
2478
                const [selectedCol, selectedRow] = gridSelection.current.cell;
11✔
2479
                // eslint-disable-next-line prefer-const
11✔
2480
                let [col, row] = args.location;
11✔
2481

11✔
2482
                if (row < 0) {
11✔
2483
                    row = visibleRegionRef.current.y;
1✔
2484
                }
1✔
2485

11✔
2486
                if (mouseState.fillHandle === true && mouseState.previousSelection?.current !== undefined) {
11✔
2487
                    const prevRange = mouseState.previousSelection.current.range;
5✔
2488
                    row = Math.min(row, lastRowSticky ? rows - 1 : rows);
5!
2489
                    const rect = getClosestRect(prevRange, col, row, allowedFillDirections);
5✔
2490
                    setFillHighlightRegion(rect);
5✔
2491
                } else {
11✔
2492
                    const startedFromLastStickyRow = lastRowSticky && selectedRow === rows;
6✔
2493
                    if (startedFromLastStickyRow) return;
6!
2494

6✔
2495
                    const landedOnLastStickyRow = lastRowSticky && row === rows;
6✔
2496
                    if (landedOnLastStickyRow) {
6!
NEW
2497
                        if (args.kind === outOfBoundsKind) row--;
×
NEW
2498
                        else return;
×
NEW
2499
                    }
×
2500

6✔
2501
                    col = Math.max(col, rowMarkerOffset);
6✔
2502

6✔
2503
                    const deltaX = col - selectedCol;
6✔
2504
                    const deltaY = row - selectedRow;
6✔
2505

6✔
2506
                    const newRange: Rectangle = {
6✔
2507
                        x: deltaX >= 0 ? selectedCol : col,
6!
2508
                        y: deltaY >= 0 ? selectedRow : row,
6✔
2509
                        width: Math.abs(deltaX) + 1,
6✔
2510
                        height: Math.abs(deltaY) + 1,
6✔
2511
                    };
6✔
2512

6✔
2513
                    setCurrent(
6✔
2514
                        {
6✔
2515
                            ...gridSelection.current,
6✔
2516
                            range: newRange,
6✔
2517
                        },
6✔
2518
                        true,
6✔
2519
                        false,
6✔
2520
                        "drag"
6✔
2521
                    );
6✔
2522
                }
6✔
2523
            }
11✔
2524

32✔
2525
            onItemHovered?.({ ...args, location: [args.location[0] - rowMarkerOffset, args.location[1]] as any });
33✔
2526
        },
33✔
2527
        [
652✔
2528
            allowedFillDirections,
652✔
2529
            mouseState,
652✔
2530
            rowMarkerOffset,
652✔
2531
            rowSelect,
652✔
2532
            gridSelection,
652✔
2533
            rangeSelect,
652✔
2534
            onItemHovered,
652✔
2535
            setSelectedRows,
652✔
2536
            lastRowSticky,
652✔
2537
            rows,
652✔
2538
            setCurrent,
652✔
2539
        ]
652✔
2540
    );
652✔
2541

652✔
2542
    const adjustSelectionOnScroll = React.useCallback(() => {
652✔
NEW
2543
        const args = hoveredRef.current;
×
NEW
2544
        if (args === undefined) return;
×
NEW
2545
        const [xDir, yDir] = args.scrollEdge;
×
NEW
2546
        let [col, row] = args.location;
×
NEW
2547
        const visible = visibleRegionRef.current;
×
NEW
2548
        if (xDir === -1) {
×
NEW
2549
            col = visible.x;
×
NEW
2550
        } else if (xDir === 1) {
×
NEW
2551
            col = visible.x + visible.width;
×
NEW
2552
        }
×
NEW
2553
        if (yDir === -1) {
×
NEW
2554
            row = Math.max(0, visible.y);
×
NEW
2555
        } else if (yDir === 1) {
×
NEW
2556
            row = Math.min(rows, visible.y + visible.height);
×
NEW
2557
        }
×
NEW
2558
        onItemHoveredImpl({
×
NEW
2559
            ...args,
×
NEW
2560
            location: [col, row] as any,
×
NEW
2561
        });
×
2562
    }, [onItemHoveredImpl, rows]);
652✔
2563

652✔
2564
    useAutoscroll(scrollDir, scrollRef, adjustSelectionOnScroll);
652✔
2565

652✔
2566
    // 1 === move one
652✔
2567
    // 2 === move to end
652✔
2568
    const adjustSelection = React.useCallback(
652✔
2569
        (direction: [0 | 1 | -1 | 2 | -2, 0 | 1 | -1 | 2 | -2]) => {
652✔
2570
            if (gridSelection.current === undefined) return;
8!
2571

8✔
2572
            const [x, y] = direction;
8✔
2573
            const [col, row] = gridSelection.current.cell;
8✔
2574
            const old = gridSelection.current.range;
8✔
2575
            let left = old.x;
8✔
2576
            let right = old.x + old.width;
8✔
2577
            let top = old.y;
8✔
2578
            let bottom = old.y + old.height;
8✔
2579

8✔
2580
            // take care of vertical first in case new spans come in
8✔
2581
            if (y !== 0) {
8✔
2582
                switch (y) {
2✔
2583
                    case 2: {
2✔
2584
                        // go to end
1✔
2585
                        bottom = rows;
1✔
2586
                        top = row;
1✔
2587
                        scrollTo(0, bottom, "vertical");
1✔
2588

1✔
2589
                        break;
1✔
2590
                    }
1✔
2591
                    case -2: {
2!
UNCOV
2592
                        // go to start
×
2593
                        top = 0;
×
2594
                        bottom = row + 1;
×
2595
                        scrollTo(0, top, "vertical");
×
UNCOV
2596

×
2597
                        break;
×
UNCOV
2598
                    }
×
2599
                    case 1: {
2✔
2600
                        // motion down
1✔
2601
                        if (top < row) {
1!
2602
                            top++;
×
2603
                            scrollTo(0, top, "vertical");
×
2604
                        } else {
1✔
2605
                            bottom = Math.min(rows, bottom + 1);
1✔
2606
                            scrollTo(0, bottom, "vertical");
1✔
2607
                        }
1✔
2608

1✔
2609
                        break;
1✔
2610
                    }
1✔
2611
                    case -1: {
2!
UNCOV
2612
                        // motion up
×
UNCOV
2613
                        if (bottom > row + 1) {
×
2614
                            bottom--;
×
2615
                            scrollTo(0, bottom, "vertical");
×
UNCOV
2616
                        } else {
×
2617
                            top = Math.max(0, top - 1);
×
2618
                            scrollTo(0, top, "vertical");
×
UNCOV
2619
                        }
×
UNCOV
2620

×
2621
                        break;
×
UNCOV
2622
                    }
×
2623
                    default: {
2!
2624
                        assertNever(y);
×
UNCOV
2625
                    }
×
2626
                }
2✔
2627
            }
2✔
2628

8✔
2629
            if (x !== 0) {
8✔
2630
                if (x === 2) {
6✔
2631
                    right = mangledCols.length;
1✔
2632
                    left = col;
1✔
2633
                    scrollTo(right - 1 - rowMarkerOffset, 0, "horizontal");
1✔
2634
                } else if (x === -2) {
6!
2635
                    left = rowMarkerOffset;
×
2636
                    right = col + 1;
×
2637
                    scrollTo(left - rowMarkerOffset, 0, "horizontal");
×
2638
                } else {
5✔
2639
                    let disallowed: number[] = [];
5✔
2640
                    if (getCellsForSelection !== undefined) {
5✔
2641
                        const cells = getCellsForSelection(
5✔
2642
                            {
5✔
2643
                                x: left,
5✔
2644
                                y: top,
5✔
2645
                                width: right - left - rowMarkerOffset,
5✔
2646
                                height: bottom - top,
5✔
2647
                            },
5✔
2648
                            abortControllerRef.current.signal
5✔
2649
                        );
5✔
2650

5✔
2651
                        if (typeof cells === "object") {
5✔
2652
                            disallowed = getSpanStops(cells);
5✔
2653
                        }
5✔
2654
                    }
5✔
2655
                    if (x === 1) {
5✔
2656
                        // motion right
4✔
2657
                        let done = false;
4✔
2658
                        if (left < col) {
4!
UNCOV
2659
                            if (disallowed.length > 0) {
×
2660
                                const target = range(left + 1, col + 1).find(
×
2661
                                    n => !disallowed.includes(n - rowMarkerOffset)
×
UNCOV
2662
                                );
×
UNCOV
2663
                                if (target !== undefined) {
×
2664
                                    left = target;
×
2665
                                    done = true;
×
UNCOV
2666
                                }
×
UNCOV
2667
                            } else {
×
2668
                                left++;
×
2669
                                done = true;
×
UNCOV
2670
                            }
×
2671
                            if (done) scrollTo(left, 0, "horizontal");
×
UNCOV
2672
                        }
×
2673
                        if (!done) {
4✔
2674
                            right = Math.min(mangledCols.length, right + 1);
4✔
2675
                            scrollTo(right - 1 - rowMarkerOffset, 0, "horizontal");
4✔
2676
                        }
4✔
2677
                    } else if (x === -1) {
5✔
2678
                        // motion left
1✔
2679
                        let done = false;
1✔
2680
                        if (right > col + 1) {
1!
UNCOV
2681
                            if (disallowed.length > 0) {
×
2682
                                const target = range(right - 1, col, -1).find(
×
2683
                                    n => !disallowed.includes(n - rowMarkerOffset)
×
UNCOV
2684
                                );
×
UNCOV
2685
                                if (target !== undefined) {
×
2686
                                    right = target;
×
2687
                                    done = true;
×
UNCOV
2688
                                }
×
UNCOV
2689
                            } else {
×
2690
                                right--;
×
2691
                                done = true;
×
UNCOV
2692
                            }
×
2693
                            if (done) scrollTo(right - rowMarkerOffset, 0, "horizontal");
×
UNCOV
2694
                        }
×
2695
                        if (!done) {
1✔
2696
                            left = Math.max(rowMarkerOffset, left - 1);
1✔
2697
                            scrollTo(left - rowMarkerOffset, 0, "horizontal");
1✔
2698
                        }
1✔
2699
                    } else {
1!
2700
                        assertNever(x);
×
UNCOV
2701
                    }
×
2702
                }
5✔
2703
            }
6✔
2704

8✔
2705
            setCurrent(
8✔
2706
                {
8✔
2707
                    cell: gridSelection.current.cell,
8✔
2708
                    range: {
8✔
2709
                        x: left,
8✔
2710
                        y: top,
8✔
2711
                        width: right - left,
8✔
2712
                        height: bottom - top,
8✔
2713
                    },
8✔
2714
                },
8✔
2715
                true,
8✔
2716
                false,
8✔
2717
                "keyboard-select"
8✔
2718
            );
8✔
2719
        },
8✔
2720
        [getCellsForSelection, gridSelection, mangledCols.length, rowMarkerOffset, rows, scrollTo, setCurrent]
652✔
2721
    );
652✔
2722

652✔
2723
    const updateSelectedCell = React.useCallback(
652✔
2724
        (col: number, row: number, fromEditingTrailingRow: boolean, freeMove: boolean): boolean => {
652✔
2725
            const rowMax = mangledRows - (fromEditingTrailingRow ? 0 : 1);
53!
2726
            col = clamp(col, rowMarkerOffset, columns.length - 1 + rowMarkerOffset);
53✔
2727
            row = clamp(row, 0, rowMax);
53✔
2728

53✔
2729
            if (col === currentCell?.[0] && row === currentCell?.[1]) return false;
53✔
2730
            if (freeMove && gridSelection.current !== undefined) {
53✔
2731
                const newStack = [...gridSelection.current.rangeStack];
1✔
2732
                if (gridSelection.current.range.width > 1 || gridSelection.current.range.height > 1) {
1!
2733
                    newStack.push(gridSelection.current.range);
1✔
2734
                }
1✔
2735
                setGridSelection(
1✔
2736
                    {
1✔
2737
                        ...gridSelection,
1✔
2738
                        current: {
1✔
2739
                            cell: [col, row],
1✔
2740
                            range: { x: col, y: row, width: 1, height: 1 },
1✔
2741
                            rangeStack: newStack,
1✔
2742
                        },
1✔
2743
                    },
1✔
2744
                    true
1✔
2745
                );
1✔
2746
            } else {
53✔
2747
                setCurrent(
25✔
2748
                    {
25✔
2749
                        cell: [col, row],
25✔
2750
                        range: { x: col, y: row, width: 1, height: 1 },
25✔
2751
                    },
25✔
2752
                    true,
25✔
2753
                    false,
25✔
2754
                    "keyboard-nav"
25✔
2755
                );
25✔
2756
            }
25✔
2757

26✔
2758
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
53✔
2759
                lastSent.current = undefined;
2✔
2760
            }
2✔
2761

26✔
2762
            scrollTo(col - rowMarkerOffset, row);
26✔
2763

26✔
2764
            return true;
26✔
2765
        },
53✔
2766
        [
652✔
2767
            mangledRows,
652✔
2768
            rowMarkerOffset,
652✔
2769
            columns.length,
652✔
2770
            currentCell,
652✔
2771
            gridSelection,
652✔
2772
            scrollTo,
652✔
2773
            setGridSelection,
652✔
2774
            setCurrent,
652✔
2775
        ]
652✔
2776
    );
652✔
2777

652✔
2778
    const onFinishEditing = React.useCallback(
652✔
2779
        (newValue: GridCell | undefined, movement: readonly [-1 | 0 | 1, -1 | 0 | 1]) => {
652✔
2780
            if (overlay?.cell !== undefined && newValue !== undefined && isEditableGridCell(newValue)) {
7✔
2781
                mangledOnCellsEdited([{ location: overlay.cell, value: newValue }]);
4✔
2782
                window.requestAnimationFrame(() => {
4✔
2783
                    gridRef.current?.damage([
4✔
2784
                        {
4✔
2785
                            cell: overlay.cell,
4✔
2786
                        },
4✔
2787
                    ]);
4✔
2788
                });
4✔
2789
            }
4✔
2790
            focus(true);
7✔
2791
            setOverlay(undefined);
7✔
2792

7✔
2793
            const [movX, movY] = movement;
7✔
2794
            if (gridSelection.current !== undefined && (movX !== 0 || movY !== 0)) {
7✔
2795
                const isEditingTrailingRow =
3✔
2796
                    gridSelection.current.cell[1] === mangledRows - 1 && newValue !== undefined;
3!
2797
                updateSelectedCell(
3✔
2798
                    clamp(gridSelection.current.cell[0] + movX, 0, mangledCols.length - 1),
3✔
2799
                    clamp(gridSelection.current.cell[1] + movY, 0, mangledRows - 1),
3✔
2800
                    isEditingTrailingRow,
3✔
2801
                    false
3✔
2802
                );
3✔
2803
            }
3✔
2804
            onFinishedEditing?.(newValue, movement);
7✔
2805
        },
7✔
2806
        [
652✔
2807
            overlay?.cell,
652✔
2808
            focus,
652✔
2809
            gridSelection,
652✔
2810
            onFinishedEditing,
652✔
2811
            mangledOnCellsEdited,
652✔
2812
            mangledRows,
652✔
2813
            updateSelectedCell,
652✔
2814
            mangledCols.length,
652✔
2815
        ]
652✔
2816
    );
652✔
2817

652✔
2818
    const overlayID = React.useMemo(() => {
652✔
2819
        return `gdg-overlay-${idCounter++}`;
133✔
2820
    }, []);
652✔
2821

652✔
2822
    const deleteRange = React.useCallback(
652✔
2823
        (r: Rectangle) => {
652✔
2824
            focus();
8✔
2825
            const editList: EditListItem[] = [];
8✔
2826
            for (let x = r.x; x < r.x + r.width; x++) {
8✔
2827
                for (let y = r.y; y < r.y + r.height; y++) {
23✔
2828
                    const cellValue = getCellContent([x - rowMarkerOffset, y]);
1,066✔
2829
                    if (!cellValue.allowOverlay && cellValue.kind !== GridCellKind.Boolean) continue;
1,066✔
2830
                    let newVal: InnerGridCell | undefined = undefined;
1,042✔
2831
                    if (cellValue.kind === GridCellKind.Custom) {
1,066✔
2832
                        const toDelete = getCellRenderer(cellValue);
1✔
2833
                        const editor = toDelete?.provideEditor?.(cellValue);
1!
2834
                        if (toDelete?.onDelete !== undefined) {
1✔
2835
                            newVal = toDelete.onDelete(cellValue);
1✔
2836
                        } else if (isObjectEditorCallbackResult(editor)) {
1!
2837
                            newVal = editor?.deletedValue?.(cellValue);
×
UNCOV
2838
                        }
×
2839
                    } else if (
1✔
2840
                        (isEditableGridCell(cellValue) && cellValue.allowOverlay) ||
1,041✔
2841
                        cellValue.kind === GridCellKind.Boolean
1✔
2842
                    ) {
1,041✔
2843
                        const toDelete = getCellRenderer(cellValue);
1,041✔
2844
                        newVal = toDelete?.onDelete?.(cellValue);
1,041✔
2845
                    }
1,041✔
2846
                    if (newVal !== undefined && !isInnerOnlyCell(newVal) && isEditableGridCell(newVal)) {
1,066✔
2847
                        editList.push({ location: [x, y], value: newVal });
1,041✔
2848
                    }
1,041✔
2849
                }
1,066✔
2850
            }
23✔
2851
            mangledOnCellsEdited(editList);
8✔
2852
            gridRef.current?.damage(editList.map(x => ({ cell: x.location })));
8✔
2853
        },
8✔
2854
        [focus, getCellContent, getCellRenderer, mangledOnCellsEdited, rowMarkerOffset]
652✔
2855
    );
652✔
2856

652✔
2857
    const onKeyDown = React.useCallback(
652✔
2858
        (event: GridKeyEventArgs) => {
652✔
2859
            const fn = async () => {
61✔
2860
                let cancelled = false;
61✔
2861
                if (onKeyDownIn !== undefined) {
61✔
2862
                    onKeyDownIn({
1✔
2863
                        ...event,
1✔
2864
                        cancel: () => {
1✔
2865
                            cancelled = true;
×
UNCOV
2866
                        },
×
2867
                    });
1✔
2868
                }
1✔
2869

61✔
2870
                if (cancelled) return;
61!
2871

61✔
2872
                const cancel = () => {
61✔
2873
                    event.stopPropagation();
42✔
2874
                    event.preventDefault();
42✔
2875
                };
42✔
2876

61✔
2877
                const overlayOpen = overlay !== undefined;
61✔
2878
                const { altKey, shiftKey, metaKey, ctrlKey, key, bounds } = event;
61✔
2879
                const isOSX = browserIsOSX.value;
61✔
2880
                const isPrimaryKey = isOSX ? metaKey : ctrlKey;
61!
2881
                const isDeleteKey = key === "Delete" || (isOSX && key === "Backspace");
61!
2882
                const vr = visibleRegionRef.current;
61✔
2883
                const selectedColumns = gridSelection.columns;
61✔
2884
                const selectedRows = gridSelection.rows;
61✔
2885

61✔
2886
                if (key === "Escape") {
61✔
2887
                    if (overlayOpen) {
4✔
2888
                        setOverlay(undefined);
2✔
2889
                    } else if (keybindings.clear) {
2✔
2890
                        setGridSelection(emptyGridSelection, false);
2✔
2891
                        onSelectionCleared?.();
2!
2892
                    }
2✔
2893
                    return;
4✔
2894
                } else if (isHotkey("primary+a", event) && keybindings.selectAll) {
61✔
2895
                    if (!overlayOpen) {
1✔
2896
                        setGridSelection(
1✔
2897
                            {
1✔
2898
                                columns: CompactSelection.empty(),
1✔
2899
                                rows: CompactSelection.empty(),
1✔
2900
                                current: {
1✔
2901
                                    cell: gridSelection.current?.cell ?? [rowMarkerOffset, 0],
1!
2902
                                    range: {
1✔
2903
                                        x: rowMarkerOffset,
1✔
2904
                                        y: 0,
1✔
2905
                                        width: columnsIn.length,
1✔
2906
                                        height: rows,
1✔
2907
                                    },
1✔
2908
                                    rangeStack: [],
1✔
2909
                                },
1✔
2910
                            },
1✔
2911
                            false
1✔
2912
                        );
1✔
2913
                    } else {
1!
2914
                        const el = document.getElementById(overlayID);
×
UNCOV
2915
                        if (el !== null) {
×
2916
                            const s = window.getSelection();
×
2917
                            const r = document.createRange();
×
2918
                            r.selectNodeContents(el);
×
2919
                            s?.removeAllRanges();
×
2920
                            s?.addRange(r);
×
UNCOV
2921
                        }
×
UNCOV
2922
                    }
×
2923
                    cancel();
1✔
2924
                    return;
1✔
2925
                } else if (isHotkey("primary+f", event) && keybindings.search) {
57!
2926
                    cancel();
×
2927
                    searchInputRef?.current?.focus({ preventScroll: true });
×
2928
                    setShowSearchInner(true);
×
UNCOV
2929
                }
✔
2930

56✔
2931
                if (isDeleteKey) {
61✔
2932
                    const callbackResult = onDelete?.(gridSelection) ?? true;
8✔
2933
                    cancel();
8✔
2934
                    if (callbackResult !== false) {
8✔
2935
                        const toDelete = callbackResult === true ? gridSelection : callbackResult;
8✔
2936

8✔
2937
                        // delete order:
8✔
2938
                        // 1) primary range
8✔
2939
                        // 2) secondary ranges
8✔
2940
                        // 3) columns
8✔
2941
                        // 4) rows
8✔
2942

8✔
2943
                        if (toDelete.current !== undefined) {
8✔
2944
                            deleteRange(toDelete.current.range);
5✔
2945
                            for (const r of toDelete.current.rangeStack) {
5!
2946
                                deleteRange(r);
×
UNCOV
2947
                            }
×
2948
                        }
5✔
2949

8✔
2950
                        for (const r of toDelete.rows) {
8✔
2951
                            deleteRange({
1✔
2952
                                x: rowMarkerOffset,
1✔
2953
                                y: r,
1✔
2954
                                width: mangledCols.length - rowMarkerOffset,
1✔
2955
                                height: 1,
1✔
2956
                            });
1✔
2957
                        }
1✔
2958

8✔
2959
                        for (const col of toDelete.columns) {
8✔
2960
                            deleteRange({
1✔
2961
                                x: col,
1✔
2962
                                y: 0,
1✔
2963
                                width: 1,
1✔
2964
                                height: rows,
1✔
2965
                            });
1✔
2966
                        }
1✔
2967
                    }
8✔
2968
                    return;
8✔
2969
                }
8✔
2970

48✔
2971
                if (gridSelection.current === undefined) return;
48✔
2972
                let [col, row] = gridSelection.current.cell;
45✔
2973
                let freeMove = false;
45✔
2974

45✔
2975
                if (keybindings.selectColumn && isHotkey("ctrl+ ", event) && columnSelect !== "none") {
61✔
2976
                    if (selectedColumns.hasIndex(col)) {
2!
2977
                        setSelectedColumns(selectedColumns.remove(col), undefined, true);
×
2978
                    } else {
2✔
2979
                        if (columnSelect === "single") {
2!
2980
                            setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, true);
×
2981
                        } else {
2✔
2982
                            setSelectedColumns(undefined, col, true);
2✔
2983
                        }
2✔
2984
                    }
2✔
2985
                } else if (keybindings.selectRow && isHotkey("shift+ ", event) && rowSelect !== "none") {
61✔
2986
                    if (selectedRows.hasIndex(row)) {
2!
2987
                        setSelectedRows(selectedRows.remove(row), undefined, true);
×
2988
                    } else {
2✔
2989
                        if (rowSelect === "single") {
2!
2990
                            setSelectedRows(CompactSelection.fromSingleSelection(row), undefined, true);
×
2991
                        } else {
2✔
2992
                            setSelectedRows(undefined, row, true);
2✔
2993
                        }
2✔
2994
                    }
2✔
2995
                } else if (
2✔
2996
                    (isHotkey("Enter", event) || isHotkey(" ", event) || isHotkey("shift+Enter", event)) &&
41✔
2997
                    bounds !== undefined
8✔
2998
                ) {
41✔
2999
                    if (overlayOpen) {
8✔
3000
                        setOverlay(undefined);
2✔
3001
                        if (isHotkey("Enter", event)) {
2✔
3002
                            row++;
2✔
3003
                        } else if (isHotkey("shift+Enter", event)) {
2!
3004
                            row--;
×
UNCOV
3005
                        }
×
3006
                    } else if (row === rows && showTrailingBlankRow) {
8!
3007
                        window.setTimeout(() => {
×
3008
                            const customTargetColumn = getCustomNewRowTargetColumn(col);
×
3009
                            void appendRow(customTargetColumn ?? col);
×
UNCOV
3010
                        }, 0);
×
3011
                    } else {
6✔
3012
                        onCellActivated?.([col - rowMarkerOffset, row]);
6✔
3013
                        reselect(bounds, true);
6✔
3014
                        cancel();
6✔
3015
                    }
6✔
3016
                } else if (
8✔
3017
                    keybindings.downFill &&
33✔
3018
                    isHotkey("primary+_68", event) &&
1✔
3019
                    gridSelection.current.range.height > 1
1✔
3020
                ) {
33✔
3021
                    // ctrl/cmd + d
1✔
3022
                    fillDown(false);
1✔
3023
                    cancel();
1✔
3024
                } else if (
1✔
3025
                    keybindings.rightFill &&
32✔
3026
                    isHotkey("primary+_82", event) &&
1✔
3027
                    gridSelection.current.range.width > 1
1✔
3028
                ) {
32✔
3029
                    // ctrl/cmd + r
1✔
3030
                    const editList: EditListItem[] = [];
1✔
3031
                    const r = gridSelection.current.range;
1✔
3032
                    for (let y = 0; y < r.height; y++) {
1✔
3033
                        const fillRow = y + r.y;
5✔
3034
                        const fillVal = getMangledCellContent([r.x, fillRow]);
5✔
3035
                        if (isInnerOnlyCell(fillVal) || !isReadWriteCell(fillVal)) continue;
5!
3036
                        for (let x = 1; x < r.width; x++) {
5✔
3037
                            const fillCol = x + r.x;
5✔
3038
                            const target = [fillCol, fillRow] as const;
5✔
3039
                            editList.push({
5✔
3040
                                location: target,
5✔
3041
                                value: { ...fillVal },
5✔
3042
                            });
5✔
3043
                        }
5✔
3044
                    }
5✔
3045
                    mangledOnCellsEdited(editList);
1✔
3046
                    gridRef.current?.damage(
1✔
3047
                        editList.map(c => ({
1✔
3048
                            cell: c.location,
5✔
3049
                        }))
1✔
3050
                    );
1✔
3051
                    cancel();
1✔
3052
                } else if (keybindings.pageDown && isHotkey("PageDown", event)) {
32!
3053
                    row += Math.max(1, visibleRegionRef.current.height - 4); // partial cell accounting
×
3054
                    cancel();
×
3055
                } else if (keybindings.pageUp && isHotkey("PageUp", event)) {
31!
3056
                    row -= Math.max(1, visibleRegionRef.current.height - 4); // partial cell accounting
×
3057
                    cancel();
×
3058
                } else if (keybindings.first && isHotkey("primary+Home", event)) {
31!
3059
                    setOverlay(undefined);
×
3060
                    row = 0;
×
3061
                    col = 0;
×
3062
                } else if (keybindings.last && isHotkey("primary+End", event)) {
31!
3063
                    setOverlay(undefined);
×
3064
                    row = Number.MAX_SAFE_INTEGER;
×
3065
                    col = Number.MAX_SAFE_INTEGER;
×
3066
                } else if (keybindings.first && isHotkey("primary+shift+Home", event)) {
31!
3067
                    setOverlay(undefined);
×
3068
                    adjustSelection([-2, -2]);
×
3069
                } else if (keybindings.last && isHotkey("primary+shift+End", event)) {
31!
3070
                    setOverlay(undefined);
×
3071
                    adjustSelection([2, 2]);
×
UNCOV
3072
                    // eslint-disable-next-line unicorn/prefer-switch
×
3073
                } else if (key === "ArrowDown") {
31✔
3074
                    if (ctrlKey && altKey) {
8!
3075
                        return;
×
UNCOV
3076
                    }
×
3077
                    setOverlay(undefined);
8✔
3078
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
8!
3079
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
2✔
3080
                        adjustSelection([0, isPrimaryKey && !altKey ? 2 : 1]);
2✔
3081
                    } else {
8✔
3082
                        if (altKey && !isPrimaryKey) {
6!
3083
                            freeMove = true;
×
UNCOV
3084
                        }
×
3085
                        if (isPrimaryKey && !altKey) {
6✔
3086
                            row = rows - 1;
1✔
3087
                        } else {
6✔
3088
                            row += 1;
5✔
3089
                        }
5✔
3090
                    }
6✔
3091
                } else if (key === "ArrowUp" || key === "Home") {
31✔
3092
                    const asPrimary = key === "Home" || isPrimaryKey;
2✔
3093
                    setOverlay(undefined);
2✔
3094
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
2!
UNCOV
3095
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
×
3096
                        adjustSelection([0, asPrimary && !altKey ? -2 : -1]);
×
3097
                    } else {
2✔
3098
                        if (altKey && !asPrimary) {
2!
3099
                            freeMove = true;
×
UNCOV
3100
                        }
×
3101
                        row += asPrimary && !altKey ? Number.MIN_SAFE_INTEGER : -1;
2✔
3102
                    }
2✔
3103
                } else if (key === "ArrowRight" || key === "End") {
23✔
3104
                    const asPrimary = key === "End" || isPrimaryKey;
8✔
3105
                    setOverlay(undefined);
8✔
3106
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
8!
3107
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
5✔
3108
                        adjustSelection([asPrimary && !altKey ? 2 : 1, 0]);
5✔
3109
                    } else {
8✔
3110
                        if (altKey && !asPrimary) {
3!
3111
                            freeMove = true;
×
UNCOV
3112
                        }
×
3113
                        col += asPrimary && !altKey ? Number.MAX_SAFE_INTEGER : 1;
3✔
3114
                    }
3✔
3115
                } else if (key === "ArrowLeft") {
21✔
3116
                    setOverlay(undefined);
4✔
3117
                    if (shiftKey && (rangeSelect === "rect" || rangeSelect === "multi-rect")) {
4!
3118
                        // ctrl + alt is used as a screen reader command, let's not nuke it.
1✔
3119
                        adjustSelection([isPrimaryKey && !altKey ? -2 : -1, 0]);
1!
3120
                    } else {
4✔
3121
                        if (altKey && !isPrimaryKey) {
3✔
3122
                            freeMove = true;
1✔
3123
                        }
1✔
3124
                        col += isPrimaryKey && !altKey ? Number.MIN_SAFE_INTEGER : -1;
3✔
3125
                    }
3✔
3126
                } else if (key === "Tab") {
13✔
3127
                    setOverlay(undefined);
2✔
3128
                    if (shiftKey) {
2✔
3129
                        col--;
1✔
3130
                    } else {
1✔
3131
                        col++;
1✔
3132
                    }
1✔
3133
                } else if (
2✔
3134
                    !metaKey &&
7✔
3135
                    !ctrlKey &&
7✔
3136
                    gridSelection.current !== undefined &&
7✔
3137
                    key.length === 1 &&
7✔
3138
                    /[ -~]/g.test(key) &&
7✔
3139
                    bounds !== undefined &&
7✔
3140
                    isReadWriteCell(getCellContent([col - rowMarkerOffset, Math.max(0, Math.min(row, rows - 1))]))
7✔
3141
                ) {
7✔
3142
                    if (
7✔
3143
                        (!lastRowSticky || row !== rows) &&
7✔
3144
                        (vr.y > row || row > vr.y + vr.height || vr.x > col || col > vr.x + vr.width)
7✔
3145
                    ) {
7!
3146
                        return;
×
UNCOV
3147
                    }
×
3148
                    reselect(bounds, true, key);
7✔
3149
                    cancel();
7✔
3150
                }
7✔
3151

45✔
3152
                const moved = updateSelectedCell(col, row, false, freeMove);
45✔
3153
                if (moved) {
61✔
3154
                    cancel();
18✔
3155
                }
18✔
3156
            };
61✔
3157
            void fn();
61✔
3158
        },
61✔
3159
        [
652✔
3160
            onKeyDownIn,
652✔
3161
            deleteRange,
652✔
3162
            overlay,
652✔
3163
            gridSelection,
652✔
3164
            keybindings.selectAll,
652✔
3165
            keybindings.search,
652✔
3166
            keybindings.selectColumn,
652✔
3167
            keybindings.selectRow,
652✔
3168
            keybindings.downFill,
652✔
3169
            keybindings.rightFill,
652✔
3170
            keybindings.pageDown,
652✔
3171
            keybindings.pageUp,
652✔
3172
            keybindings.first,
652✔
3173
            keybindings.last,
652✔
3174
            keybindings.clear,
652✔
3175
            columnSelect,
652✔
3176
            rowSelect,
652✔
3177
            getCellContent,
652✔
3178
            rowMarkerOffset,
652✔
3179
            updateSelectedCell,
652✔
3180
            setGridSelection,
652✔
3181
            onSelectionCleared,
652✔
3182
            columnsIn.length,
652✔
3183
            rows,
652✔
3184
            overlayID,
652✔
3185
            mangledOnCellsEdited,
652✔
3186
            onDelete,
652✔
3187
            mangledCols.length,
652✔
3188
            setSelectedColumns,
652✔
3189
            setSelectedRows,
652✔
3190
            showTrailingBlankRow,
652✔
3191
            getCustomNewRowTargetColumn,
652✔
3192
            appendRow,
652✔
3193
            onCellActivated,
652✔
3194
            reselect,
652✔
3195
            fillDown,
652✔
3196
            getMangledCellContent,
652✔
3197
            adjustSelection,
652✔
3198
            rangeSelect,
652✔
3199
            lastRowSticky,
652✔
3200
        ]
652✔
3201
    );
652✔
3202

652✔
3203
    const onContextMenu = React.useCallback(
652✔
3204
        (args: GridMouseEventArgs, preventDefault: () => void) => {
652✔
3205
            const adjustedCol = args.location[0] - rowMarkerOffset;
7✔
3206
            if (args.kind === "header") {
7!
3207
                onHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
UNCOV
3208
            }
×
3209

7✔
3210
            if (args.kind === groupHeaderKind) {
7!
UNCOV
3211
                if (adjustedCol < 0) {
×
3212
                    return;
×
UNCOV
3213
                }
×
3214
                onGroupHeaderContextMenu?.(adjustedCol, { ...args, preventDefault });
×
UNCOV
3215
            }
×
3216

7✔
3217
            if (args.kind === "cell") {
7✔
3218
                const [col, row] = args.location;
7✔
3219
                onCellContextMenu?.([adjustedCol, row], {
7✔
3220
                    ...args,
7✔
3221
                    preventDefault,
7✔
3222
                });
7✔
3223

7✔
3224
                if (!gridSelectionHasItem(gridSelection, args.location)) {
7✔
3225
                    updateSelectedCell(col, row, false, false);
3✔
3226
                }
3✔
3227
            }
7✔
3228
        },
7✔
3229
        [
652✔
3230
            gridSelection,
652✔
3231
            onCellContextMenu,
652✔
3232
            onGroupHeaderContextMenu,
652✔
3233
            onHeaderContextMenu,
652✔
3234
            rowMarkerOffset,
652✔
3235
            updateSelectedCell,
652✔
3236
        ]
652✔
3237
    );
652✔
3238

652✔
3239
    const onPasteInternal = React.useCallback(
652✔
3240
        async (e?: ClipboardEvent) => {
652✔
3241
            if (!keybindings.paste) return;
6!
3242
            function pasteToCell(
6✔
3243
                inner: InnerGridCell,
51✔
3244
                target: Item,
51✔
3245
                rawValue: string | boolean | string[] | number | boolean | BooleanEmpty | BooleanIndeterminate,
51✔
3246
                formatted?: string | string[]
51✔
3247
            ): EditListItem | undefined {
51✔
3248
                const stringifiedRawValue =
51✔
3249
                    typeof rawValue === "object" ? rawValue?.join("\n") ?? "" : rawValue?.toString() ?? "";
51!
3250

51✔
3251
                if (!isInnerOnlyCell(inner) && isReadWriteCell(inner) && inner.readonly !== true) {
51✔
3252
                    const coerced = coercePasteValue?.(stringifiedRawValue, inner);
51!
3253
                    if (coerced !== undefined && isEditableGridCell(coerced)) {
51!
UNCOV
3254
                        if (process.env.NODE_ENV !== "production" && coerced.kind !== inner.kind) {
×
UNCOV
3255
                            // eslint-disable-next-line no-console
×
3256
                            console.warn("Coercion should not change cell kind.");
×
UNCOV
3257
                        }
×
3258
                        return {
×
UNCOV
3259
                            location: target,
×
UNCOV
3260
                            value: coerced,
×
UNCOV
3261
                        };
×
UNCOV
3262
                    }
×
3263
                    const r = getCellRenderer(inner);
51✔
3264
                    if (r === undefined) return undefined;
51!
3265
                    if (r.kind === GridCellKind.Custom) {
51✔
3266
                        assert(inner.kind === GridCellKind.Custom);
1✔
3267
                        const newVal = (r as unknown as CustomRenderer<CustomCell<any>>).onPaste?.(
1✔
3268
                            stringifiedRawValue,
1✔
3269
                            inner.data
1✔
3270
                        );
1✔
3271
                        if (newVal === undefined) return undefined;
1!
3272
                        return {
×
UNCOV
3273
                            location: target,
×
UNCOV
3274
                            value: {
×
UNCOV
3275
                                ...inner,
×
UNCOV
3276
                                data: newVal,
×
UNCOV
3277
                            },
×
UNCOV
3278
                        };
×
3279
                    } else {
51✔
3280
                        const newVal = r.onPaste?.(stringifiedRawValue, inner, {
50✔
3281
                            formatted,
50✔
3282
                            formattedString: typeof formatted === "string" ? formatted : formatted?.join("\n"),
50!
3283
                            rawValue,
50✔
3284
                        });
50✔
3285
                        if (newVal === undefined) return undefined;
50✔
3286
                        assert(newVal.kind === inner.kind);
36✔
3287
                        return {
36✔
3288
                            location: target,
36✔
3289
                            value: newVal,
36✔
3290
                        };
36✔
3291
                    }
36✔
3292
                }
51!
3293
                return undefined;
×
3294
            }
51✔
3295

6✔
3296
            const selectedColumns = gridSelection.columns;
6✔
3297
            const selectedRows = gridSelection.rows;
6✔
3298
            const focused =
6✔
3299
                scrollRef.current?.contains(document.activeElement) === true ||
6✔
3300
                canvasRef.current?.contains(document.activeElement) === true;
6✔
3301

6✔
3302
            let target: Item | undefined;
6✔
3303

6✔
3304
            if (gridSelection.current !== undefined) {
6✔
3305
                target = [gridSelection.current.range.x, gridSelection.current.range.y];
5✔
3306
            } else if (selectedColumns.length === 1) {
6!
UNCOV
3307
                target = [selectedColumns.first() ?? 0, 0];
×
3308
            } else if (selectedRows.length === 1) {
1!
UNCOV
3309
                target = [rowMarkerOffset, selectedRows.first() ?? 0];
×
UNCOV
3310
            }
×
3311

6✔
3312
            if (focused && target !== undefined) {
6✔
3313
                let data: CopyBuffer | undefined;
5✔
3314
                let text: string | undefined;
5✔
3315

5✔
3316
                const textPlain = "text/plain";
5✔
3317
                const textHtml = "text/html";
5✔
3318

5✔
3319
                if (navigator.clipboard.read !== undefined) {
5!
3320
                    const clipboardContent = await navigator.clipboard.read();
×
UNCOV
3321

×
UNCOV
3322
                    for (const item of clipboardContent) {
×
UNCOV
3323
                        if (item.types.includes(textHtml)) {
×
3324
                            const htmlBlob = await item.getType(textHtml);
×
3325
                            const html = await htmlBlob.text();
×
3326
                            const decoded = decodeHTML(html);
×
UNCOV
3327
                            if (decoded !== undefined) {
×
3328
                                data = decoded;
×
3329
                                break;
×
UNCOV
3330
                            }
×
UNCOV
3331
                        }
×
UNCOV
3332
                        if (item.types.includes(textPlain)) {
×
UNCOV
3333
                            // eslint-disable-next-line unicorn/no-await-expression-member
×
3334
                            text = await (await item.getType(textPlain)).text();
×
UNCOV
3335
                        }
×
UNCOV
3336
                    }
×
3337
                } else if (navigator.clipboard.readText !== undefined) {
5✔
3338
                    text = await navigator.clipboard.readText();
5✔
3339
                } else if (e !== undefined && e?.clipboardData !== null) {
5!
UNCOV
3340
                    if (e.clipboardData.types.includes(textHtml)) {
×
3341
                        const html = e.clipboardData.getData(textHtml);
×
3342
                        data = decodeHTML(html);
×
UNCOV
3343
                    }
×
UNCOV
3344
                    if (data === undefined && e.clipboardData.types.includes(textPlain)) {
×
3345
                        text = e.clipboardData.getData(textPlain);
×
UNCOV
3346
                    }
×
UNCOV
3347
                } else {
×
3348
                    return; // I didn't want to read that paste value anyway
×
UNCOV
3349
                }
×
3350

5✔
3351
                const [targetCol, targetRow] = target;
5✔
3352

5✔
3353
                const editList: EditListItem[] = [];
5✔
3354
                do {
5✔
3355
                    if (onPaste === undefined) {
5✔
3356
                        const cellData = getMangledCellContent(target);
2✔
3357
                        const rawValue = text ?? data?.map(r => r.map(cb => cb.rawValue).join("\t")).join("\t") ?? "";
2!
3358
                        const newVal = pasteToCell(cellData, target, rawValue, undefined);
2✔
3359
                        if (newVal !== undefined) {
2✔
3360
                            editList.push(newVal);
1✔
3361
                        }
1✔
3362
                        break;
2✔
3363
                    }
2✔
3364

3✔
3365
                    if (data === undefined) {
3✔
3366
                        if (text === undefined) return;
3!
3367
                        data = unquote(text);
3✔
3368
                    }
3✔
3369

3✔
3370
                    if (
3✔
3371
                        onPaste === false ||
3✔
3372
                        (typeof onPaste === "function" &&
3✔
3373
                            onPaste?.(
2✔
3374
                                [target[0] - rowMarkerOffset, target[1]],
2✔
3375
                                data.map(r => r.map(cb => cb.rawValue?.toString() ?? ""))
2!
3376
                            ) !== true)
2✔
3377
                    ) {
5!
3378
                        return;
×
UNCOV
3379
                    }
✔
3380

3✔
3381
                    for (const [row, dataRow] of data.entries()) {
5✔
3382
                        if (row + targetRow >= rows) break;
21!
3383
                        for (const [col, dataItem] of dataRow.entries()) {
21✔
3384
                            const index = [col + targetCol, row + targetRow] as const;
63✔
3385
                            const [writeCol, writeRow] = index;
63✔
3386
                            if (writeCol >= mangledCols.length) continue;
63✔
3387
                            if (writeRow >= mangledRows) continue;
49!
3388
                            const cellData = getMangledCellContent(index);
49✔
3389
                            const newVal = pasteToCell(cellData, index, dataItem.rawValue, dataItem.formatted);
49✔
3390
                            if (newVal !== undefined) {
63✔
3391
                                editList.push(newVal);
35✔
3392
                            }
35✔
3393
                        }
63✔
3394
                    }
21✔
3395
                    // eslint-disable-next-line no-constant-condition
3✔
3396
                } while (false);
5✔
3397

5✔
3398
                mangledOnCellsEdited(editList);
5✔
3399

5✔
3400
                gridRef.current?.damage(
5✔
3401
                    editList.map(c => ({
5✔
3402
                        cell: c.location,
36✔
3403
                    }))
5✔
3404
                );
5✔
3405
            }
5✔
3406
        },
6✔
3407
        [
652✔
3408
            coercePasteValue,
652✔
3409
            getCellRenderer,
652✔
3410
            getMangledCellContent,
652✔
3411
            gridSelection,
652✔
3412
            keybindings.paste,
652✔
3413
            mangledCols.length,
652✔
3414
            mangledOnCellsEdited,
652✔
3415
            mangledRows,
652✔
3416
            onPaste,
652✔
3417
            rowMarkerOffset,
652✔
3418
            rows,
652✔
3419
        ]
652✔
3420
    );
652✔
3421

652✔
3422
    useEventListener("paste", onPasteInternal, safeWindow, false, true);
652✔
3423

652✔
3424
    // While this function is async, we deeply prefer not to await if we don't have to. This will lead to unpacking
652✔
3425
    // promises in rather awkward ways when possible to avoid awaiting. We have to use fallback copy mechanisms when
652✔
3426
    // an await has happened.
652✔
3427
    const onCopy = React.useCallback(
652✔
3428
        async (e?: ClipboardEvent, ignoreFocus?: boolean) => {
652✔
3429
            if (!keybindings.copy) return;
6!
3430
            const focused =
6✔
3431
                ignoreFocus === true ||
6✔
3432
                scrollRef.current?.contains(document.activeElement) === true ||
5✔
3433
                canvasRef.current?.contains(document.activeElement) === true;
5✔
3434

6✔
3435
            const selectedColumns = gridSelection.columns;
6✔
3436
            const selectedRows = gridSelection.rows;
6✔
3437

6✔
3438
            const copyToClipboardWithHeaders = (
6✔
3439
                cells: readonly (readonly GridCell[])[],
5✔
3440
                columnIndexes: readonly number[]
5✔
3441
            ) => {
5✔
3442
                if (!copyHeaders) {
5✔
3443
                    copyToClipboard(cells, columnIndexes, e);
5✔
3444
                } else {
5!
3445
                    const headers = columnIndexes.map(index => ({
×
UNCOV
3446
                        kind: GridCellKind.Text,
×
UNCOV
3447
                        data: columnsIn[index].title,
×
UNCOV
3448
                        displayData: columnsIn[index].title,
×
UNCOV
3449
                        allowOverlay: false,
×
UNCOV
3450
                    })) as GridCell[];
×
3451
                    copyToClipboard([headers, ...cells], columnIndexes, e);
×
UNCOV
3452
                }
×
3453
            };
5✔
3454

6✔
3455
            if (focused && getCellsForSelection !== undefined) {
6✔
3456
                if (gridSelection.current !== undefined) {
6✔
3457
                    let thunk = getCellsForSelection(gridSelection.current.range, abortControllerRef.current.signal);
3✔
3458
                    if (typeof thunk !== "object") {
3!
3459
                        thunk = await thunk();
×
UNCOV
3460
                    }
×
3461
                    copyToClipboardWithHeaders(
3✔
3462
                        thunk,
3✔
3463
                        range(
3✔
3464
                            gridSelection.current.range.x - rowMarkerOffset,
3✔
3465
                            gridSelection.current.range.x + gridSelection.current.range.width - rowMarkerOffset
3✔
3466
                        )
3✔
3467
                    );
3✔
3468
                } else if (selectedRows !== undefined && selectedRows.length > 0) {
3✔
3469
                    const toCopy = [...selectedRows];
1✔
3470
                    const cells = toCopy.map(rowIndex => {
1✔
3471
                        const thunk = getCellsForSelection(
1✔
3472
                            {
1✔
3473
                                x: rowMarkerOffset,
1✔
3474
                                y: rowIndex,
1✔
3475
                                width: columnsIn.length,
1✔
3476
                                height: 1,
1✔
3477
                            },
1✔
3478
                            abortControllerRef.current.signal
1✔
3479
                        );
1✔
3480
                        if (typeof thunk === "object") {
1✔
3481
                            return thunk[0];
1✔
3482
                        }
1!
3483
                        return thunk().then(v => v[0]);
×
3484
                    });
1✔
3485
                    if (cells.some(x => x instanceof Promise)) {
1!
3486
                        const settled = await Promise.all(cells);
×
3487
                        copyToClipboardWithHeaders(settled, range(columnsIn.length));
×
3488
                    } else {
1✔
3489
                        copyToClipboardWithHeaders(cells as (readonly GridCell[])[], range(columnsIn.length));
1✔
3490
                    }
1✔
3491
                } else if (selectedColumns.length > 0) {
3✔
3492
                    const results: (readonly (readonly GridCell[])[])[] = [];
1✔
3493
                    const cols: number[] = [];
1✔
3494
                    for (const col of selectedColumns) {
1✔
3495
                        let thunk = getCellsForSelection(
3✔
3496
                            {
3✔
3497
                                x: col,
3✔
3498
                                y: 0,
3✔
3499
                                width: 1,
3✔
3500
                                height: rows,
3✔
3501
                            },
3✔
3502
                            abortControllerRef.current.signal
3✔
3503
                        );
3✔
3504
                        if (typeof thunk !== "object") {
3!
3505
                            thunk = await thunk();
×
UNCOV
3506
                        }
×
3507
                        results.push(thunk);
3✔
3508
                        cols.push(col - rowMarkerOffset);
3✔
3509
                    }
3✔
3510
                    if (results.length === 1) {
1!
3511
                        copyToClipboardWithHeaders(results[0], cols);
×
3512
                    } else {
1✔
3513
                        // FIXME: this is dumb
1✔
3514
                        const toCopy = results.reduce((pv, cv) => pv.map((row, index) => [...row, ...cv[index]]));
1✔
3515
                        copyToClipboardWithHeaders(toCopy, cols);
1✔
3516
                    }
1✔
3517
                }
1✔
3518
            }
6✔
3519
        },
6✔
3520
        [columnsIn, getCellsForSelection, gridSelection, keybindings.copy, rowMarkerOffset, rows, copyHeaders]
652✔
3521
    );
652✔
3522

652✔
3523
    useEventListener("copy", onCopy, safeWindow, false, false);
652✔
3524

652✔
3525
    const onCut = React.useCallback(
652✔
3526
        async (e?: ClipboardEvent) => {
652✔
3527
            if (!keybindings.cut) return;
1!
3528
            const focused =
1✔
3529
                scrollRef.current?.contains(document.activeElement) === true ||
1✔
3530
                canvasRef.current?.contains(document.activeElement) === true;
1✔
3531

1✔
3532
            if (!focused) return;
1!
3533
            await onCopy(e);
1✔
3534
            if (gridSelection.current !== undefined) {
1✔
3535
                let effectiveSelection: GridSelection = {
1✔
3536
                    current: {
1✔
3537
                        cell: gridSelection.current.cell,
1✔
3538
                        range: gridSelection.current.range,
1✔
3539
                        rangeStack: [],
1✔
3540
                    },
1✔
3541
                    rows: CompactSelection.empty(),
1✔
3542
                    columns: CompactSelection.empty(),
1✔
3543
                };
1✔
3544
                const onDeleteResult = onDelete?.(effectiveSelection);
1✔
3545
                if (onDeleteResult === false) return;
1!
3546
                effectiveSelection = onDeleteResult === true ? effectiveSelection : onDeleteResult;
1!
3547
                if (effectiveSelection.current === undefined) return;
1!
3548
                deleteRange(effectiveSelection.current.range);
1✔
3549
            }
1✔
3550
        },
1✔
3551
        [deleteRange, gridSelection, keybindings.cut, onCopy, onDelete]
652✔
3552
    );
652✔
3553

652✔
3554
    useEventListener("cut", onCut, safeWindow, false, false);
652✔
3555

652✔
3556
    const onSearchResultsChanged = React.useCallback(
652✔
3557
        (results: readonly Item[], navIndex: number) => {
652✔
3558
            if (onSearchResultsChangedIn !== undefined) {
7!
UNCOV
3559
                if (rowMarkerOffset !== 0) {
×
3560
                    results = results.map(item => [item[0] - rowMarkerOffset, item[1]]);
×
UNCOV
3561
                }
×
3562
                onSearchResultsChangedIn(results, navIndex);
×
3563
                return;
×
UNCOV
3564
            }
×
3565
            if (results.length === 0 || navIndex === -1) return;
7✔
3566

2✔
3567
            const [col, row] = results[navIndex];
2✔
3568
            if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) {
7!
3569
                return;
×
UNCOV
3570
            }
✔
3571
            lastSent.current = [col, row];
2✔
3572
            updateSelectedCell(col, row, false, false);
2✔
3573
        },
7✔
3574
        [onSearchResultsChangedIn, rowMarkerOffset, updateSelectedCell]
652✔
3575
    );
652✔
3576

652✔
3577
    // this effects purpose in life is to scroll the newly selected cell into view when and ONLY when that cell
652✔
3578
    // is from an external gridSelection change. Also note we want the unmangled out selection because scrollTo
652✔
3579
    // expects unmangled indexes
652✔
3580
    const [outCol, outRow] = gridSelectionOuter?.current?.cell ?? [];
652✔
3581
    const scrollToRef = React.useRef(scrollTo);
652✔
3582
    scrollToRef.current = scrollTo;
652✔
3583
    React.useLayoutEffect(() => {
652✔
3584
        if (
207✔
3585
            !hasJustScrolled.current &&
207✔
3586
            outCol !== undefined &&
207✔
3587
            outRow !== undefined &&
77✔
3588
            (outCol !== expectedExternalGridSelection.current?.current?.cell[0] ||
77✔
3589
                outRow !== expectedExternalGridSelection.current?.current?.cell[1])
77✔
3590
        ) {
207!
3591
            scrollToRef.current(outCol, outRow);
×
UNCOV
3592
        }
×
3593
        hasJustScrolled.current = false; //only allow skipping a single scroll
207✔
3594
    }, [outCol, outRow]);
652✔
3595

652✔
3596
    const selectionOutOfBounds =
652✔
3597
        gridSelection.current !== undefined &&
652✔
3598
        (gridSelection.current.cell[0] >= mangledCols.length || gridSelection.current.cell[1] >= mangledRows);
303✔
3599
    React.useLayoutEffect(() => {
652✔
3600
        if (selectionOutOfBounds) {
136✔
3601
            setGridSelection(emptyGridSelection, false);
1✔
3602
        }
1✔
3603
    }, [selectionOutOfBounds, setGridSelection]);
652✔
3604

652✔
3605
    const disabledRows = React.useMemo(() => {
652✔
3606
        if (showTrailingBlankRow === true && trailingRowOptions?.tint === true) {
135✔
3607
            return CompactSelection.fromSingleSelection(mangledRows - 1);
132✔
3608
        }
132✔
3609
        return CompactSelection.empty();
3✔
3610
    }, [mangledRows, showTrailingBlankRow, trailingRowOptions?.tint]);
652✔
3611

652✔
3612
    const mangledVerticalBorder = React.useCallback(
652✔
3613
        (col: number) => {
652✔
3614
            return typeof verticalBorder === "boolean"
7,354!
UNCOV
3615
                ? verticalBorder
×
3616
                : verticalBorder?.(col - rowMarkerOffset) ?? true;
7,354!
3617
        },
7,354✔
3618
        [rowMarkerOffset, verticalBorder]
652✔
3619
    );
652✔
3620

652✔
3621
    const renameGroupNode = React.useMemo(() => {
652✔
3622
        if (renameGroup === undefined || canvasRef.current === null) return null;
136✔
3623
        const { bounds, group } = renameGroup;
2✔
3624
        const canvasBounds = canvasRef.current.getBoundingClientRect();
2✔
3625
        return (
2✔
3626
            <GroupRename
2✔
3627
                bounds={bounds}
2✔
3628
                group={group}
2✔
3629
                canvasBounds={canvasBounds}
2✔
3630
                onClose={() => setRenameGroup(undefined)}
2✔
3631
                onFinish={newVal => {
2✔
3632
                    setRenameGroup(undefined);
1✔
3633
                    onGroupHeaderRenamed?.(group, newVal);
1✔
3634
                }}
1✔
3635
            />
2✔
3636
        );
136✔
3637
    }, [onGroupHeaderRenamed, renameGroup]);
652✔
3638

652✔
3639
    const mangledFreezeColumns = Math.min(mangledCols.length, freezeColumns + (hasRowMarkers ? 1 : 0));
652✔
3640

652✔
3641
    React.useImperativeHandle(
652✔
3642
        forwardedRef,
652✔
3643
        () => ({
652✔
3644
            appendRow: (col: number, openOverlay?: boolean) => appendRow(col + rowMarkerOffset, openOverlay),
27✔
3645
            updateCells: damageList => {
27✔
3646
                if (rowMarkerOffset !== 0) {
2✔
3647
                    damageList = damageList.map(x => ({ cell: [x.cell[0] + rowMarkerOffset, x.cell[1]] }));
1✔
3648
                }
1✔
3649
                return gridRef.current?.damage(damageList);
2✔
3650
            },
2✔
3651
            getBounds: (col, row) => {
27✔
3652
                if (canvasRef?.current === null || scrollRef?.current === null) {
1!
NEW
3653
                    return undefined;
×
UNCOV
3654
                }
×
3655

1✔
3656
                if (col === undefined && row === undefined) {
1!
UNCOV
3657
                    // Return the bounds of the entire scroll area:
×
NEW
3658
                    const rect = canvasRef.current.getBoundingClientRect();
×
NEW
3659
                    const scale = rect.width / scrollRef.current.clientWidth;
×
NEW
3660
                    return {
×
NEW
3661
                        x: rect.x - scrollRef.current.scrollLeft * scale,
×
NEW
3662
                        y: rect.y - scrollRef.current.scrollTop * scale,
×
NEW
3663
                        width: scrollRef.current.scrollWidth * scale,
×
NEW
3664
                        height: scrollRef.current.scrollHeight * scale,
×
NEW
3665
                    };
×
3666
                }
×
3667
                return gridRef.current?.getBounds((col ?? 0) + rowMarkerOffset, row);
1!
3668
            },
1✔
3669
            focus: () => gridRef.current?.focus(),
27✔
3670
            emit: async e => {
27✔
3671
                switch (e) {
5✔
3672
                    case "delete":
5✔
3673
                        onKeyDown({
1✔
3674
                            bounds: undefined,
1✔
3675
                            cancel: () => undefined,
1✔
3676
                            stopPropagation: () => undefined,
1✔
3677
                            preventDefault: () => undefined,
1✔
3678
                            ctrlKey: false,
1✔
3679
                            key: "Delete",
1✔
3680
                            keyCode: 46,
1✔
3681
                            metaKey: false,
1✔
3682
                            shiftKey: false,
1✔
3683
                            altKey: false,
1✔
3684
                            rawEvent: undefined,
1✔
3685
                            location: undefined,
1✔
3686
                        });
1✔
3687
                        break;
1✔
3688
                    case "fill-right":
5✔
3689
                        onKeyDown({
1✔
3690
                            bounds: undefined,
1✔
3691
                            cancel: () => undefined,
1✔
3692
                            stopPropagation: () => undefined,
1✔
3693
                            preventDefault: () => undefined,
1✔
3694
                            ctrlKey: true,
1✔
3695
                            key: "r",
1✔
3696
                            keyCode: 82,
1✔
3697
                            metaKey: false,
1✔
3698
                            shiftKey: false,
1✔
3699
                            altKey: false,
1✔
3700
                            rawEvent: undefined,
1✔
3701
                            location: undefined,
1✔
3702
                        });
1✔
3703
                        break;
1✔
3704
                    case "fill-down":
5✔
3705
                        onKeyDown({
1✔
3706
                            bounds: undefined,
1✔
3707
                            cancel: () => undefined,
1✔
3708
                            stopPropagation: () => undefined,
1✔
3709
                            preventDefault: () => undefined,
1✔
3710
                            ctrlKey: true,
1✔
3711
                            key: "d",
1✔
3712
                            keyCode: 68,
1✔
3713
                            metaKey: false,
1✔
3714
                            shiftKey: false,
1✔
3715
                            altKey: false,
1✔
3716
                            rawEvent: undefined,
1✔
3717
                            location: undefined,
1✔
3718
                        });
1✔
3719
                        break;
1✔
3720
                    case "copy":
5✔
3721
                        await onCopy(undefined, true);
1✔
3722
                        break;
1✔
3723
                    case "paste":
5✔
3724
                        await onPasteInternal();
1✔
3725
                        break;
1✔
3726
                }
5✔
3727
            },
5✔
3728
            scrollTo,
27✔
3729
            remeasureColumns: cols => {
27✔
3730
                for (const col of cols) {
1✔
3731
                    void normalSizeColumn(col + rowMarkerOffset, true);
1✔
3732
                }
1✔
3733
            },
1✔
3734
        }),
27✔
3735
        [appendRow, normalSizeColumn, onCopy, onKeyDown, onPasteInternal, rowMarkerOffset, scrollTo]
652✔
3736
    );
652✔
3737

652✔
3738
    const [selCol, selRow] = currentCell ?? [];
652✔
3739
    const onCellFocused = React.useCallback(
652✔
3740
        (cell: Item) => {
652✔
3741
            const [col, row] = cell;
24✔
3742

24✔
3743
            if (row === -1) {
24!
UNCOV
3744
                if (columnSelect !== "none") {
×
3745
                    setSelectedColumns(CompactSelection.fromSingleSelection(col), undefined, false);
×
3746
                    focus();
×
UNCOV
3747
                }
×
3748
                return;
×
UNCOV
3749
            }
×
3750

24✔
3751
            if (selCol === col && selRow === row) return;
24✔
3752
            setCurrent(
1✔
3753
                {
1✔
3754
                    cell,
1✔
3755
                    range: { x: col, y: row, width: 1, height: 1 },
1✔
3756
                },
1✔
3757
                true,
1✔
3758
                false,
1✔
3759
                "keyboard-nav"
1✔
3760
            );
1✔
3761
            scrollTo(col, row);
1✔
3762
        },
24✔
3763
        [columnSelect, focus, scrollTo, selCol, selRow, setCurrent, setSelectedColumns]
652✔
3764
    );
652✔
3765

652✔
3766
    const [isFocused, setIsFocused] = React.useState(false);
652✔
3767
    const setIsFocusedDebounced = React.useRef(
652✔
3768
        debounce((val: boolean) => {
652✔
3769
            setIsFocused(val);
48✔
3770
        }, 5)
652✔
3771
    );
652✔
3772

652✔
3773
    const onCanvasFocused = React.useCallback(() => {
652✔
3774
        setIsFocusedDebounced.current(true);
58✔
3775

58✔
3776
        // check for mouse state, don't do anything if the user is clicked to focus.
58✔
3777
        if (
58✔
3778
            gridSelection.current === undefined &&
58✔
3779
            gridSelection.columns.length === 0 &&
6✔
3780
            gridSelection.rows.length === 0 &&
5✔
3781
            mouseState === undefined
5✔
3782
        ) {
58✔
3783
            setCurrent(
5✔
3784
                {
5✔
3785
                    cell: [rowMarkerOffset, cellYOffset],
5✔
3786
                    range: {
5✔
3787
                        x: rowMarkerOffset,
5✔
3788
                        y: cellYOffset,
5✔
3789
                        width: 1,
5✔
3790
                        height: 1,
5✔
3791
                    },
5✔
3792
                },
5✔
3793
                true,
5✔
3794
                false,
5✔
3795
                "keyboard-select"
5✔
3796
            );
5✔
3797
        }
5✔
3798
    }, [cellYOffset, gridSelection, mouseState, rowMarkerOffset, setCurrent]);
652✔
3799

652✔
3800
    const onFocusOut = React.useCallback(() => {
652✔
3801
        setIsFocusedDebounced.current(false);
28✔
3802
    }, []);
652✔
3803

652✔
3804
    const [idealWidth, idealHeight] = React.useMemo(() => {
652✔
3805
        let h: number;
148✔
3806
        const scrollbarWidth = experimental?.scrollbarWidthOverride ?? getScrollBarWidth();
148✔
3807
        const rowsCountWithTrailingRow = rows + (showTrailingBlankRow ? 1 : 0);
148!
3808
        if (typeof rowHeight === "number") {
148✔
3809
            h = totalHeaderHeight + rowsCountWithTrailingRow * rowHeight;
147✔
3810
        } else {
148✔
3811
            let avg = 0;
1✔
3812
            const toAverage = Math.min(rowsCountWithTrailingRow, 10);
1✔
3813
            for (let i = 0; i < toAverage; i++) {
1✔
3814
                avg += rowHeight(i);
10✔
3815
            }
10✔
3816
            avg = Math.floor(avg / toAverage);
1✔
3817

1✔
3818
            h = totalHeaderHeight + rowsCountWithTrailingRow * avg;
1✔
3819
        }
1✔
3820
        h += scrollbarWidth;
148✔
3821

148✔
3822
        const w = mangledCols.reduce((acc, x) => x.width + acc, 0) + scrollbarWidth;
148✔
3823

148✔
3824
        // We need to set a reasonable cap here as some browsers will just ignore huge values
148✔
3825
        // rather than treat them as huge values.
148✔
3826
        return [`${Math.min(100_000, w)}px`, `${Math.min(100_000, h)}px`];
148✔
3827
    }, [mangledCols, experimental?.scrollbarWidthOverride, rowHeight, rows, showTrailingBlankRow, totalHeaderHeight]);
652✔
3828

652✔
3829
    return (
652✔
3830
        <ThemeContext.Provider value={mergedTheme}>
652✔
3831
            <DataEditorContainer
652✔
3832
                style={makeCSSStyle(mergedTheme)}
652✔
3833
                className={className}
652✔
3834
                inWidth={width ?? idealWidth}
652✔
3835
                inHeight={height ?? idealHeight}>
652✔
3836
                <DataGridSearch
652✔
3837
                    fillHandle={fillHandle}
652✔
3838
                    drawFocusRing={drawFocusRing}
652✔
3839
                    experimental={experimental}
652✔
3840
                    fixedShadowX={fixedShadowX}
652✔
3841
                    fixedShadowY={fixedShadowY}
652✔
3842
                    getRowThemeOverride={getRowThemeOverride}
652✔
3843
                    headerIcons={headerIcons}
652✔
3844
                    imageWindowLoader={imageWindowLoader}
652✔
3845
                    initialSize={initialSize}
652✔
3846
                    isDraggable={isDraggable}
652✔
3847
                    onDragLeave={onDragLeave}
652✔
3848
                    onRowMoved={onRowMoved}
652✔
3849
                    overscrollX={overscrollX}
652✔
3850
                    overscrollY={overscrollY}
652✔
3851
                    preventDiagonalScrolling={preventDiagonalScrolling}
652✔
3852
                    rightElement={rightElement}
652✔
3853
                    rightElementProps={rightElementProps}
652✔
3854
                    smoothScrollX={smoothScrollX}
652✔
3855
                    smoothScrollY={smoothScrollY}
652✔
3856
                    className={className}
652✔
3857
                    enableGroups={enableGroups}
652✔
3858
                    onCanvasFocused={onCanvasFocused}
652✔
3859
                    onCanvasBlur={onFocusOut}
652✔
3860
                    canvasRef={canvasRef}
652✔
3861
                    onContextMenu={onContextMenu}
652✔
3862
                    theme={mergedTheme}
652✔
3863
                    cellXOffset={cellXOffset}
652✔
3864
                    cellYOffset={cellYOffset}
652✔
3865
                    accessibilityHeight={visibleRegion.height}
652✔
3866
                    onDragEnd={onDragEnd}
652✔
3867
                    columns={mangledCols}
652✔
3868
                    nonGrowWidth={nonGrowWidth}
652✔
3869
                    drawHeader={drawHeader}
652✔
3870
                    onColumnProposeMove={onColumnProposeMove}
652✔
3871
                    drawCell={drawCell}
652✔
3872
                    disabledRows={disabledRows}
652✔
3873
                    freezeColumns={mangledFreezeColumns}
652✔
3874
                    lockColumns={rowMarkerOffset}
652✔
3875
                    firstColAccessible={rowMarkerOffset === 0}
652✔
3876
                    getCellContent={getMangledCellContent}
652✔
3877
                    minColumnWidth={minColumnWidth}
652✔
3878
                    maxColumnWidth={maxColumnWidth}
652✔
3879
                    searchInputRef={searchInputRef}
652✔
3880
                    showSearch={showSearch}
652✔
3881
                    onSearchClose={onSearchClose}
652✔
3882
                    highlightRegions={highlightRegions}
652✔
3883
                    getCellsForSelection={getCellsForSelection}
652✔
3884
                    getGroupDetails={mangledGetGroupDetails}
652✔
3885
                    headerHeight={headerHeight}
652✔
3886
                    isFocused={isFocused}
652✔
3887
                    groupHeaderHeight={enableGroups ? groupHeaderHeight : 0}
652✔
3888
                    trailingRowType={
652✔
3889
                        !showTrailingBlankRow ? "none" : trailingRowOptions?.sticky === true ? "sticky" : "appended"
652!
3890
                    }
652✔
3891
                    onColumnResize={onColumnResize}
652✔
3892
                    onColumnResizeEnd={onColumnResizeEnd}
652✔
3893
                    onColumnResizeStart={onColumnResizeStart}
652✔
3894
                    onCellFocused={onCellFocused}
652✔
3895
                    onColumnMoved={onColumnMovedImpl}
652✔
3896
                    onDragStart={onDragStartImpl}
652✔
3897
                    onHeaderMenuClick={onHeaderMenuClickInner}
652✔
3898
                    onItemHovered={onItemHoveredImpl}
652✔
3899
                    isFilling={mouseState?.fillHandle === true}
652✔
3900
                    onMouseMove={onMouseMoveImpl}
652✔
3901
                    onKeyDown={onKeyDown}
652✔
3902
                    onKeyUp={onKeyUpIn}
652✔
3903
                    onMouseDown={onMouseDown}
652✔
3904
                    onMouseUp={onMouseUp}
652✔
3905
                    onDragOverCell={onDragOverCell}
652✔
3906
                    onDrop={onDrop}
652✔
3907
                    onSearchResultsChanged={onSearchResultsChanged}
652✔
3908
                    onVisibleRegionChanged={onVisibleRegionChangedImpl}
652✔
3909
                    clientSize={clientSize}
652✔
3910
                    rowHeight={rowHeight}
652✔
3911
                    searchResults={searchResults}
652✔
3912
                    searchValue={searchValue}
652✔
3913
                    onSearchValueChange={onSearchValueChange}
652✔
3914
                    rows={mangledRows}
652✔
3915
                    scrollRef={scrollRef}
652✔
3916
                    selection={gridSelection}
652✔
3917
                    translateX={visibleRegion.tx}
652✔
3918
                    translateY={visibleRegion.ty}
652✔
3919
                    verticalBorder={mangledVerticalBorder}
652✔
3920
                    gridRef={gridRef}
652✔
3921
                    getCellRenderer={getCellRenderer}
652✔
3922
                />
652✔
3923
                {renameGroupNode}
652✔
3924
                {overlay !== undefined && (
652✔
3925
                    <React.Suspense fallback={null}>
27✔
3926
                        <DataGridOverlayEditor
27✔
3927
                            {...overlay}
27✔
3928
                            validateCell={validateCell}
27✔
3929
                            id={overlayID}
27✔
3930
                            getCellRenderer={getCellRenderer}
27✔
3931
                            className={experimental?.isSubGrid === true ? "click-outside-ignore" : undefined}
27!
3932
                            provideEditor={provideEditor}
27✔
3933
                            imageEditorOverride={imageEditorOverride}
27✔
3934
                            onFinishEditing={onFinishEditing}
27✔
3935
                            markdownDivCreateNode={markdownDivCreateNode}
27✔
3936
                            isOutsideClick={isOutsideClick}
27✔
3937
                        />
27✔
3938
                    </React.Suspense>
27✔
3939
                )}
652✔
3940
            </DataEditorContainer>
652✔
3941
        </ThemeContext.Provider>
652✔
3942
    );
652✔
3943
};
652✔
3944

1✔
3945
/**
1✔
3946
 * The primary component of Glide Data Grid.
1✔
3947
 * @category DataEditor
1✔
3948
 * @param {DataEditorProps} props
1✔
3949
 */
1✔
3950
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