-
Notifications
You must be signed in to change notification settings - Fork 330
/
Copy pathdata-grid.tsx
1930 lines (1742 loc) · 72 KB
/
data-grid.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
import * as React from "react";
import type { FullTheme } from "../../common/styles.js";
import {
computeBounds,
getColumnIndexForX,
getEffectiveColumns,
getRowIndexForY,
getStickyWidth,
rectBottomRight,
useMappedColumns,
} from "./render/data-grid-lib.js";
import {
GridCellKind,
type Rectangle,
type GridSelection,
type InnerGridCell,
InnerGridCellKind,
CompactSelection,
type Item,
type DrawHeaderCallback,
isReadWriteCell,
isInnerOnlyCell,
booleanCellIsEditable,
type InnerGridColumn,
type DrawCellCallback,
} from "./data-grid-types.js";
import { CellSet } from "./cell-set.js";
import { SpriteManager, type SpriteMap } from "./data-grid-sprites.js";
import { direction, getScrollBarWidth, useDebouncedMemo, useEventListener } from "../../common/utils.js";
import clamp from "lodash/clamp.js";
import makeRange from "lodash/range.js";
import { drawGrid } from "./render/data-grid-render.js";
import { type BlitData } from "./render/data-grid-render.blit.js";
import { AnimationManager, type StepCallback } from "./animation-manager.js";
import { RenderStateProvider, packColRowToNumber } from "../../common/render-state-provider.js";
import { browserIsFirefox, browserIsSafari } from "../../common/browser-detect.js";
import { type EnqueueCallback, useAnimationQueue } from "./use-animation-queue.js";
import { assert } from "../../common/support.js";
import type { CellRenderer, GetCellRendererCallback } from "../../cells/cell-types.js";
import type { DrawGridArg } from "./render/draw-grid-arg.js";
import type { ImageWindowLoader } from "./image-window-loader-interface.js";
import {
type GridMouseEventArgs,
type GridKeyEventArgs,
type GridDragEventArgs,
OutOfBoundsRegionAxis,
outOfBoundsKind,
groupHeaderKind,
headerKind,
mouseEventArgsAreEqual,
} from "./event-args.js";
import { pointInRect } from "../../common/math.js";
import {
type GroupDetailsCallback,
type GetRowThemeCallback,
type Highlight,
drawCell,
} from "./render/data-grid-render.cells.js";
import { getActionBoundsForGroup, drawHeader, computeHeaderLayout } from "./render/data-grid-render.header.js";
export interface DataGridProps {
readonly width: number;
readonly height: number;
readonly cellXOffset: number;
readonly cellYOffset: number;
readonly translateX: number | undefined;
readonly translateY: number | undefined;
readonly accessibilityHeight: number;
readonly freezeColumns: number;
readonly freezeTrailingRows: number;
readonly hasAppendRow: boolean;
readonly firstColAccessible: boolean;
/**
* Enables or disables the overlay shadow when scrolling horizontally
* @group Style
*/
readonly fixedShadowX: boolean | undefined;
/**
* Enables or disables the overlay shadow when scrolling vertical
* @group Style
*/
readonly fixedShadowY: boolean | undefined;
readonly allowResize: boolean | undefined;
readonly isResizing: boolean;
readonly resizeColumn: number | undefined;
readonly isDragging: boolean;
readonly isFilling: boolean;
readonly isFocused: boolean;
readonly columns: readonly InnerGridColumn[];
/**
* The number of rows in the grid.
* @group Data
*/
readonly rows: number;
readonly headerHeight: number;
readonly groupHeaderHeight: number;
readonly enableGroups: boolean;
readonly rowHeight: number | ((index: number) => number);
readonly canvasRef: React.MutableRefObject<HTMLCanvasElement | null> | undefined;
readonly eventTargetRef: React.MutableRefObject<HTMLDivElement | null> | undefined;
readonly getCellContent: (cell: Item, forceStrict?: boolean) => InnerGridCell;
/**
* Provides additional details about groups to extend group functionality.
* @group Data
*/
readonly getGroupDetails: GroupDetailsCallback | undefined;
/**
* Provides per row theme overrides.
* @group Style
*/
readonly getRowThemeOverride: GetRowThemeCallback | undefined;
/**
* Emitted when a header menu disclosure indicator is clicked.
* @group Events
*/
readonly onHeaderMenuClick: ((col: number, screenPosition: Rectangle) => void) | undefined;
/**
* Emitted when a header indicator icon is clicked.
* @group Events
*/
readonly onHeaderIndicatorClick: ((col: number, screenPosition: Rectangle) => void) | undefined;
readonly selection: GridSelection;
readonly prelightCells: readonly Item[] | undefined;
/**
* Highlight regions provide hints to users about relations between cells and selections.
* @group Selection
*/
readonly highlightRegions: readonly Highlight[] | undefined;
/**
* Enabled/disables the fill handle.
* @defaultValue false
* @group Editing
*/
readonly fillHandle: boolean | undefined;
readonly disabledRows: CompactSelection | undefined;
/**
* Allows passing a custom image window loader.
* @group Advanced
*/
readonly imageWindowLoader: ImageWindowLoader;
/**
* Emitted when an item is hovered.
* @group Events
*/
readonly onItemHovered: (args: GridMouseEventArgs) => void;
readonly onMouseMove: (args: GridMouseEventArgs) => void;
readonly onMouseDown: (args: GridMouseEventArgs) => void;
readonly onMouseUp: (args: GridMouseEventArgs, isOutside: boolean) => void;
readonly onContextMenu: (args: GridMouseEventArgs, preventDefault: () => void) => void;
readonly onCanvasFocused: () => void;
readonly onCanvasBlur: () => void;
readonly onCellFocused: (args: Item) => void;
readonly onMouseMoveRaw: (event: MouseEvent) => void;
/**
* Emitted when the canvas receives a key down event.
* @group Events
*/
readonly onKeyDown: (event: GridKeyEventArgs) => void;
/**
* Emitted when the canvas receives a key up event.
* @group Events
*/
readonly onKeyUp: ((event: GridKeyEventArgs) => void) | undefined;
readonly verticalBorder: (col: number) => boolean;
/**
* Determines what can be dragged using HTML drag and drop
* @defaultValue false
* @group Drag and Drop
*/
readonly isDraggable: boolean | "cell" | "header" | undefined;
/**
* If `isDraggable` is set, the grid becomes HTML draggable, and `onDragStart` will be called when dragging starts.
* You can use this to build a UI where the user can drag the Grid around.
* @group Drag and Drop
*/
readonly onDragStart: (args: GridDragEventArgs) => void;
readonly onDragEnd: () => void;
/** @group Drag and Drop */
readonly onDragOverCell: ((cell: Item, dataTransfer: DataTransfer | null) => void) | undefined;
/** @group Drag and Drop */
readonly onDragLeave: (() => void) | undefined;
/**
* Called when a HTML Drag and Drop event is ended on the data grid.
* @group Drag and Drop
*/
readonly onDrop: ((cell: Item, dataTransfer: DataTransfer | null) => void) | undefined;
/**
* Overrides the rendering of a header. The grid will call this for every header it needs to render. Header
* rendering is not as well optimized because they do not redraw as often, but very heavy drawing methods can
* negatively impact horizontal scrolling performance.
*
* It is possible to return `false` after rendering just a background and the regular foreground rendering
* will happen.
* @group Drawing
* @returns `false` if default header rendering should still happen, `true` to cancel rendering.
*/
readonly drawHeader: DrawHeaderCallback | undefined;
readonly drawCell: DrawCellCallback | undefined;
/**
* Controls the drawing of the focus ring.
* @defaultValue true
* @group Style
*/
readonly drawFocusRing: boolean;
readonly dragAndDropState:
| {
src: number;
dest: number;
}
| undefined;
/**
* Experimental features
* @group Advanced
* @experimental
*/
readonly experimental:
| {
readonly disableAccessibilityTree?: boolean;
readonly disableMinimumCellWidth?: boolean;
readonly paddingRight?: number;
readonly paddingBottom?: number;
readonly enableFirefoxRescaling?: boolean;
readonly enableSafariRescaling?: boolean;
readonly kineticScrollPerfHack?: boolean;
readonly isSubGrid?: boolean;
readonly strict?: boolean;
readonly scrollbarWidthOverride?: number;
readonly hyperWrapping?: boolean;
readonly renderStrategy?: "single-buffer" | "double-buffer" | "direct";
}
| undefined;
/**
* Additional header icons for use by `GridColumn`.
*
* Providing custom header icons to the data grid must be done with a somewhat non-standard mechanism to allow
* theming and scaling. The `headerIcons` property takes a dictionary which maps icon names to functions which can
* take a foreground and background color and returns back a string representation of an svg. The svg should contain
* a header similar to this `<svg width="20" height="20" fill="none" xmlns="http://www.w3.org/2000/svg">` and
* interpolate the fg/bg colors into the string.
*
* We recognize this process is not fantastic from a graphics workflow standpoint, improvements are very welcome
* here.
*
* @group Style
*/
readonly headerIcons: SpriteMap | undefined;
/** Controls smooth scrolling in the data grid. If smooth scrolling is not enabled the grid will always be cell
* aligned.
* @defaultValue `false`
* @group Style
*/
readonly smoothScrollX: boolean | undefined;
/** Controls smooth scrolling in the data grid. If smooth scrolling is not enabled the grid will always be cell
* aligned.
* @defaultValue `false`
* @group Style
*/
readonly smoothScrollY: boolean | undefined;
readonly theme: FullTheme;
readonly getCellRenderer: <T extends InnerGridCell>(cell: T) => CellRenderer<T> | undefined;
/**
* Controls the resize indicator behavior.
*
* - `full` will show the resize indicator on the full height.
* - `header` will show the resize indicator only on the header.
* - `none` will not show the resize indicator.
*
* @defaultValue "full"
* @group Style
*/
readonly resizeIndicator: "full" | "header" | "none" | undefined;
}
type DamageUpdateList = readonly {
cell: Item;
// newValue: GridCell,
}[];
const fillHandleClickSize = 6;
export interface DataGridRef {
focus: () => void;
getBounds: (col?: number, row?: number) => Rectangle | undefined;
damage: (cells: DamageUpdateList) => void;
}
const getRowData = (cell: InnerGridCell, getCellRenderer?: GetCellRendererCallback) => {
if (cell.kind === GridCellKind.Custom) return cell.copyData;
const r = getCellRenderer?.(cell);
return r?.getAccessibilityString(cell) ?? "";
};
const DataGrid: React.ForwardRefRenderFunction<DataGridRef, DataGridProps> = (p, forwardedRef) => {
const {
width,
height,
accessibilityHeight,
columns,
cellXOffset: cellXOffsetReal,
cellYOffset,
headerHeight,
fillHandle = false,
groupHeaderHeight,
rowHeight,
rows,
getCellContent,
getRowThemeOverride,
onHeaderMenuClick,
onHeaderIndicatorClick,
enableGroups,
isFilling,
onCanvasFocused,
onCanvasBlur,
isFocused,
selection,
freezeColumns,
onContextMenu,
freezeTrailingRows,
fixedShadowX = true,
fixedShadowY = true,
drawFocusRing,
onMouseDown,
onMouseUp,
onMouseMoveRaw,
onMouseMove,
onItemHovered,
dragAndDropState,
firstColAccessible,
onKeyDown,
onKeyUp,
highlightRegions,
canvasRef,
onDragStart,
onDragEnd,
eventTargetRef,
isResizing,
resizeColumn: resizeCol,
isDragging,
isDraggable = false,
allowResize,
disabledRows,
hasAppendRow,
getGroupDetails,
theme,
prelightCells,
headerIcons,
verticalBorder,
drawCell: drawCellCallback,
drawHeader: drawHeaderCallback,
onCellFocused,
onDragOverCell,
onDrop,
onDragLeave,
imageWindowLoader,
smoothScrollX = false,
smoothScrollY = false,
experimental,
getCellRenderer,
resizeIndicator = "full",
} = p;
const translateX = p.translateX ?? 0;
const translateY = p.translateY ?? 0;
const cellXOffset = Math.max(freezeColumns, Math.min(columns.length - 1, cellXOffsetReal));
const ref = React.useRef<HTMLCanvasElement | null>(null);
const windowEventTargetRef = React.useRef<Document | Window>(window);
const windowEventTarget = windowEventTargetRef.current;
const imageLoader = imageWindowLoader;
const damageRegion = React.useRef<CellSet | undefined>();
const [scrolling, setScrolling] = React.useState<boolean>(false);
const hoverValues = React.useRef<readonly { item: Item; hoverAmount: number }[]>([]);
const lastBlitData = React.useRef<BlitData | undefined>();
const [hoveredItemInfo, setHoveredItemInfo] = React.useState<[Item, readonly [number, number]] | undefined>();
const [hoveredOnEdge, setHoveredOnEdge] = React.useState<boolean>();
const overlayRef = React.useRef<HTMLCanvasElement | null>(null);
const [drawCursorOverride, setDrawCursorOverride] = React.useState<React.CSSProperties["cursor"] | undefined>();
const [lastWasTouch, setLastWasTouch] = React.useState(false);
const lastWasTouchRef = React.useRef(lastWasTouch);
lastWasTouchRef.current = lastWasTouch;
const spriteManager = React.useMemo(
() =>
new SpriteManager(headerIcons, () => {
lastArgsRef.current = undefined;
lastDrawRef.current();
}),
[headerIcons]
);
const totalHeaderHeight = enableGroups ? groupHeaderHeight + headerHeight : headerHeight;
const scrollingStopRef = React.useRef(-1);
const enableFirefoxRescaling = (experimental?.enableFirefoxRescaling ?? false) && browserIsFirefox.value;
const enableSafariRescaling = (experimental?.enableSafariRescaling ?? false) && browserIsSafari.value;
React.useLayoutEffect(() => {
if (window.devicePixelRatio === 1 || (!enableFirefoxRescaling && !enableSafariRescaling)) return;
// We don't want to go into scroll mode for a single repaint
if (scrollingStopRef.current !== -1) {
setScrolling(true);
}
window.clearTimeout(scrollingStopRef.current);
scrollingStopRef.current = window.setTimeout(() => {
setScrolling(false);
scrollingStopRef.current = -1;
}, 200);
}, [cellYOffset, cellXOffset, translateX, translateY, enableFirefoxRescaling, enableSafariRescaling]);
const mappedColumns = useMappedColumns(columns, freezeColumns);
const stickyX = fixedShadowX ? getStickyWidth(mappedColumns, dragAndDropState) : 0;
// row: -1 === columnHeader, -2 === groupHeader
const getBoundsForItem = React.useCallback(
(canvas: HTMLCanvasElement, col: number, row: number): Rectangle | undefined => {
const rect = canvas.getBoundingClientRect();
if (col >= mappedColumns.length || row >= rows) {
return undefined;
}
const scale = rect.width / width;
const result = computeBounds(
col,
row,
width,
height,
groupHeaderHeight,
totalHeaderHeight,
cellXOffset,
cellYOffset,
translateX,
translateY,
rows,
freezeColumns,
freezeTrailingRows,
mappedColumns,
rowHeight
);
if (scale !== 1) {
result.x *= scale;
result.y *= scale;
result.width *= scale;
result.height *= scale;
}
result.x += rect.x;
result.y += rect.y;
return result;
},
[
width,
height,
groupHeaderHeight,
totalHeaderHeight,
cellXOffset,
cellYOffset,
translateX,
translateY,
rows,
freezeColumns,
freezeTrailingRows,
mappedColumns,
rowHeight,
]
);
const getMouseArgsForPosition = React.useCallback(
(canvas: HTMLCanvasElement, posX: number, posY: number, ev?: MouseEvent | TouchEvent): GridMouseEventArgs => {
const rect = canvas.getBoundingClientRect();
const scale = rect.width / width;
const x = (posX - rect.left) / scale;
const y = (posY - rect.top) / scale;
const edgeDetectionBuffer = 5;
const effectiveCols = getEffectiveColumns(mappedColumns, cellXOffset, width, undefined, translateX);
let button = 0;
let buttons = 0;
if (ev instanceof MouseEvent) {
button = ev.button;
buttons = ev.buttons;
}
// -1 === off right edge
const col = getColumnIndexForX(x, effectiveCols, translateX);
// -1: header or above
// undefined: offbottom
const row = getRowIndexForY(
y,
height,
enableGroups,
headerHeight,
groupHeaderHeight,
rows,
rowHeight,
cellYOffset,
translateY,
freezeTrailingRows
);
const shiftKey = ev?.shiftKey === true;
const ctrlKey = ev?.ctrlKey === true;
const metaKey = ev?.metaKey === true;
const isTouch = (ev !== undefined && !(ev instanceof MouseEvent)) || (ev as any)?.pointerType === "touch";
const scrollEdge: GridMouseEventArgs["scrollEdge"] = [
x < 0 ? -1 : width < x ? 1 : 0,
y < totalHeaderHeight ? -1 : height < y ? 1 : 0,
];
let result: GridMouseEventArgs;
if (col === -1 || y < 0 || x < 0 || row === undefined || x > width || y > height) {
const horizontal = x > width ? 1 : x < 0 ? -1 : 0;
const vertical = y > height ? 1 : y < 0 ? -1 : 0;
let innerHorizontal: OutOfBoundsRegionAxis = horizontal * 2;
let innerVertical: OutOfBoundsRegionAxis = vertical * 2;
if (horizontal === 0)
innerHorizontal = col === -1 ? OutOfBoundsRegionAxis.EndPadding : OutOfBoundsRegionAxis.Center;
if (vertical === 0)
innerVertical = row === undefined ? OutOfBoundsRegionAxis.EndPadding : OutOfBoundsRegionAxis.Center;
let isEdge = false;
if (col === -1 && row === -1) {
const b = getBoundsForItem(canvas, mappedColumns.length - 1, -1);
assert(b !== undefined);
isEdge = posX < b.x + b.width + edgeDetectionBuffer;
}
// This is used to ensure that clicking on the scrollbar doesn't unset the selection.
// Unfortunately this doesn't work for overlay scrollbars because they are just a broken interaction
// by design.
const isMaybeScrollbar =
(x > width && x < width + getScrollBarWidth()) || (y > height && y < height + getScrollBarWidth());
result = {
kind: outOfBoundsKind,
location: [col !== -1 ? col : x < 0 ? 0 : mappedColumns.length - 1, row ?? rows - 1],
region: [innerHorizontal, innerVertical],
shiftKey,
ctrlKey,
metaKey,
isEdge,
isTouch,
button,
buttons,
scrollEdge,
isMaybeScrollbar,
};
} else if (row <= -1) {
let bounds = getBoundsForItem(canvas, col, row);
assert(bounds !== undefined);
let isEdge = bounds !== undefined && bounds.x + bounds.width - posX <= edgeDetectionBuffer;
const previousCol = col - 1;
if (posX - bounds.x <= edgeDetectionBuffer && previousCol >= 0) {
isEdge = true;
bounds = getBoundsForItem(canvas, previousCol, row);
assert(bounds !== undefined);
result = {
kind: enableGroups && row === -2 ? groupHeaderKind : headerKind,
location: [previousCol, row] as any,
bounds: bounds,
group: mappedColumns[previousCol].group ?? "",
isEdge,
shiftKey,
ctrlKey,
metaKey,
isTouch,
localEventX: posX - bounds.x,
localEventY: posY - bounds.y,
button,
buttons,
scrollEdge,
};
} else {
result = {
kind: enableGroups && row === -2 ? groupHeaderKind : headerKind,
group: mappedColumns[col].group ?? "",
location: [col, row] as any,
bounds: bounds,
isEdge,
shiftKey,
ctrlKey,
metaKey,
isTouch,
localEventX: posX - bounds.x,
localEventY: posY - bounds.y,
button,
buttons,
scrollEdge,
};
}
} else {
const bounds = getBoundsForItem(canvas, col, row);
assert(bounds !== undefined);
const isEdge = bounds !== undefined && bounds.x + bounds.width - posX < edgeDetectionBuffer;
let isFillHandle = false;
if (fillHandle && selection.current !== undefined) {
const fillHandleLocation = rectBottomRight(selection.current.range);
const fillHandleCellBounds = getBoundsForItem(canvas, fillHandleLocation[0], fillHandleLocation[1]);
if (fillHandleCellBounds !== undefined) {
const handleLogicalCenterX = fillHandleCellBounds.x + fillHandleCellBounds.width - 2;
const handleLogicalCenterY = fillHandleCellBounds.y + fillHandleCellBounds.height - 2;
//check if posX and posY are within fillHandleClickSize from handleLogicalCenter
isFillHandle =
Math.abs(handleLogicalCenterX - posX) < fillHandleClickSize &&
Math.abs(handleLogicalCenterY - posY) < fillHandleClickSize;
}
}
result = {
kind: "cell",
location: [col, row],
bounds: bounds,
isEdge,
shiftKey,
ctrlKey,
isFillHandle,
metaKey,
isTouch,
localEventX: posX - bounds.x,
localEventY: posY - bounds.y,
button,
buttons,
scrollEdge,
};
}
return result;
},
[
width,
mappedColumns,
cellXOffset,
translateX,
height,
enableGroups,
headerHeight,
groupHeaderHeight,
rows,
rowHeight,
cellYOffset,
translateY,
freezeTrailingRows,
getBoundsForItem,
fillHandle,
selection,
totalHeaderHeight,
]
);
const [hoveredItem] = hoveredItemInfo ?? [];
const enqueueRef = React.useRef<EnqueueCallback>(() => {
// do nothing
});
const hoverInfoRef = React.useRef(hoveredItemInfo);
hoverInfoRef.current = hoveredItemInfo;
const [bufferACtx, bufferBCtx] = React.useMemo(() => {
const a = document.createElement("canvas");
const b = document.createElement("canvas");
a.style["display"] = "none";
a.style["opacity"] = "0";
a.style["position"] = "fixed";
b.style["display"] = "none";
b.style["opacity"] = "0";
b.style["position"] = "fixed";
return [a.getContext("2d", { alpha: false }), b.getContext("2d", { alpha: false })];
}, []);
React.useLayoutEffect(() => {
if (bufferACtx === null || bufferBCtx === null) return;
document.documentElement.append(bufferACtx.canvas);
document.documentElement.append(bufferBCtx.canvas);
return () => {
bufferACtx.canvas.remove();
bufferBCtx.canvas.remove();
};
}, [bufferACtx, bufferBCtx]);
const renderStateProvider = React.useMemo(() => new RenderStateProvider(), []);
const maxDPR = enableFirefoxRescaling && scrolling ? 1 : enableSafariRescaling && scrolling ? 2 : 5;
const minimumCellWidth = experimental?.disableMinimumCellWidth === true ? 1 : 10;
const lastArgsRef = React.useRef<DrawGridArg>();
const canvasCtx = React.useRef<CanvasRenderingContext2D | null>(null);
const overlayCtx = React.useRef<CanvasRenderingContext2D | null>(null);
const draw = React.useCallback(() => {
const canvas = ref.current;
const overlay = overlayRef.current;
if (canvas === null || overlay === null) return;
if (canvasCtx.current === null) {
canvasCtx.current = canvas.getContext("2d", { alpha: false });
canvas.width = 0;
canvas.height = 0;
}
if (overlayCtx.current === null) {
overlayCtx.current = overlay.getContext("2d", { alpha: false });
overlay.width = 0;
overlay.height = 0;
}
if (canvasCtx.current === null || overlayCtx.current === null || bufferACtx === null || bufferBCtx === null) {
return;
}
let didOverride = false;
const overrideCursor = (cursor: React.CSSProperties["cursor"]) => {
didOverride = true;
setDrawCursorOverride(cursor);
};
const last = lastArgsRef.current;
const current = {
headerCanvasCtx: overlayCtx.current,
canvasCtx: canvasCtx.current,
bufferACtx,
bufferBCtx,
width,
height,
cellXOffset,
cellYOffset,
translateX: Math.round(translateX),
translateY: Math.round(translateY),
mappedColumns,
enableGroups,
freezeColumns,
dragAndDropState,
theme,
headerHeight,
groupHeaderHeight,
disabledRows: disabledRows ?? CompactSelection.empty(),
rowHeight,
verticalBorder,
isResizing,
resizeCol,
isFocused,
selection,
fillHandle,
drawCellCallback,
hasAppendRow,
overrideCursor,
maxScaleFactor: maxDPR,
freezeTrailingRows,
rows,
drawFocus: drawFocusRing,
getCellContent,
getGroupDetails: getGroupDetails ?? (name => ({ name })),
getRowThemeOverride,
drawHeaderCallback,
prelightCells,
highlightRegions,
imageLoader,
lastBlitData,
damage: damageRegion.current,
hoverValues: hoverValues.current,
hoverInfo: hoverInfoRef.current,
spriteManager,
scrolling,
hyperWrapping: experimental?.hyperWrapping ?? false,
touchMode: lastWasTouch,
enqueue: enqueueRef.current,
renderStateProvider,
renderStrategy: experimental?.renderStrategy ?? (browserIsSafari.value ? "double-buffer" : "single-buffer"),
getCellRenderer,
minimumCellWidth,
resizeIndicator,
};
// This confusing bit of code due to some poor design. Long story short, the damage property is only used
// with what is effectively the "last args" for the last normal draw anyway. We don't want the drawing code
// to look at this and go "shit dawg, nothing changed" so we force it to draw frash, but the damage restricts
// the draw anyway.
//
// Dear future Jason, I'm sorry. It was expedient, it worked, and had almost zero perf overhead. THe universe
// basically made me do it. What choice did I have?
if (current.damage === undefined) {
lastArgsRef.current = current;
drawGrid(current, last);
} else {
drawGrid(current, undefined);
}
// don't reset on damage events
if (!didOverride && (current.damage === undefined || current.damage.has(hoverInfoRef?.current?.[0]))) {
setDrawCursorOverride(undefined);
}
}, [
bufferACtx,
bufferBCtx,
width,
height,
cellXOffset,
cellYOffset,
translateX,
translateY,
mappedColumns,
enableGroups,
freezeColumns,
dragAndDropState,
theme,
headerHeight,
groupHeaderHeight,
disabledRows,
rowHeight,
verticalBorder,
isResizing,
hasAppendRow,
resizeCol,
isFocused,
selection,
fillHandle,
freezeTrailingRows,
rows,
drawFocusRing,
maxDPR,
getCellContent,
getGroupDetails,
getRowThemeOverride,
drawCellCallback,
drawHeaderCallback,
prelightCells,
highlightRegions,
imageLoader,
spriteManager,
scrolling,
experimental?.hyperWrapping,
experimental?.renderStrategy,
lastWasTouch,
renderStateProvider,
getCellRenderer,
minimumCellWidth,
resizeIndicator,
]);
const lastDrawRef = React.useRef(draw);
React.useLayoutEffect(() => {
draw();
lastDrawRef.current = draw;
}, [draw]);
React.useLayoutEffect(() => {
const fn = async () => {
if (document?.fonts?.ready === undefined) return;
await document.fonts.ready;
lastArgsRef.current = undefined;
lastDrawRef.current();
};
void fn();
}, []);
const damageInternal = React.useCallback((locations: CellSet) => {
damageRegion.current = locations;
lastDrawRef.current();
damageRegion.current = undefined;
}, []);
const enqueue = useAnimationQueue(damageInternal);
enqueueRef.current = enqueue;
const damage = React.useCallback(
(cells: DamageUpdateList) => {
damageInternal(new CellSet(cells.map(x => x.cell)));
},
[damageInternal]
);
imageLoader.setCallback(damageInternal);
const [overFill, setOverFill] = React.useState(false);
const [hCol, hRow] = hoveredItem ?? [];
const headerHovered = hCol !== undefined && hRow === -1 && columns[hCol].headerRowMarkerDisabled !== true;
const groupHeaderHovered = hCol !== undefined && hRow === -2;
let clickableInnerCellHovered = false;
let editableBoolHovered = false;
let cursorOverride: React.CSSProperties["cursor"] | undefined = drawCursorOverride;
if (cursorOverride === undefined && hCol !== undefined && hRow !== undefined && hRow > -1 && hRow < rows) {
const cell = getCellContent([hCol, hRow], true);
clickableInnerCellHovered =
cell.kind === InnerGridCellKind.NewRow ||
(cell.kind === InnerGridCellKind.Marker && cell.markerKind !== "number");
editableBoolHovered = cell.kind === GridCellKind.Boolean && booleanCellIsEditable(cell);
cursorOverride = cell.cursor;
}
const canDrag = hoveredOnEdge ?? false;
const cursor = isDragging
? "grabbing"
: canDrag || isResizing
? "col-resize"
: overFill || isFilling
? "crosshair"
: cursorOverride !== undefined
? cursorOverride
: headerHovered || clickableInnerCellHovered || editableBoolHovered || groupHeaderHovered
? "pointer"
: "default";
console.log("CURSOR", cursor, cursorOverride, headerHovered);
const style = React.useMemo(
() => ({
// width,
// height,
contain: "strict",
display: "block",
cursor,
}),
[cursor]
);
const lastSetCursor = React.useRef<typeof cursor>("default");
const target = eventTargetRef?.current;
if (target !== null && target !== undefined && lastSetCursor.current !== style.cursor) {
// because we have an event target we need to set its cursor instead.
target.style.cursor = lastSetCursor.current = style.cursor;
}
const groupHeaderActionForEvent = React.useCallback(
(group: string, bounds: Rectangle, localEventX: number, localEventY: number) => {
if (getGroupDetails === undefined) return undefined;
const groupDesc = getGroupDetails(group);
if (groupDesc.actions !== undefined) {
const boxes = getActionBoundsForGroup(bounds, groupDesc.actions);
for (const [i, box] of boxes.entries()) {
if (pointInRect(box, localEventX + bounds.x, localEventY + box.y)) {
return groupDesc.actions[i];
}
}
}
return undefined;
},
[getGroupDetails]
);
const isOverHeaderElement = React.useCallback(
(
canvas: HTMLCanvasElement,
col: number,
clientX: number,
clientY: number
):
| {
area: "menu" | "indicator";
bounds: Rectangle;
}
| undefined => {
const header = mappedColumns[col];
if (!isDragging && !isResizing && !(hoveredOnEdge ?? false)) {
const headerBounds = getBoundsForItem(canvas, col, -1);
assert(headerBounds !== undefined);
const headerLayout = computeHeaderLayout(
undefined,
header,
headerBounds.x,
headerBounds.y,