/
data-editor.tsx
3967 lines (3648 loc) 路 154 KB
/
data-editor.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable sonarjs/no-duplicate-string */
import * as React from "react";
import { assert, assertNever, maybe } from "../common/support.js";
import clamp from "lodash/clamp.js";
import uniq from "lodash/uniq.js";
import flatten from "lodash/flatten.js";
import range from "lodash/range.js";
import debounce from "lodash/debounce.js";
import {
type EditableGridCell,
type GridCell,
GridCellKind,
type GridSelection,
isEditableGridCell,
type Rectangle,
isReadWriteCell,
type InnerGridCell,
InnerGridCellKind,
CompactSelection,
type Slice,
isInnerOnlyCell,
type ProvideEditorCallback,
type GridColumn,
isObjectEditorCallbackResult,
type Item,
type MarkerCell,
headerCellUnheckedMarker,
headerCellCheckedMarker,
headerCellIndeterminateMarker,
type ValidatedGridCell,
type ImageEditorType,
type CustomCell,
BooleanEmpty,
BooleanIndeterminate,
type FillHandleDirection,
type EditListItem,
} from "../internal/data-grid/data-grid-types.js";
import DataGridSearch, { type DataGridSearchProps } from "../internal/data-grid-search/data-grid-search.js";
import { browserIsOSX } from "../common/browser-detect.js";
import {
getDataEditorTheme,
makeCSSStyle,
type FullTheme,
type Theme,
ThemeContext,
mergeAndRealizeTheme,
} from "../common/styles.js";
import type { DataGridRef } from "../internal/data-grid/data-grid.js";
import { getScrollBarWidth, useEventListener, useStateWithReactiveInput, whenDefined } from "../common/utils.js";
import {
isGroupEqual,
itemsAreEqual,
itemIsInRect,
gridSelectionHasItem,
getFreezeTrailingHeight,
} from "../internal/data-grid/render/data-grid-lib.js";
import { GroupRename } from "./group-rename.js";
import { measureColumn, useColumnSizer } from "./use-column-sizer.js";
import { isHotkey } from "../common/is-hotkey.js";
import { type SelectionBlending, useSelectionBehavior } from "../internal/data-grid/use-selection-behavior.js";
import { useCellsForSelection } from "./use-cells-for-selection.js";
import { unquote, expandSelection, copyToClipboard, toggleBoolean } from "./data-editor-fns.js";
import { DataEditorContainer } from "../internal/data-editor-container/data-grid-container.js";
import { useAutoscroll } from "./use-autoscroll.js";
import type { CustomRenderer, CellRenderer, InternalCellRenderer } from "../cells/cell-types.js";
import { decodeHTML, type CopyBuffer } from "./copy-paste.js";
import { useRemAdjuster } from "./use-rem-adjuster.js";
import { withAlpha } from "../internal/data-grid/color-parser.js";
import { combineRects, getClosestRect, pointInRect } from "../common/math.js";
import {
type HeaderClickedEventArgs,
type GroupHeaderClickedEventArgs,
type CellClickedEventArgs,
type FillPatternEventArgs,
type GridMouseEventArgs,
groupHeaderKind,
outOfBoundsKind,
type GridMouseCellEventArgs,
headerKind,
type GridDragEventArgs,
mouseEventArgsAreEqual,
type GridKeyEventArgs,
} from "../internal/data-grid/event-args.js";
import { type Keybinds, useKeybindingsWithDefaults } from "./data-editor-keybindings.js";
import type { Highlight } from "../internal/data-grid/render/data-grid-render.cells.js";
const DataGridOverlayEditor = React.lazy(
async () => await import("../internal/data-grid-overlay-editor/data-grid-overlay-editor.js")
);
let idCounter = 0;
interface MouseState {
readonly previousSelection?: GridSelection;
readonly fillHandle?: boolean;
}
type Props = Partial<
Omit<
DataGridSearchProps,
| "accessibilityHeight"
| "canvasRef"
| "cellXOffset"
| "cellYOffset"
| "className"
| "clientSize"
| "columns"
| "disabledRows"
| "enableGroups"
| "firstColAccessible"
| "firstColSticky"
| "freezeColumns"
| "hasAppendRow"
| "getCellContent"
| "getCellRenderer"
| "getCellsForSelection"
| "gridRef"
| "groupHeaderHeight"
| "headerHeight"
| "isFilling"
| "isFocused"
| "imageWindowLoader"
| "lockColumns"
| "maxColumnWidth"
| "minColumnWidth"
| "nonGrowWidth"
| "onCanvasBlur"
| "onCanvasFocused"
| "onCellFocused"
| "onContextMenu"
| "onDragEnd"
| "onMouseDown"
| "onMouseMove"
| "onMouseUp"
| "onVisibleRegionChanged"
| "rowHeight"
| "rows"
| "scrollRef"
| "searchInputRef"
| "selectedColumns"
| "selection"
| "theme"
| "translateX"
| "translateY"
| "verticalBorder"
>
>;
type EmitEvents = "copy" | "paste" | "delete" | "fill-right" | "fill-down";
function getSpanStops(cells: readonly (readonly GridCell[])[]): number[] {
return uniq(
flatten(
flatten(cells)
.filter(c => c.span !== undefined)
.map(c => range((c.span?.[0] ?? 0) + 1, (c.span?.[1] ?? 0) + 1))
)
);
}
function shiftSelection(input: GridSelection, offset: number): GridSelection {
if (input === undefined || offset === 0 || (input.columns.length === 0 && input.current === undefined))
return input;
return {
current:
input.current === undefined
? undefined
: {
cell: [input.current.cell[0] + offset, input.current.cell[1]],
range: {
...input.current.range,
x: input.current.range.x + offset,
},
rangeStack: input.current.rangeStack.map(r => ({
...r,
x: r.x + offset,
})),
},
rows: input.rows,
columns: input.columns.offset(offset),
};
}
/**
* @category DataEditor
*/
export interface DataEditorProps extends Props, Pick<DataGridSearchProps, "imageWindowLoader"> {
/** Emitted whenever the user has requested the deletion of the selection.
* @group Editing
*/
readonly onDelete?: (selection: GridSelection) => boolean | GridSelection;
/** Emitted whenever a cell edit is completed.
* @group Editing
*/
readonly onCellEdited?: (cell: Item, newValue: EditableGridCell) => void;
/** Emitted whenever a cell mutation is completed and provides all edits inbound as a single batch.
* @group Editing
*/
readonly onCellsEdited?: (newValues: readonly EditListItem[]) => boolean | void;
/** Emitted whenever a row append operation is requested. Append location can be set in callback.
* @group Editing
*/
readonly onRowAppended?: () => Promise<"top" | "bottom" | number | undefined> | void;
/** Emitted when a column header should show a context menu. Usually right click.
* @group Events
*/
readonly onHeaderClicked?: (colIndex: number, event: HeaderClickedEventArgs) => void;
/** Emitted when a group header is clicked.
* @group Events
*/
readonly onGroupHeaderClicked?: (colIndex: number, event: GroupHeaderClickedEventArgs) => void;
/** Emitted whe the user wishes to rename a group.
* @group Events
*/
readonly onGroupHeaderRenamed?: (groupName: string, newVal: string) => void;
/** Emitted when a cell is clicked.
* @group Events
*/
readonly onCellClicked?: (cell: Item, event: CellClickedEventArgs) => void;
/** Emitted when a cell is activated, by pressing Enter, Space or double clicking it.
* @group Events
*/
readonly onCellActivated?: (cell: Item) => void;
/**
* Emitted whenever the user initiats a pattern fill using the fill handle. This event provides both
* a patternSource region and a fillDestination region, and can be prevented.
* @group Editing
*/
readonly onFillPattern?: (event: FillPatternEventArgs) => void;
/** Emitted when editing has finished, regardless of data changing or not.
* @group Editing
*/
readonly onFinishedEditing?: (newValue: GridCell | undefined, movement: Item) => void;
/** Emitted when a column header should show a context menu. Usually right click.
* @group Events
*/
readonly onHeaderContextMenu?: (colIndex: number, event: HeaderClickedEventArgs) => void;
/** Emitted when a group header should show a context menu. Usually right click.
* @group Events
*/
readonly onGroupHeaderContextMenu?: (colIndex: number, event: GroupHeaderClickedEventArgs) => void;
/** Emitted when a cell should show a context menu. Usually right click.
* @group Events
*/
readonly onCellContextMenu?: (cell: Item, event: CellClickedEventArgs) => void;
/** Used for validating cell values during editing.
* @group Editing
* @param cell The cell which is being validated.
* @param newValue The new value being proposed.
* @param prevValue The previous value before the edit.
* @returns A return of false indicates the value will not be accepted. A value of
* true indicates the value will be accepted. Returning a new GridCell will immediately coerce the value to match.
*/
readonly validateCell?: (
cell: Item,
newValue: EditableGridCell,
prevValue: GridCell
) => boolean | ValidatedGridCell;
/** The columns to display in the data grid.
* @group Data
*/
readonly columns: readonly GridColumn[];
/** Controls the trailing row used to insert new data into the grid.
* @group Editing
*/
readonly trailingRowOptions?: {
/** If the trailing row should be tinted */
readonly tint?: boolean;
/** A hint string displayed on hover. Usually something like "New row" */
readonly hint?: string;
/** When set to true, the trailing row is always visible. */
readonly sticky?: boolean;
/** The icon to use for the cell. Either a GridColumnIcon or a member of the passed headerIcons */
readonly addIcon?: string;
/** Overrides the column to focus when a new row is created. */
readonly targetColumn?: number | GridColumn;
};
/** Controls the height of the header row
* @defaultValue 36
* @group Style
*/
readonly headerHeight?: number;
/** Controls the header of the group header row
* @defaultValue `headerHeight`
* @group Style
*/
readonly groupHeaderHeight?: number;
/**
* The number of rows in the grid.
* @group Data
*/
readonly rows: number;
/** Determines if row markers should be automatically added to the grid.
* Interactive row markers allow the user to select a row.
*
* - "clickable-number" renders a number that can be clicked to
* select the row
* - "both" causes the row marker to show up as a number but
* reveal a checkbox when the marker is hovered.
*
* @defaultValue `none`
* @group Style
*/
readonly rowMarkers?: "checkbox" | "number" | "clickable-number" | "checkbox-visible" | "both" | "none";
/**
* Sets the width of row markers in pixels, if unset row markers will automatically size.
* @group Style
*/
readonly rowMarkerWidth?: number;
/** Changes the starting index for row markers.
* @defaultValue 1
* @group Style
*/
readonly rowMarkerStartIndex?: number;
/** Changes the theme of the row marker column
* @group Style
*/
readonly rowMarkerTheme?: Partial<Theme>;
/** Sets the width of the data grid.
* @group Style
*/
readonly width?: number | string;
/** Sets the height of the data grid.
* @group Style
*/
readonly height?: number | string;
/** Custom classname for data grid wrapper.
* @group Style
*/
readonly className?: string;
/** If set to `default`, `gridSelection` will be coerced to always include full spans.
* @group Selection
* @defaultValue `default`
*/
readonly spanRangeBehavior?: "default" | "allowPartial";
/** Controls which types of selections can exist at the same time in the grid. If selection blending is set to
* exclusive, the grid will clear other types of selections when the exclusive selection is made. By default row,
* column, and range selections are exclusive.
* @group Selection
* @defaultValue `exclusive`
* */
readonly rangeSelectionBlending?: SelectionBlending;
/** {@inheritDoc rangeSelectionBlending}
* @group Selection
*/
readonly columnSelectionBlending?: SelectionBlending;
/** {@inheritDoc rangeSelectionBlending}
* @group Selection
*/
readonly rowSelectionBlending?: SelectionBlending;
/** Controls if multi-selection is allowed. If disabled, shift/ctrl/command clicking will work as if no modifiers
* are pressed.
*
* 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
* time. The multi variants allow for multiples of the rect or cell to be selected.
* @group Selection
* @defaultValue `rect`
*/
readonly rangeSelect?: "none" | "cell" | "rect" | "multi-cell" | "multi-rect";
/** {@inheritDoc rangeSelect}
* @group Selection
* @defaultValue `multi`
*/
readonly columnSelect?: "none" | "single" | "multi";
/** {@inheritDoc rangeSelect}
* @group Selection
* @defaultValue `multi`
*/
readonly rowSelect?: "none" | "single" | "multi";
/** Sets the initial scroll Y offset.
* @see {@link scrollOffsetX}
* @group Advanced
*/
readonly scrollOffsetY?: number;
/** Sets the initial scroll X offset
* @see {@link scrollOffsetY}
* @group Advanced
*/
readonly scrollOffsetX?: number;
/** Determins the height of each row.
* @group Style
* @defaultValue 34
*/
readonly rowHeight?: DataGridSearchProps["rowHeight"];
/** Fires whenever the mouse moves
* @group Events
* @param args
*/
readonly onMouseMove?: DataGridSearchProps["onMouseMove"];
/**
* The minimum width a column can be resized to.
* @defaultValue 50
* @group Style
*/
readonly minColumnWidth?: DataGridSearchProps["minColumnWidth"];
/**
* The maximum width a column can be resized to.
* @defaultValue 500
* @group Style
*/
readonly maxColumnWidth?: DataGridSearchProps["maxColumnWidth"];
/**
* The maximum width a column can be automatically sized to.
* @defaultValue `maxColumnWidth`
* @group Style
*/
readonly maxColumnAutoWidth?: number;
/**
* Used to provide an override to the default image editor for the data grid. `provideEditor` may be a better
* choice for most people.
* @group Advanced
* */
readonly imageEditorOverride?: ImageEditorType;
/**
* If specified, it will be used to render Markdown, instead of the default Markdown renderer used by the Grid.
* You'll want to use this if you need to process your Markdown for security purposes, or if you want to use a
* renderer with different Markdown features.
* @group Advanced
*/
readonly markdownDivCreateNode?: (content: string) => DocumentFragment;
/** Callback for providing a custom editor for a cell.
* @group Editing
*/
readonly provideEditor?: ProvideEditorCallback<GridCell>;
/**
* Allows coercion of pasted values.
* @group Editing
* @param val The pasted value
* @param cell The cell being pasted into
* @returns `undefined` to accept default behavior or a `GridCell` which should be used to represent the pasted value.
*/
readonly coercePasteValue?: (val: string, cell: GridCell) => GridCell | undefined;
/**
* Emitted when the grid selection is cleared.
* @group Selection
*/
readonly onSelectionCleared?: () => void;
/**
* The current selection of the data grid. Contains all selected cells, ranges, rows, and columns.
* Used in conjunction with {@link onGridSelectionChange}
* method to implement a controlled selection.
* @group Selection
*/
readonly gridSelection?: GridSelection;
/**
* Emitted whenever the grid selection changes. Specifying
* this function will make the grid鈥檚 selection controlled, so
* so you will need to specify {@link gridSelection} as well. See
* the "Controlled Selection" example for details.
*
* @param newSelection The new gridSelection as created by user input.
* @group Selection
*/
readonly onGridSelectionChange?: (newSelection: GridSelection) => void;
/**
* Emitted whenever the visible cells change, usually due to scrolling.
* @group Events
* @param range An inclusive range of all visible cells. May include cells obscured by UI elements such
* as headers.
* @param tx The x transform of the cell region.
* @param ty The y transform of the cell region.
* @param extras Contains information about the selected cell and
* any visible freeze columns.
*/
readonly onVisibleRegionChanged?: (
range: Rectangle,
tx: number,
ty: number,
extras: {
/** The selected item if visible */
selected?: Item;
/** A selection of visible freeze columns
* @deprecated
*/
freezeRegion?: Rectangle;
/**
* All visible freeze regions
*/
freezeRegions?: readonly Rectangle[];
}
) => void;
/**
* The primary callback for getting cell data into the data grid.
* @group Data
* @param cell The location of the cell being requested.
* @returns A valid GridCell to be rendered by the Grid.
*/
readonly getCellContent: (cell: Item) => GridCell;
/**
* Determines if row selection requires a modifier key to enable multi-selection or not. In auto mode it adapts to
* touch or mouse environments automatically, in multi-mode it always acts as if the multi key (Ctrl) is pressed.
* @group Editing
* @defaultValue `auto`
*/
readonly rowSelectionMode?: "auto" | "multi";
/**
* Add table headers to copied data.
* @group Editing
* @defaultValue `false`
*/
readonly copyHeaders?: boolean;
/**
* Determins which keybindings are enabled.
* @group Editing
*/
readonly keybindings?: Partial<Keybinds>;
/**
* Used to fetch large amounts of cells at once. Used for copy/paste, if unset copy will not work.
*
* `getCellsForSelection` is called when the user copies a selection to the clipboard or the data editor needs to
* inspect data which may be outside the curently visible range. It must return a two-dimensional array (an array of
* rows, where each row is an array of cells) of the cells in the selection's rectangle. Note that the rectangle can
* include cells that are not currently visible.
*
* If `true` is passed instead of a callback, the data grid will internally use the `getCellContent` callback to
* provide a basic implementation of `getCellsForSelection`. This can make it easier to light up more data grid
* functionality, but may have negative side effects if your data source is not able to handle being queried for
* data outside the normal window.
*
* If `getCellsForSelection` returns a thunk, the data may be loaded asynchronously, however the data grid may be
* unable to properly react to column spans when performing range selections. Copying large amounts of data out of
* the grid will depend on the performance of the thunk as well.
* @group Data
* @param {Rectangle} selection The range of requested cells
* @param {AbortSignal} abortSignal A signal indicating the requested cells are no longer needed
* @returns A row-major collection of cells or an async thunk which returns a row-major collection.
*/
readonly getCellsForSelection?: DataGridSearchProps["getCellsForSelection"] | true;
/** The number of columns which should remain in place when scrolling horizontally. The row marker column, if
* enabled is always frozen and is not included in this count.
* @defaultValue 0
* @group Style
*/
readonly freezeColumns?: DataGridSearchProps["freezeColumns"];
/**
* Controls the drawing of the left hand vertical border of a column. If set to a boolean value it controls all
* borders.
* @defaultValue `true`
* @group Style
*/
readonly verticalBorder?: DataGridSearchProps["verticalBorder"] | boolean;
/**
* Called when data is pasted into the grid. If left undefined, the `DataEditor` will operate in a
* fallback mode and attempt to paste the text buffer into the current cell assuming the current cell is not
* readonly and can accept the data type. If `onPaste` is set to false or the function returns false, the grid will
* simply ignore paste. If `onPaste` evaluates to true the grid will attempt to split the data by tabs and newlines
* and paste into available cells.
*
* The grid will not attempt to add additional rows if more data is pasted then can fit. In that case it is
* advisable to simply return false from onPaste and handle the paste manually.
* @group Editing
*/
readonly onPaste?: ((target: Item, values: readonly (readonly string[])[]) => boolean) | boolean;
/**
* The theme used by the data grid to get all color and font information
* @group Style
*/
readonly theme?: Partial<Theme>;
readonly renderers?: readonly InternalCellRenderer<InnerGridCell>[];
/**
* An array of custom renderers which can be used to extend the data grid.
* @group Advanced
*/
readonly customRenderers?: readonly CustomRenderer<any>[];
/**
* Scales most elements in the theme to match rem scaling automatically
* @defaultValue false
*/
readonly scaleToRem?: boolean;
/**
* Custom predicate function to decide whether the click event occurred outside the grid
* Especially used when custom editor is opened with the portal and is outside the grid, but there is no possibility
* to add a class "click-outside-ignore"
* If this function is supplied and returns false, the click event is ignored
*/
readonly isOutsideClick?: (e: MouseEvent | TouchEvent) => boolean;
/**
* Controls which directions fill is allowed in.
*/
readonly allowedFillDirections?: FillHandleDirection;
/**
* Determines when a cell is considered activated and will emit the `onCellActivated` event. Generally an activated
* cell will open to edit mode.
*/
readonly cellActivationBehavior?: "double-click" | "single-click" | "second-click";
/**
* Controls if focus will trap inside the data grid when doing tab and caret navigation.
*/
readonly trapFocus?: boolean;
}
type ScrollToFn = (
col: number | { amount: number; unit: "cell" | "px" },
row: number | { amount: number; unit: "cell" | "px" },
dir?: "horizontal" | "vertical" | "both",
paddingX?: number,
paddingY?: number,
options?: {
hAlign?: "start" | "center" | "end";
vAlign?: "start" | "center" | "end";
}
) => void;
/** @category DataEditor */
export interface DataEditorRef {
/**
* Programatically appends a row.
* @param col The column index to focus in the new row.
* @returns A promise which waits for the append to complete.
*/
appendRow: (col: number, openOverlay?: boolean) => Promise<void>;
/**
* Triggers cells to redraw.
*/
updateCells: DataGridRef["damage"];
/**
* Gets the screen space bounds of the requested item.
*/
getBounds: DataGridRef["getBounds"];
/**
* Triggers the data grid to focus itself or the correct accessibility element.
*/
focus: DataGridRef["focus"];
/**
* Generic API for emitting events as if they had been triggered via user interaction.
*/
emit: (eventName: EmitEvents) => Promise<void>;
/**
* Scrolls to the desired cell or location in the grid.
*/
scrollTo: ScrollToFn;
/**
* Causes the columns in the selection to have their natural size recomputed and re-emitted as a resize event.
*/
remeasureColumns: (cols: CompactSelection) => void;
}
const loadingCell: GridCell = {
kind: GridCellKind.Loading,
allowOverlay: false,
};
const emptyGridSelection: GridSelection = {
columns: CompactSelection.empty(),
rows: CompactSelection.empty(),
current: undefined,
};
const DataEditorImpl: React.ForwardRefRenderFunction<DataEditorRef, DataEditorProps> = (p, forwardedRef) => {
const [gridSelectionInner, setGridSelectionInner] = React.useState<GridSelection>(emptyGridSelection);
const [overlay, setOverlay] = React.useState<{
target: Rectangle;
content: GridCell;
theme: FullTheme;
initialValue: string | undefined;
cell: Item;
highlight: boolean;
forceEditMode: boolean;
}>();
const searchInputRef = React.useRef<HTMLInputElement | null>(null);
const canvasRef = React.useRef<HTMLCanvasElement | null>(null);
const [mouseState, setMouseState] = React.useState<MouseState>();
const scrollRef = React.useRef<HTMLDivElement | null>(null);
const lastSent = React.useRef<[number, number]>();
const safeWindow = typeof window === "undefined" ? null : window;
const {
rowMarkers = "none",
rowMarkerWidth: rowMarkerWidthRaw,
imageEditorOverride,
getRowThemeOverride,
markdownDivCreateNode,
width,
height,
columns: columnsIn,
rows,
getCellContent,
onCellClicked,
onCellActivated,
onFillPattern,
onFinishedEditing,
coercePasteValue,
drawHeader: drawHeaderIn,
drawCell: drawCellIn,
onHeaderClicked,
onColumnProposeMove,
spanRangeBehavior = "default",
onGroupHeaderClicked,
onCellContextMenu,
className,
onHeaderContextMenu,
getCellsForSelection: getCellsForSelectionIn,
onGroupHeaderContextMenu,
onGroupHeaderRenamed,
onCellEdited,
onCellsEdited,
onSearchResultsChanged: onSearchResultsChangedIn,
searchResults,
onSearchValueChange,
searchValue,
onKeyDown: onKeyDownIn,
onKeyUp: onKeyUpIn,
keybindings: keybindingsIn,
onRowAppended,
onColumnMoved,
validateCell: validateCellIn,
highlightRegions: highlightRegionsIn,
rangeSelect = "rect",
columnSelect = "multi",
rowSelect = "multi",
rangeSelectionBlending = "exclusive",
columnSelectionBlending = "exclusive",
rowSelectionBlending = "exclusive",
onDelete: onDeleteIn,
onDragStart,
onMouseMove,
onPaste,
copyHeaders = false,
freezeColumns = 0,
cellActivationBehavior = "second-click",
rowSelectionMode = "auto",
rowMarkerStartIndex = 1,
rowMarkerTheme,
onHeaderMenuClick,
getGroupDetails,
onSearchClose: onSearchCloseIn,
onItemHovered,
onSelectionCleared,
showSearch: showSearchIn,
onVisibleRegionChanged,
gridSelection: gridSelectionOuter,
onGridSelectionChange,
minColumnWidth: minColumnWidthIn = 50,
maxColumnWidth: maxColumnWidthIn = 500,
maxColumnAutoWidth: maxColumnAutoWidthIn,
provideEditor,
trailingRowOptions,
freezeTrailingRows = 0,
allowedFillDirections = "orthogonal",
scrollOffsetX,
scrollOffsetY,
verticalBorder,
onDragOverCell,
onDrop,
onColumnResize: onColumnResizeIn,
onColumnResizeEnd: onColumnResizeEndIn,
onColumnResizeStart: onColumnResizeStartIn,
customRenderers: additionalRenderers,
fillHandle,
drawFocusRing,
experimental,
fixedShadowX,
fixedShadowY,
headerIcons,
imageWindowLoader,
initialSize,
isDraggable,
onDragLeave,
onRowMoved,
overscrollX: overscrollXIn,
overscrollY: overscrollYIn,
preventDiagonalScrolling,
rightElement,
rightElementProps,
trapFocus = false,
smoothScrollX,
smoothScrollY,
scaleToRem = false,
rowHeight: rowHeightIn = 34,
headerHeight: headerHeightIn = 36,
groupHeaderHeight: groupHeaderHeightIn = headerHeightIn,
theme: themeIn,
isOutsideClick,
renderers,
} = p;
const minColumnWidth = Math.max(minColumnWidthIn, 20);
const maxColumnWidth = Math.max(maxColumnWidthIn, minColumnWidth);
const maxColumnAutoWidth = Math.max(maxColumnAutoWidthIn ?? maxColumnWidth, minColumnWidth);
const docStyle = React.useMemo(() => {
if (typeof window === "undefined") return { fontSize: "16px" };
return window.getComputedStyle(document.documentElement);
}, []);
const remSize = React.useMemo(() => Number.parseFloat(docStyle.fontSize), [docStyle]);
const { rowHeight, headerHeight, groupHeaderHeight, theme, overscrollX, overscrollY } = useRemAdjuster({
groupHeaderHeight: groupHeaderHeightIn,
headerHeight: headerHeightIn,
overscrollX: overscrollXIn,
overscrollY: overscrollYIn,
remSize,
rowHeight: rowHeightIn,
scaleToRem,
theme: themeIn,
});
const keybindings = useKeybindingsWithDefaults(keybindingsIn);
const rowMarkerWidth = rowMarkerWidthRaw ?? (rows > 10_000 ? 48 : rows > 1000 ? 44 : rows > 100 ? 36 : 32);
const hasRowMarkers = rowMarkers !== "none";
const rowMarkerOffset = hasRowMarkers ? 1 : 0;
const showTrailingBlankRow = onRowAppended !== undefined;
const lastRowSticky = trailingRowOptions?.sticky === true;
const [showSearchInner, setShowSearchInner] = React.useState(false);
const showSearch = showSearchIn ?? showSearchInner;
const onSearchClose = React.useCallback(() => {
if (onSearchCloseIn !== undefined) {
onSearchCloseIn();
} else {
setShowSearchInner(false);
}
}, [onSearchCloseIn]);
const gridSelectionOuterMangled: GridSelection | undefined = React.useMemo((): GridSelection | undefined => {
return gridSelectionOuter === undefined ? undefined : shiftSelection(gridSelectionOuter, rowMarkerOffset);
}, [gridSelectionOuter, rowMarkerOffset]);
const gridSelection = gridSelectionOuterMangled ?? gridSelectionInner;
const abortControllerRef = React.useRef() as React.MutableRefObject<AbortController>;
if (abortControllerRef.current === undefined) abortControllerRef.current = new AbortController();
React.useEffect(() => () => abortControllerRef?.current.abort(), []);
const [getCellsForSelection, getCellsForSeletionDirect] = useCellsForSelection(
getCellsForSelectionIn,
getCellContent,
rowMarkerOffset,
abortControllerRef.current,
rows
);
const validateCell = React.useCallback<NonNullable<typeof validateCellIn>>(
(cell, newValue, prevValue) => {
if (validateCellIn === undefined) return true;
const item: Item = [cell[0] - rowMarkerOffset, cell[1]];
return validateCellIn?.(item, newValue, prevValue);
},
[rowMarkerOffset, validateCellIn]
);
const expectedExternalGridSelection = React.useRef<GridSelection | undefined>(gridSelectionOuter);
const setGridSelection = React.useCallback(
(newVal: GridSelection, expand: boolean): void => {
if (expand) {
newVal = expandSelection(
newVal,
getCellsForSelection,
rowMarkerOffset,
spanRangeBehavior,
abortControllerRef.current
);
}
if (onGridSelectionChange !== undefined) {
expectedExternalGridSelection.current = shiftSelection(newVal, -rowMarkerOffset);
onGridSelectionChange(expectedExternalGridSelection.current);
} else {
setGridSelectionInner(newVal);
}
},
[onGridSelectionChange, getCellsForSelection, rowMarkerOffset, spanRangeBehavior]
);
const onColumnResize = whenDefined(
onColumnResizeIn,
React.useCallback<NonNullable<typeof onColumnResizeIn>>(
(_, w, ind, wg) => {
onColumnResizeIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
},
[onColumnResizeIn, rowMarkerOffset, columnsIn]
)
);
const onColumnResizeEnd = whenDefined(
onColumnResizeEndIn,
React.useCallback<NonNullable<typeof onColumnResizeEndIn>>(
(_, w, ind, wg) => {
onColumnResizeEndIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
},
[onColumnResizeEndIn, rowMarkerOffset, columnsIn]
)
);
const onColumnResizeStart = whenDefined(
onColumnResizeStartIn,
React.useCallback<NonNullable<typeof onColumnResizeStartIn>>(
(_, w, ind, wg) => {
onColumnResizeStartIn?.(columnsIn[ind - rowMarkerOffset], w, ind - rowMarkerOffset, wg);
},
[onColumnResizeStartIn, rowMarkerOffset, columnsIn]
)
);
const drawHeader = whenDefined(
drawHeaderIn,
React.useCallback<NonNullable<typeof drawHeaderIn>>(
(args, draw) => {
return drawHeaderIn?.({ ...args, columnIndex: args.columnIndex - rowMarkerOffset }, draw) ?? false;
},
[drawHeaderIn, rowMarkerOffset]
)
);
const drawCell = whenDefined(
drawCellIn,
React.useCallback<NonNullable<typeof drawCellIn>>(
(args, draw) => {
return drawCellIn?.({ ...args, col: args.col - rowMarkerOffset }, draw) ?? false;
},
[drawCellIn, rowMarkerOffset]
)
);
const onDelete = React.useCallback<NonNullable<DataEditorProps["onDelete"]>>(
sel => {
if (onDeleteIn !== undefined) {
const result = onDeleteIn(shiftSelection(sel, -rowMarkerOffset));
if (typeof result === "boolean") {
return result;
}
return shiftSelection(result, rowMarkerOffset);
}
return true;
},
[onDeleteIn, rowMarkerOffset]
);
const [setCurrent, setSelectedRows, setSelectedColumns] = useSelectionBehavior(
gridSelection,
setGridSelection,
rangeSelectionBlending,
columnSelectionBlending,
rowSelectionBlending,
rangeSelect
);
const mergedTheme = React.useMemo(() => {
return mergeAndRealizeTheme(getDataEditorTheme(), theme);
}, [theme]);
const [clientSize, setClientSize] = React.useState<readonly [number, number, number]>([0, 0, 0]);
const rendererMap = React.useMemo(() => {
if (renderers === undefined) return {};
const result: Partial<Record<InnerGridCellKind | GridCellKind, InternalCellRenderer<InnerGridCell>>> = {};
for (const r of renderers) {
result[r.kind] = r;
}
return result;
}, [renderers]);
const getCellRenderer: <T extends InnerGridCell>(cell: T) => CellRenderer<T> | undefined = React.useCallback(
<T extends InnerGridCell>(cell: T) => {
if (cell.kind !== GridCellKind.Custom) {
return rendererMap[cell.kind] as unknown as CellRenderer<T>;
}
return additionalRenderers?.find(x => x.isMatch(cell)) as CellRenderer<T>;
},
[additionalRenderers, rendererMap]
);
// eslint-disable-next-line prefer-const
let { sizedColumns: columns, nonGrowWidth } = useColumnSizer(