forked from deephaven/web-client-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGrid.tsx
More file actions
2297 lines (1993 loc) · 70.9 KB
/
Grid.tsx
File metadata and controls
2297 lines (1993 loc) · 70.9 KB
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 react/no-did-update-set-state: "off" */
import React, {
CSSProperties,
PureComponent,
ReactNode,
RefObject,
} from 'react';
import classNames from 'classnames';
import memoize from 'memoize-one';
import clamp from 'lodash.clamp';
import { assertNotNull, EMPTY_ARRAY, getChangedKeys } from '@deephaven/utils';
import GridMetricCalculator, { GridMetricState } from './GridMetricCalculator';
import GridModel from './GridModel';
import GridMouseHandler, {
GridMouseEvent,
GridMouseHandlerFunctionName,
} from './GridMouseHandler';
import GridTheme, { GridTheme as GridThemeType } from './GridTheme';
import GridRange, { GridRangeIndex, SELECTION_DIRECTION } from './GridRange';
import GridRenderer from './GridRenderer';
import GridUtils, { GridPoint, isLinkToken, Token } from './GridUtils';
import {
GridSelectionMouseHandler,
GridColumnMoveMouseHandler,
GridColumnSeparatorMouseHandler,
GridHorizontalScrollBarMouseHandler,
GridRowMoveMouseHandler,
GridRowSeparatorMouseHandler,
GridRowTreeMouseHandler,
GridScrollBarCornerMouseHandler,
GridVerticalScrollBarMouseHandler,
EditMouseHandler,
GridSeparator,
GridTokenMouseHandler,
} from './mouse-handlers';
import './Grid.scss';
import KeyHandler, {
GridKeyHandlerFunctionName,
GridKeyboardEvent,
} from './KeyHandler';
import {
EditKeyHandler,
PasteKeyHandler,
SelectionKeyHandler,
TreeKeyHandler,
} from './key-handlers';
import CellInputField from './CellInputField';
import PasteError from './errors/PasteError';
import GridMetrics, {
Coordinate,
ModelIndex,
MoveOperation,
VisibleIndex,
} from './GridMetrics';
import { isExpandableGridModel } from './ExpandableGridModel';
import {
assertIsEditableGridModel,
EditOperation,
isEditableGridModel,
} from './EditableGridModel';
import { EventHandlerResultOptions } from './EventHandlerResult';
import { assertIsDefined } from './errors';
import ThemeContext from './ThemeContext';
import { DraggingColumn } from './mouse-handlers/GridColumnMoveMouseHandler';
import {
EditingCell,
GridRenderState,
EditingCellTextSelectionRange,
} from './GridRendererTypes';
type LegacyCanvasRenderingContext2D = CanvasRenderingContext2D & {
webkitBackingStorePixelRatio?: number;
mozBackingStorePixelRatio?: number;
msBackingStorePixelRatio?: number;
oBackingStorePixelRatio?: number;
backingStorePixelRatio?: number;
};
export type GridProps = typeof Grid.defaultProps & {
// Children to render in the grid
children?: ReactNode;
// Options to set on the canvas
canvasOptions?: CanvasRenderingContext2DSettings;
// Whether the grid should stick to the bottom or the right once scrolled to the end
// Only matters with ticking grids
isStickyBottom?: boolean;
isStickyRight?: boolean;
// Whether the grid is currently stuck to the bottom or the right
isStuckToBottom?: boolean;
isStuckToRight?: boolean;
// Calculate all the metrics required for drawing the grid
metricCalculator?: GridMetricCalculator;
// The model to pull data from
model: GridModel;
// Optional key and mouse handlers
keyHandlers?: readonly KeyHandler[];
mouseHandlers?: readonly GridMouseHandler[];
// Initial state of moved columns or rows
movedColumns?: readonly MoveOperation[];
movedRows?: readonly MoveOperation[];
// Callback for if an error occurs
onError?: (e: Error) => void;
// Callback when the selection within the grid changes
onSelectionChanged?: (ranges: readonly GridRange[]) => void;
// Callback when the moved columns or rows have changed
onMovedColumnsChanged?: (movedColumns: readonly MoveOperation[]) => void;
onMovedRowsChanged?: (movedRows: readonly MoveOperation[]) => void;
// Callback when a move operation is completed
onMoveColumnComplete?: (movedColumns: readonly MoveOperation[]) => void;
onMoveRowComplete?: (movedRows: readonly MoveOperation[]) => void;
// Callback when the viewport has scrolled or changed
onViewChanged?: (metrics: GridMetrics) => void;
// Callback when a token is clicked
// eslint-disable-next-line react/no-unused-prop-types
onTokenClicked?: (token: Token) => void;
// Renderer for the grid canvas
renderer?: GridRenderer;
// Optional state override to pass in to the metric and render state
// Can be used to add custom properties as well
stateOverride?: Record<string, unknown>;
theme?: Partial<GridThemeType>;
};
export type GridState = {
// Top/left visible cell in the grid. Note that it's visible row/column index, not the model index (ie. if columns are re-ordered)
top: VisibleIndex;
left: VisibleIndex;
// The scroll offset of the top/left cell. 0,0 means the cell is at the top left
topOffset: number; // Should be less than the height of the row
leftOffset: number; // Should be less than the width of the column
// current column/row that user is dragging
draggingColumn: DraggingColumn | null;
draggingRow: VisibleIndex | null;
// Offset when dragging a row
draggingRowOffset: number | null;
// When drawing header separators for resizing
// Keeps hover style when mouse is in buffer before resize starts
draggingColumnSeparator: GridSeparator | null;
draggingRowSeparator: GridSeparator | null;
// Dragging a scroll bar status
isDraggingHorizontalScrollBar: boolean;
isDraggingVerticalScrollBar: boolean;
// Anything is performing a drag, for blocking hover rendering
isDragging: boolean;
// The coordinates of the mouse. May be outside of the canvas
mouseX: number | null;
mouseY: number | null;
// Move operations the user has performed on this grids columns/rows
movedColumns: readonly MoveOperation[];
movedRows: readonly MoveOperation[];
// Cursor (highlighted cell) location and active selected range
cursorRow: VisibleIndex | null;
cursorColumn: VisibleIndex | null;
selectionStartRow: VisibleIndex | null;
selectionStartColumn: VisibleIndex | null;
selectionEndRow: VisibleIndex | null;
selectionEndColumn: VisibleIndex | null;
// Currently selected ranges and previously selected ranges
// Store the previously selected ranges to determine if the new selection should
// deselect again (if it's the same range)
selectedRanges: readonly GridRange[];
lastSelectedRanges: readonly GridRange[];
// The mouse cursor style to use when hovering over the grid element
cursor: string | null;
// { column: number, row: number, selectionRange: [number, number], value: string | null, isQuickEdit?: boolean }
// The cell that is currently being edited
editingCell: EditingCell | null;
// Whether we're stuck to the bottom or the right
isStuckToBottom: boolean;
isStuckToRight: boolean;
};
/**
* High performance, extendible, themeable grid component.
* Architectured to be fast and handle billions of rows/columns by default.
* The base model does not provide support for sorting, filtering, etc.
* To get that functionality, extend GridModel/GridRenderer, and add onClick/onContextMenu handlers to implement your own sort.
*
* Extend GridModel with your own data model to provide the data for the grid.
* Extend GridTheme to change the appearance if the grid. See GridTheme for all the settable values.
* Extend GridMetricCalculator to provide different metrics for the grid, such as column sizing, header sizing, etc.
* Extend GridRenderer to have complete control over the rendering process. Can override just one method such as drawColumnHeader, or override the whole drawCanvas process.
*
* Add an onViewChanged callback to page in/out data as user moves around the grid
* Can also add onClick and onContextMenu handlers to add custom functionality and menus.
*/
class Grid extends PureComponent<GridProps, GridState> {
static contextType = ThemeContext;
static defaultProps = {
canvasOptions: { alpha: false } as CanvasRenderingContext2DSettings,
isStickyBottom: false,
isStickyRight: false,
isStuckToBottom: false,
isStuckToRight: false,
keyHandlers: EMPTY_ARRAY as readonly KeyHandler[],
mouseHandlers: EMPTY_ARRAY as readonly GridMouseHandler[],
movedColumns: EMPTY_ARRAY as readonly MoveOperation[],
movedRows: EMPTY_ARRAY as readonly MoveOperation[],
onError: (): void => undefined,
onSelectionChanged: (): void => undefined,
onMovedColumnsChanged: (moveOperations: readonly MoveOperation[]): void =>
undefined,
onMoveColumnComplete: (): void => undefined,
onMovedRowsChanged: (): void => undefined,
onMoveRowComplete: (): void => undefined,
onViewChanged: (metrics: GridMetrics): void => undefined,
onTokenClicked: (token: Token): void => {
if (isLinkToken(token)) {
window.open(token.href, '_blank', 'noopener,noreferrer');
}
},
stateOverride: {} as Record<string, unknown>,
theme: {
autoSelectColumn: false,
autoSelectRow: false,
} as Partial<GridThemeType>,
};
// use same constant as chrome source for windows
// https://github.com/chromium/chromium/blob/973af9d461b6b5dc60208c8d3d66adc27e53da78/ui/events/blink/web_input_event_builders_win.cc#L285
static pixelsPerLine = 100 / 3;
static dragTimeout = 1000;
static getTheme = memoize(
(
contextTheme: Partial<GridThemeType>,
userTheme: Partial<GridThemeType>
) => ({
...GridTheme,
...contextTheme,
...userTheme,
})
);
/**
* On some devices there may be different scaling required for high DPI. Get the scale required for the canvas.
* @param context The canvas context
* @returns The scale to use
*/
static getScale(context: CanvasRenderingContext2D): number {
const devicePixelRatio = window.devicePixelRatio || 1;
// backingStorePixelRatio is deprecated, but check it just in case
const legacyContext = context as LegacyCanvasRenderingContext2D;
const backingStorePixelRatio =
// Not worth converting to a massive if structure
// Converting would reduce readability and maintainability
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
legacyContext.webkitBackingStorePixelRatio ??
legacyContext.mozBackingStorePixelRatio ??
legacyContext.msBackingStorePixelRatio ??
legacyContext.oBackingStorePixelRatio ??
legacyContext.backingStorePixelRatio ??
1;
return devicePixelRatio / backingStorePixelRatio;
}
/**
* Get the class name from the cursor provided
* @param cursor The grid cursor to use
* @returns Class name with the grid-cursor prefix or null if no cursor provided
*/
static getCursorClassName(cursor: string | null): string | null {
return cursor != null && cursor !== '' ? `grid-cursor-${cursor}` : null;
}
// Need to disable react/sort-comp so I can put the fields here
/* eslint-disable react/sort-comp */
renderer: GridRenderer;
metricCalculator: GridMetricCalculator;
canvas: HTMLCanvasElement | null;
canvasContext: CanvasRenderingContext2D | null;
// The wrapper element for the canvas, used for sizing
canvasWrapper: RefObject<HTMLDivElement>;
// Listen for resizing of the element and update the canvas appropriately
resizeObserver: ResizeObserver;
// We draw the canvas on the next animation frame, keep track of the next one
animationFrame: number | null;
// Keep track of previous metrics and new metrics for comparison
prevMetrics: GridMetrics | null;
metrics: GridMetrics | null;
renderState: GridRenderState;
// Track the cursor that is currently added to the document
// Add to document so that when dragging the cursor stays, even if mouse leaves the canvas
// Note: on document, not body so that cursor styling can be combined with
// blocked pointer events that would otherwise prevent cursor styling from showing
documentCursor: string | null;
dragTimer: ReturnType<typeof setTimeout> | null;
keyHandlers: readonly KeyHandler[];
mouseHandlers: readonly GridMouseHandler[];
/* eslint-enable react/sort-comp */
constructor(props: GridProps) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.handleContextMenu = this.handleContextMenu.bind(this);
this.handleEditCellCancel = this.handleEditCellCancel.bind(this);
this.handleEditCellChange = this.handleEditCellChange.bind(this);
this.handleEditCellCommit = this.handleEditCellCommit.bind(this);
this.handleDoubleClick = this.handleDoubleClick.bind(this);
this.notifyKeyboardHandlers = this.notifyKeyboardHandlers.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.handleKeyUp = this.handleKeyUp.bind(this);
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseDrag = this.handleMouseDrag.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseLeave = this.handleMouseLeave.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
this.handleResize = this.handleResize.bind(this);
this.handleWheel = this.handleWheel.bind(this);
this.getSelectedRanges = this.getSelectedRanges.bind(this);
const {
isStuckToBottom,
isStuckToRight,
metricCalculator,
movedColumns,
movedRows,
renderer,
} = props;
this.renderer = renderer || new GridRenderer();
this.metricCalculator = metricCalculator || new GridMetricCalculator();
this.canvas = null;
this.canvasContext = null;
this.canvasWrapper = React.createRef();
this.resizeObserver = new window.ResizeObserver(this.handleResize);
this.animationFrame = null;
this.prevMetrics = null;
this.metrics = null;
this.renderState = {} as GridRenderState;
// Track the cursor that is currently added to the document
// Add to document so that when dragging the cursor stays, even if mouse leaves the canvas
// Note: on document, not body so that cursor styling can be combined with
// blocked pointer events that would otherwise prevent cursor styling from showing
this.documentCursor = null;
this.dragTimer = null;
// specify handler ordering, such that any extensions can insert handlers in between
this.keyHandlers = [
new EditKeyHandler(400),
new PasteKeyHandler(450),
new SelectionKeyHandler(500),
new TreeKeyHandler(900),
];
this.mouseHandlers = [
new GridRowSeparatorMouseHandler(100),
new GridColumnSeparatorMouseHandler(200),
new GridRowMoveMouseHandler(300),
new GridColumnMoveMouseHandler(400),
new EditMouseHandler(450),
new GridVerticalScrollBarMouseHandler(500),
new GridHorizontalScrollBarMouseHandler(600),
new GridScrollBarCornerMouseHandler(700),
new GridRowTreeMouseHandler(800),
new GridTokenMouseHandler(875),
new GridSelectionMouseHandler(900),
];
this.state = {
// Top/left visible cell in the grid. Note that it's visible row/column index, not the model index (ie. if columns are re-ordered)
top: 0,
left: 0,
// The scroll offset of the top/left cell. 0,0 means the cell is at the top left
// Should be less than the width of the column
topOffset: 0,
leftOffset: 0,
// current column/row that user is dragging
draggingColumn: null,
draggingRow: null,
// Offset when dragging a row
draggingRowOffset: null,
// When drawing header separators for resizing
draggingColumnSeparator: null,
draggingRowSeparator: null,
isDraggingHorizontalScrollBar: false,
isDraggingVerticalScrollBar: false,
// Anything is performing a drag, for blocking hover rendering
isDragging: false,
// The coordinates of the mouse. May be outside of the canvas
mouseX: null,
mouseY: null,
// Move operations the user has performed on this grids columns/rows
movedColumns,
movedRows,
// Cursor (highlighted cell) location and active selected range
cursorRow: null,
cursorColumn: null,
selectionStartRow: null,
selectionStartColumn: null,
selectionEndRow: null,
selectionEndColumn: null,
// Currently selected ranges and previously selected ranges
// Store the previously selected ranges to determine if the new selection should
// deselect again (if it's the same range)
selectedRanges: EMPTY_ARRAY,
lastSelectedRanges: EMPTY_ARRAY,
// The mouse cursor style to use when hovering over the grid element
cursor: null,
// { column: number, row: number, selectionRange: [number, number], value: string | null, isQuickEdit?: boolean }
// The cell that is currently being edited
editingCell: null,
isStuckToBottom,
isStuckToRight,
};
}
componentDidMount(): void {
this.initContext();
// Need to explicitly add wheel event to canvas so we can preventDefault/avoid passive listener issue
// Otherwise React attaches listener at doc level and you can't prevent default
// https://github.com/facebook/react/issues/14856
this.canvas?.addEventListener('wheel', this.handleWheel, {
passive: false,
});
if (this.canvasWrapper.current != null) {
this.resizeObserver.observe(this.canvasWrapper.current);
}
this.updateCanvas();
// apply on mount, so that it works with a static model
// https://github.com/deephaven/web-client-ui/issues/581
const { isStuckToBottom, isStuckToRight } = this.props;
if (isStuckToBottom) {
this.scrollToBottom();
}
if (isStuckToRight) {
this.scrollToRight();
}
}
componentDidUpdate(prevProps: GridProps, prevState: GridState): void {
const changedProps = getChangedKeys(prevProps, this.props);
const changedState = getChangedKeys(prevState, this.state);
// We don't need to bother re-checking any of the metrics if only the children have changed
if (
changedProps.length === 1 &&
changedProps[0] === 'children' &&
changedState.length === 0
) {
return;
}
const {
isStickyBottom,
isStickyRight,
movedColumns,
movedRows,
onMovedColumnsChanged,
onMoveColumnComplete,
onMovedRowsChanged,
onMoveRowComplete,
} = this.props;
const {
isStickyBottom: prevIsStickyBottom,
isStickyRight: prevIsStickyRight,
movedColumns: prevPropMovedColumns,
movedRows: prevPropMovedRows,
} = prevProps;
const {
movedColumns: prevStateMovedColumns,
movedRows: prevStateMovedRows,
} = prevState;
const {
draggingColumn,
draggingRow,
movedColumns: currentStateMovedColumns,
movedRows: currentStateMovedRows,
} = this.state;
if (prevPropMovedColumns !== movedColumns) {
this.setState({ movedColumns });
}
if (prevPropMovedRows !== movedRows) {
this.setState({ movedRows });
}
if (prevStateMovedColumns !== currentStateMovedColumns) {
onMovedColumnsChanged(currentStateMovedColumns);
}
if (prevState.draggingColumn != null && draggingColumn == null) {
onMoveColumnComplete(currentStateMovedColumns);
}
if (prevStateMovedRows !== currentStateMovedRows) {
onMovedRowsChanged(currentStateMovedRows);
}
if (prevState.draggingRow != null && draggingRow == null) {
onMoveRowComplete(currentStateMovedRows);
}
if (isStickyBottom !== prevIsStickyBottom) {
this.setState({ isStuckToBottom: false });
}
if (isStickyRight !== prevIsStickyRight) {
this.setState({ isStuckToRight: false });
}
this.updateMetrics();
this.requestUpdateCanvas();
this.checkStickyScroll();
if (this.validateSelection()) {
this.checkSelectionChange(prevState);
}
}
componentWillUnmount(): void {
if (this.animationFrame != null) {
cancelAnimationFrame(this.animationFrame);
}
this.canvas?.removeEventListener('wheel', this.handleWheel);
window.removeEventListener(
'mousemove',
this.handleMouseDrag as unknown as EventListenerOrEventListenerObject,
true
);
window.removeEventListener(
'mouseup',
this.handleMouseUp as unknown as EventListenerOrEventListenerObject,
true
);
this.resizeObserver.disconnect();
this.stopDragTimer();
}
getTheme(): GridThemeType {
const { theme } = this.props;
return Grid.getTheme(this.context, theme);
}
getGridPointFromEvent(event: GridMouseEvent): GridPoint {
assertIsDefined(this.canvas);
const rect = this.canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
return this.getGridPointFromXY(x, y);
}
getGridPointFromXY(x: Coordinate, y: Coordinate): GridPoint {
if (!this.metrics) throw new Error('metrics must be set');
return GridUtils.getGridPointFromXY(x, y, this.metrics);
}
getMetricState(state = this.state): GridMetricState {
const theme = this.getTheme();
const { model, stateOverride } = this.props;
if (!this.canvasContext || !this.canvas) {
throw new Error('Canvas and context must be defined to get metrics');
}
const context = this.canvasContext;
const width = this.canvas.clientWidth;
const height = this.canvas.clientHeight;
const {
left,
top,
leftOffset,
topOffset,
movedColumns,
movedRows,
isDraggingHorizontalScrollBar,
isDraggingVerticalScrollBar,
draggingColumn,
} = state;
return {
left,
top,
leftOffset,
topOffset,
width,
height,
context,
theme,
model,
movedColumns,
movedRows,
isDraggingHorizontalScrollBar,
isDraggingVerticalScrollBar,
draggingColumn,
...stateOverride,
};
}
getCachedKeyHandlers = memoize((keyHandlers: readonly KeyHandler[]) =>
[...keyHandlers, ...this.keyHandlers].sort((a, b) => a.order - b.order)
);
getKeyHandlers(): readonly KeyHandler[] {
const { keyHandlers } = this.props;
return this.getCachedKeyHandlers(keyHandlers);
}
getCachedMouseHandlers = memoize(
(mouseHandlers: readonly GridMouseHandler[]): readonly GridMouseHandler[] =>
[...mouseHandlers, ...this.mouseHandlers].sort(
(a, b) => a.order - b.order
)
);
getMouseHandlers(): readonly GridMouseHandler[] {
const { mouseHandlers } = this.props;
return this.getCachedMouseHandlers(mouseHandlers);
}
/**
* Translate from the provided visible index to the model index
* @param columnIndex The column index to get the model for
* @returns The model index
*/
getModelColumn(columnIndex: VisibleIndex): ModelIndex {
const modelIndex = this.metrics?.modelColumns?.get(columnIndex);
if (modelIndex === undefined) {
throw new Error(`Unable to get ModelIndex for column ${columnIndex}`);
}
return modelIndex;
}
/**
* Translate from the provided visible index to the model index
* @param rowIndex The row index to get the model for
* @returns The model index
*/
getModelRow(rowIndex: VisibleIndex): ModelIndex {
const modelIndex = this.metrics?.modelRows?.get(rowIndex);
if (modelIndex === undefined) {
throw new Error(`Unable to get ModelIndex for row ${rowIndex}`);
}
return modelIndex;
}
/**
* Toggle a row between expanded and collapsed states
* @param row The row to toggle expansion for
* @param expandDescendants True if nested rows should be expanded, false otherwise
*/
toggleRowExpanded(row: VisibleIndex, expandDescendants = false): void {
const modelRow = this.getModelRow(row);
const { model } = this.props;
// We only want to set expansion if the row is expandable
// If it's not, still move the cursor to that position, as it may be outside of the current viewport and we don't know if it's expandable yet
if (isExpandableGridModel(model) && model.isRowExpandable(modelRow)) {
model.setRowExpanded(
modelRow,
!model.isRowExpanded(modelRow),
expandDescendants
);
}
this.clearSelectedRanges();
this.commitSelection(); // Need to commit before moving in case we're selecting same row again
this.moveCursorToPosition(0, row);
this.commitSelection();
this.setState({ isStuckToBottom: false });
}
/**
* Scrolls to bottom, if not already at bottom
*/
scrollToBottom(): void {
if (!this.metrics) return;
const { bottomVisible, rowCount, top, lastTop } = this.metrics;
if ((bottomVisible < rowCount - 1 && bottomVisible > 0) || top > lastTop) {
this.setState({ top: lastTop });
}
}
/**
* Scrolls to right, if not already at right
*/
scrollToRight(): void {
if (!this.metrics) return;
const { rightVisible, columnCount, left, lastLeft } = this.metrics;
if (
(rightVisible < columnCount - 1 && rightVisible > 0) ||
left > lastLeft
) {
this.setState({ left: lastLeft });
}
}
/**
* Allows the selected ranges to be set programatically
* Will update the cursor and selection start/end based on the new ranges
* @param gridRanges The new selected ranges to set
*/
setSelectedRanges(gridRanges: readonly GridRange[]): void {
const { model } = this.props;
const { columnCount, rowCount } = model;
const { cursorRow, cursorColumn, selectedRanges } = this.state;
this.setState({
selectedRanges: gridRanges,
lastSelectedRanges: selectedRanges,
});
if (gridRanges.length > 0) {
const range = GridRange.boundedRange(
gridRanges[0],
columnCount,
rowCount
);
let newCursorRow = cursorRow;
let newCursorColumn = cursorColumn;
if (!range.containsCell(cursorColumn, cursorRow)) {
({ row: newCursorRow, column: newCursorColumn } = range.startCell());
}
this.setState({
selectionStartColumn: range.startColumn,
selectionStartRow: range.startRow,
selectionEndColumn: range.endColumn,
selectionEndRow: range.endRow,
cursorColumn: newCursorColumn,
cursorRow: newCursorRow,
});
}
}
initContext(): void {
const { canvas } = this;
const { canvasOptions } = this.props;
if (!canvas) throw new Error('Canvas not set');
this.canvasContext = canvas.getContext('2d', canvasOptions);
}
requestUpdateCanvas(): void {
if (this.animationFrame != null) {
return;
}
this.animationFrame = requestAnimationFrame(() => {
this.animationFrame = null;
this.updateCanvas();
});
}
updateCanvas(): void {
this.updateCanvasScale();
this.updateMetrics();
this.updateRenderState();
const { canvasContext, metrics, renderState } = this;
assertNotNull(canvasContext);
assertNotNull(metrics);
assertNotNull(renderState);
this.renderer.configureContext(canvasContext, renderState);
const { onViewChanged } = this.props;
onViewChanged(metrics);
this.drawCanvas(metrics);
}
private updateCanvasScale(): void {
const { canvas, canvasContext, canvasWrapper } = this;
if (!canvas) throw new Error('canvas not set');
if (!canvasContext) throw new Error('canvasContext not set');
if (!canvasWrapper.current) throw new Error('canvasWrapper not set');
// the parent wrapper has 100% width/height, and is used for determining size
// we don't want to stretch the canvas to 100%, to avoid fractional pixels.
// A wrapper element must be used for sizing, and canvas size must be
// set manually to a floored value in css and a scaled value in width/height
const rect = canvasWrapper.current.getBoundingClientRect();
const width = Math.floor(rect.width);
const height = Math.floor(rect.height);
// avoid triggering a dom re-calc if size hasn't changed
if (
parseFloat(canvas.style.width) === width &&
parseFloat(canvas.style.height) === height
) {
return;
}
const scale = Grid.getScale(canvasContext);
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
canvas.width = width * scale;
canvas.height = height * scale;
canvasContext.scale(scale, scale);
}
updateScrollBounds(): void {
if (!this.metrics) throw new Error('metrics not set');
const { left, top } = this.state;
const { lastLeft, lastTop } = this.metrics;
if (left > lastLeft) {
this.setState({ left: lastLeft, leftOffset: 0 });
}
if (top > lastTop) {
this.setState({ top: lastTop, topOffset: 0 });
}
}
/**
* Compares the current metrics with the previous metrics to see if we need to scroll when it is stuck to the bottom or the right
*/
checkStickyScroll(): void {
if (!this.metrics) {
return;
}
if (this.prevMetrics) {
const { rowCount, columnCount, height, width } = this.metrics;
const {
rowCount: prevRowCount,
columnCount: prevColumnCount,
height: prevHeight,
width: prevWidth,
} = this.prevMetrics;
if (prevRowCount !== rowCount || height !== prevHeight) {
const { isStuckToBottom } = this.state;
if (isStuckToBottom) {
this.scrollToBottom();
}
}
if (prevColumnCount !== columnCount || width !== prevWidth) {
const { isStuckToRight } = this.state;
if (isStuckToRight) {
this.scrollToRight();
}
}
}
this.prevMetrics = this.metrics;
}
updateMetrics(state = this.state): GridMetrics {
this.prevMetrics = this.metrics;
const { metricCalculator } = this;
const metricState = this.getMetricState(state);
this.metrics = metricCalculator.getMetrics(metricState);
this.updateScrollBounds();
return this.metrics;
}
/**
* Check if the selection state has changed, and call the onSelectionChanged callback if they have
* @param prevState The previous grid state
*/
checkSelectionChange(prevState: GridState): void {
const { selectedRanges: oldSelectedRanges } = prevState;
const { selectedRanges } = this.state;
if (selectedRanges !== oldSelectedRanges) {
const { onSelectionChanged } = this.props;
onSelectionChanged(selectedRanges);
}
}
/**
* Validate the current selection, and reset if it is invalid
* @returns True if the selection is valid, false if the selection was invalid and has been reset
*/
validateSelection(): boolean {
const { model } = this.props;
const { selectedRanges } = this.state;
const { columnCount, rowCount } = model;
for (let i = 0; i < selectedRanges.length; i += 1) {
const range = selectedRanges[i];
if (
(range.endColumn != null && range.endColumn >= columnCount) ||
(range.endRow != null && range.endRow >= rowCount)
) {
// Just clear the selection rather than trying to trim it.
this.setState({ selectedRanges: [], lastSelectedRanges: [] });
return false;
}
}
return true;
}
/**
* Clears all selected ranges
*/
clearSelectedRanges(): void {
const { selectedRanges } = this.state;
this.setState({ selectedRanges: [], lastSelectedRanges: selectedRanges });
}
/** Clears all but the last selected range */
trimSelectedRanges(): void {
const { selectedRanges } = this.state;
if (selectedRanges.length > 0) {
this.setState({
selectedRanges: selectedRanges.slice(selectedRanges.length - 1),
});
}
}
/** Gets the selected ranges */
getSelectedRanges(): readonly GridRange[] {
const { selectedRanges } = this.state;
return selectedRanges;
}
/**
* Begin a selection operation at the provided location
* @param column Column where the selection is beginning
* @param row Row where the selection is beginning
*/
beginSelection(column: GridRangeIndex, row: GridRangeIndex): void {
this.setState({
selectionStartColumn: column,
selectionStartRow: row,
selectionEndColumn: column,
selectionEndRow: row,
cursorColumn: column,
cursorRow: row,
});
}