-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathtable.tsx
2288 lines (1973 loc) · 87.1 KB
/
table.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
/*
* Copyright 2016 Palantir Technologies, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import classNames from "classnames";
import * as React from "react";
import { polyfill } from "react-lifecycles-compat";
import {
AbstractComponent2,
DISPLAYNAME_PREFIX,
Hotkey,
Hotkeys,
HotkeysTarget,
Props,
IRef,
Utils as CoreUtils,
} from "@blueprintjs/core";
import { ICellProps } from "./cell/cell";
import { Column, IColumnProps } from "./column";
import { IFocusedCellCoordinates } from "./common/cell";
import * as Classes from "./common/classes";
import { Clipboard } from "./common/clipboard";
import { columnInteractionBarContextTypes, IColumnInteractionBarContextTypes } from "./common/context";
import { Direction } from "./common/direction";
import * as Errors from "./common/errors";
import { Grid, ICellMapper, IColumnIndices, IRowIndices } from "./common/grid";
import * as FocusedCellUtils from "./common/internal/focusedCellUtils";
import * as ScrollUtils from "./common/internal/scrollUtils";
import * as SelectionUtils from "./common/internal/selectionUtils";
import { Rect } from "./common/rect";
import { RenderMode } from "./common/renderMode";
import { Utils } from "./common/utils";
import { ColumnHeader, IColumnWidths } from "./headers/columnHeader";
import { ColumnHeaderCell, IColumnHeaderCellProps } from "./headers/columnHeaderCell";
import { IRowHeaderRenderer, IRowHeights, renderDefaultRowHeader, RowHeader } from "./headers/rowHeader";
import { IContextMenuRenderer } from "./interactions/menus";
import { IIndexedResizeCallback } from "./interactions/resizable";
import { ResizeSensor } from "./interactions/resizeSensor";
import { ISelectedRegionTransform } from "./interactions/selectable";
import { GuideLayer } from "./layers/guides";
import { IRegionStyler, RegionLayer } from "./layers/regions";
import { Locator } from "./locator";
import { QuadrantType } from "./quadrants/tableQuadrant";
import { TableQuadrantStack } from "./quadrants/tableQuadrantStack";
import {
ColumnLoadingOption,
IRegion,
IStyledRegionGroup,
RegionCardinality,
Regions,
SelectionModes,
TableLoadingOption,
} from "./regions";
import { TableBody } from "./tableBody";
export interface IResizeRowsByApproximateHeightOptions {
/**
* Approximate width (in pixels) of an average character of text.
*/
getApproximateCharWidth?: number | ICellMapper<number>;
/**
* Approximate height (in pixels) of an average line of text.
*/
getApproximateLineHeight?: number | ICellMapper<number>;
/**
* Sum of horizontal paddings (in pixels) from the left __and__ right sides
* of the cell.
*/
getCellHorizontalPadding?: number | ICellMapper<number>;
/**
* Number of extra lines to add in case the calculation is imperfect.
*/
getNumBufferLines?: number | ICellMapper<number>;
}
interface IResizeRowsByApproximateHeightResolvedOptions {
getApproximateCharWidth?: number;
getApproximateLineHeight?: number;
getCellHorizontalPadding?: number;
getNumBufferLines?: number;
}
// eslint-disable-next-line deprecation/deprecation
export type TableProps = ITableProps;
/** @deprecated use TableProps */
export interface ITableProps extends Props, IRowHeights, IColumnWidths {
/**
* The children of a `Table` component, which must be React elements
* that use `IColumnProps`.
*/
children?: React.ReactElement<IColumnProps> | Array<React.ReactElement<IColumnProps>>;
/**
* A sparse number array with a length equal to the number of columns. Any
* non-null value will be used to set the width of the column at the same
* index. Note that if you want to update these values when the user
* drag-resizes a column, you may define a callback for `onColumnWidthChanged`.
*/
columnWidths?: Array<number | null | undefined>;
/**
* An optional callback for displaying a context menu when right-clicking
* on the table body. The callback is supplied with an array of
* `IRegion`s. If the mouse click was on a selection, the array will
* contain all selected regions. Otherwise it will have one `IRegion` that
* represents the clicked cell.
*/
bodyContextMenuRenderer?: IContextMenuRenderer;
/**
* If `true`, adds an interaction bar on top of all column header cells, and
* moves interaction triggers into it.
*
* @default false
*/
enableColumnInteractionBar?: boolean;
/**
* If `false`, disables reordering of columns.
*
* @default false
*/
enableColumnReordering?: boolean;
/**
* If `false`, disables resizing of columns.
*
* @default true
*/
enableColumnResizing?: boolean;
/**
* If `true`, there will be a single "focused" cell at all times,
* which can be used to interact with the table as though it is a
* spreadsheet. When false, no such cell will exist.
*
* @default false
*/
enableFocusedCell?: boolean;
/**
* If `true`, empty space in the table container will be filled with empty
* cells instead of a blank background.
*
* @default false
*/
enableGhostCells?: boolean;
/**
* If `false`, only a single region of a single column/row/cell may be
* selected at one time. Using `ctrl` or `meta` key will have no effect,
* and a mouse drag will select the current column/row/cell only.
*
* @default true
*/
enableMultipleSelection?: boolean;
/**
* If `false`, hides the row headers and settings menu.
*
* @default true
*/
enableRowHeader?: boolean;
/**
* If `false`, disables reordering of rows.
*
* @default false
*/
enableRowReordering?: boolean;
/**
* If `false`, disables resizing of rows.
*
* @default true
*/
enableRowResizing?: boolean;
/**
* If defined, will set the focused cell state. This changes
* the focused cell to controlled mode, meaning you are in charge of
* setting the focus in response to events in the `onFocusedCell` callback.
*/
focusedCell?: IFocusedCellCoordinates;
/**
* If `true`, selection state changes will cause the component to re-render.
* If `false`, selection state is ignored when deciding to re-render.
*
* @default false
*/
forceRerenderOnSelectionChange?: boolean;
/**
* If defined, this callback will be invoked for each cell when the user
* attempts to copy a selection via `mod+c`. The returned data will be copied
* to the clipboard and need not match the display value of the `<Cell>`.
* The data will be invisibly added as `textContent` into the DOM before
* copying. If not defined, keyboard copying via `mod+c` will be disabled.
*/
getCellClipboardData?: (row: number, col: number) => any;
/**
* A list of `TableLoadingOption`. Set this prop to specify whether to
* render the loading state for the column header, row header, and body
* sections of the table.
*/
loadingOptions?: TableLoadingOption[];
/**
* The number of columns to freeze to the left side of the table, counting
* from the leftmost column.
*
* @default 0
*/
numFrozenColumns?: number;
/**
* The number of rows to freeze to the top of the table, counting from the
* topmost row.
*
* @default 0
*/
numFrozenRows?: number;
/**
* The number of rows in the table.
*/
numRows?: number;
/**
* If reordering is enabled, this callback will be invoked when the user finishes
* drag-reordering one or more columns.
*/
onColumnsReordered?: (oldIndex: number, newIndex: number, length: number) => void;
/**
* If resizing is enabled, this callback will be invoked when the user
* finishes drag-resizing a column.
*/
onColumnWidthChanged?: IIndexedResizeCallback;
/**
* An optional callback invoked when all cells in view have completely rendered.
* Will be invoked on initial mount and whenever cells update (e.g., on scroll).
*/
onCompleteRender?: () => void;
/**
* If you want to do something after the copy or if you want to notify the
* user if a copy fails, you may provide this optional callback.
*
* Due to browser limitations, the copy can fail. This usually occurs if
* the selection is too large, like 20,000+ cells. The copy will also fail
* if the browser does not support the copy method (see
* `Clipboard.isCopySupported`).
*/
onCopy?: (success: boolean) => void;
/**
* A callback called when the focus is changed in the table.
*/
onFocusedCell?: (focusedCell: IFocusedCellCoordinates) => void;
/**
* If resizing is enabled, this callback will be invoked when the user
* finishes drag-resizing a row.
*/
onRowHeightChanged?: IIndexedResizeCallback;
/**
* If reordering is enabled, this callback will be invoked when the user finishes
* drag-reordering one or more rows.
*/
onRowsReordered?: (oldIndex: number, newIndex: number, length: number) => void;
/**
* A callback called when the selection is changed in the table.
*/
onSelection?: (selectedRegions: IRegion[]) => void;
/**
* A callback called when the visible cell indices change in the table.
*/
onVisibleCellsChange?: (rowIndices: IRowIndices, columnIndices: IColumnIndices) => void;
/**
* Dictates how cells should be rendered. Supported modes are:
* - `RenderMode.BATCH`: renders cells in batches to improve performance
* - `RenderMode.BATCH_ON_UPDATE`: renders cells synchronously on mount and
* in batches on update
* - `RenderMode.NONE`: renders cells synchronously all at once
*
* @default RenderMode.BATCH_ON_UPDATE
*/
renderMode?: RenderMode;
/**
* Render each row's header cell.
*/
rowHeaderCellRenderer?: IRowHeaderRenderer;
/**
* A sparse number array with a length equal to the number of rows. Any
* non-null value will be used to set the height of the row at the same
* index. Note that if you want to update these values when the user
* drag-resizes a row, you may define a callback for `onRowHeightChanged`.
*/
rowHeights?: Array<number | null | undefined>;
/**
* If defined, will set the selected regions in the cells. If defined, this
* changes table selection to controlled mode, meaning you in charge of
* setting the selections in response to events in the `onSelection`
* callback.
*
* Note that the `selectionModes` prop controls which types of events are
* triggered to the `onSelection` callback, but does not restrict what
* selection you can pass to the `selectedRegions` prop. Therefore you can,
* for example, convert cell clicks into row selections.
*/
selectedRegions?: IRegion[];
/**
* An optional transform function that will be applied to the located
* `Region`.
*
* This allows you to, for example, convert cell `Region`s into row
* `Region`s while maintaining the existing multi-select and meta-click
* functionality.
*/
selectedRegionTransform?: ISelectedRegionTransform;
/**
* A `SelectionModes` enum value indicating the selection mode. You may
* equivalently provide an array of `RegionCardinality` enum values for
* precise configuration.
*
* The `SelectionModes` enum values are:
* - `ALL`
* - `NONE`
* - `COLUMNS_AND_CELLS`
* - `COLUMNS_ONLY`
* - `ROWS_AND_CELLS`
* - `ROWS_ONLY`
*
* The `RegionCardinality` enum values are:
* - `FULL_COLUMNS`
* - `FULL_ROWS`
* - `FULL_TABLE`
* - `CELLS`
*
* @default SelectionModes.ALL
*/
selectionModes?: RegionCardinality[];
/**
* Styled region groups are rendered as overlays above the table and are
* marked with their own `className` for custom styling.
*/
styledRegionGroups?: IStyledRegionGroup[];
}
export interface ITableState {
/**
* An array of column widths. These are initialized from the column props
* and updated when the user drags column header resize handles.
*/
columnWidths?: number[];
/**
* The coordinates of the currently focused table cell
*/
focusedCell?: IFocusedCellCoordinates;
/**
* An array of pixel offsets for resize guides, which are drawn over the
* table body when a row is being resized.
*/
horizontalGuides?: number[];
/**
* If `true`, will disable updates that will cause re-renders of children
* components. This is used, for example, to disable layout updates while
* the user is dragging a resize handle.
*/
isLayoutLocked?: boolean;
/**
* Whether the user is currently dragging to reorder one or more elements.
* Can be referenced to toggle the reordering-cursor overlay, which
* displays a `grabbing` CSS cursor wherever the mouse moves in the table
* for the duration of the dragging interaction.
*/
isReordering?: boolean;
/**
* The number of frozen columns, clamped to [0, num <Column>s].
*/
numFrozenColumnsClamped?: number;
/**
* The number of frozen rows, clamped to [0, numRows].
*/
numFrozenRowsClamped?: number;
/**
* An array of row heights. These are initialized updated when the user
* drags row header resize handles.
*/
rowHeights?: number[];
/**
* An array of Regions representing the selections of the table.
*/
selectedRegions?: IRegion[];
/**
* An array of pixel offsets for resize guides, which are drawn over the
* table body when a column is being resized.
*/
verticalGuides?: number[];
/**
* The `Rect` bounds of the viewport used to perform virtual viewport
* performance enhancements.
*/
viewportRect?: Rect;
columnIdToIndex: { [key: string]: number };
childrenArray: Array<React.ReactElement<IColumnProps>>;
}
export interface ITableSnapshot {
nextScrollTop?: number;
nextScrollLeft?: number;
}
// HACKHACK(adahiya): fix for Blueprint 4.0
// eslint-disable-next-line deprecation/deprecation
@HotkeysTarget
@polyfill
export class Table extends AbstractComponent2<TableProps, ITableState, ITableSnapshot> {
public static displayName = `${DISPLAYNAME_PREFIX}.Table`;
public static defaultProps: TableProps = {
defaultColumnWidth: 150,
defaultRowHeight: 20,
enableFocusedCell: false,
enableGhostCells: false,
enableMultipleSelection: true,
enableRowHeader: true,
forceRerenderOnSelectionChange: false,
loadingOptions: [],
minColumnWidth: 50,
minRowHeight: 20,
numFrozenColumns: 0,
numFrozenRows: 0,
numRows: 0,
renderMode: RenderMode.BATCH_ON_UPDATE,
rowHeaderCellRenderer: renderDefaultRowHeader,
selectionModes: SelectionModes.ALL,
};
public static childContextTypes: React.ValidationMap<IColumnInteractionBarContextTypes> = columnInteractionBarContextTypes;
public static getDerivedStateFromProps(props: TableProps, state: ITableState) {
const {
children,
defaultColumnWidth,
defaultRowHeight,
enableFocusedCell,
focusedCell,
numRows,
selectedRegions,
selectionModes,
} = props;
// assign values from state if uncontrolled
let { columnWidths, rowHeights } = props;
if (columnWidths == null) {
columnWidths = state.columnWidths;
}
if (rowHeights == null) {
rowHeights = state.rowHeights;
}
const newChildrenArray = React.Children.toArray(children) as Array<React.ReactElement<IColumnProps>>;
const didChildrenChange = newChildrenArray !== state.childrenArray;
const numCols = newChildrenArray.length;
let newColumnWidths = columnWidths;
if (columnWidths !== state.columnWidths || didChildrenChange) {
// Try to maintain widths of columns by looking up the width of the
// column that had the same `ID` prop. If none is found, use the
// previous width at the same index.
const previousColumnWidths = newChildrenArray.map(
(child: React.ReactElement<IColumnProps>, index: number) => {
const mappedIndex = state.columnIdToIndex[child.props.id];
return state.columnWidths[mappedIndex != null ? mappedIndex : index];
},
);
// Make sure the width/height arrays have the correct length, but keep
// as many existing widths/heights as possible. Also, apply the
// sparse width/heights from props.
newColumnWidths = Utils.arrayOfLength(newColumnWidths, numCols, defaultColumnWidth);
newColumnWidths = Utils.assignSparseValues(newColumnWidths, previousColumnWidths);
newColumnWidths = Utils.assignSparseValues(newColumnWidths, columnWidths);
}
let newRowHeights = rowHeights;
if (rowHeights !== state.rowHeights || numRows !== state.rowHeights.length) {
newRowHeights = Utils.arrayOfLength(newRowHeights, numRows, defaultRowHeight);
newRowHeights = Utils.assignSparseValues(newRowHeights, rowHeights);
}
let newSelectedRegions = selectedRegions;
if (selectedRegions == null) {
// if we're in uncontrolled mode, filter out all selected regions that don't
// fit in the current new table dimensions
newSelectedRegions = state.selectedRegions.filter(region => {
const regionCardinality = Regions.getRegionCardinality(region);
return (
Table.isSelectionModeEnabled(props, regionCardinality, selectionModes) &&
Regions.isRegionValidForTable(region, numRows, numCols)
);
});
}
const newFocusedCell = FocusedCellUtils.getInitialFocusedCell(
enableFocusedCell,
focusedCell,
state.focusedCell,
newSelectedRegions,
);
const nextState = {
childrenArray: newChildrenArray,
columnIdToIndex: didChildrenChange ? Table.createColumnIdIndex(newChildrenArray) : state.columnIdToIndex,
columnWidths: newColumnWidths,
focusedCell: newFocusedCell,
numFrozenColumnsClamped: clampNumFrozenColumns(props),
numFrozenRowsClamped: clampNumFrozenRows(props),
rowHeights: newRowHeights,
selectedRegions: newSelectedRegions,
};
if (!CoreUtils.deepCompareKeys(state, nextState, Table.SHALLOW_COMPARE_STATE_KEYS_DENYLIST)) {
return nextState;
}
return null;
}
// these default values for `resizeRowsByApproximateHeight` have been
// fine-tuned to work well with default Table font styles.
private static resizeRowsByApproximateHeightDefaults: Record<
keyof IResizeRowsByApproximateHeightOptions,
number
> = {
getApproximateCharWidth: 8,
getApproximateLineHeight: 18,
getCellHorizontalPadding: 2 * Locator.CELL_HORIZONTAL_PADDING,
getNumBufferLines: 1,
};
private static SHALLOW_COMPARE_PROP_KEYS_DENYLIST = [
"selectedRegions", // (intentionally omitted; can be deeply compared to save on re-renders in controlled mode)
] as Array<keyof TableProps>;
private static SHALLOW_COMPARE_STATE_KEYS_DENYLIST = [
"selectedRegions", // (intentionally omitted; can be deeply compared to save on re-renders in uncontrolled mode)
"viewportRect",
] as Array<keyof ITableState>;
private static createColumnIdIndex(children: Array<React.ReactElement<any>>) {
const columnIdToIndex: { [key: string]: number } = {};
for (let i = 0; i < children.length; i++) {
const key = children[i].props.id;
if (key != null) {
columnIdToIndex[String(key)] = i;
}
}
return columnIdToIndex;
}
private static isSelectionModeEnabled(
props: TableProps,
selectionMode: RegionCardinality,
selectionModes = props.selectionModes,
) {
const { children, numRows } = props;
const numColumns = React.Children.count(children);
return selectionModes.indexOf(selectionMode) >= 0 && numRows > 0 && numColumns > 0;
}
public grid: Grid;
public locator: Locator;
private resizeSensorDetach: () => void;
private refHandlers = {
cellContainer: (ref: HTMLElement) => (this.cellContainerElement = ref),
columnHeader: (ref: HTMLElement) => (this.columnHeaderElement = ref),
quadrantStack: (ref: TableQuadrantStack) => (this.quadrantStackInstance = ref),
rootTable: (ref: HTMLElement) => (this.rootTableElement = ref),
rowHeader: (ref: HTMLElement) => (this.rowHeaderElement = ref),
scrollContainer: (ref: HTMLElement) => (this.scrollContainerElement = ref),
};
private cellContainerElement: HTMLElement;
private columnHeaderElement: HTMLElement;
private quadrantStackInstance: TableQuadrantStack;
private rootTableElement: HTMLElement;
private rowHeaderElement: HTMLElement;
private scrollContainerElement: HTMLElement;
/*
* This value is set to `true` when all cells finish mounting for the first
* time. It serves as a signal that we can switch to batch rendering.
*/
private didCompletelyMount = false;
public constructor(props: TableProps, context?: any) {
super(props, context);
const { children, columnWidths, defaultRowHeight, defaultColumnWidth, numRows, rowHeights } = this.props;
const childrenArray = React.Children.toArray(children) as Array<React.ReactElement<IColumnProps>>;
const columnIdToIndex = Table.createColumnIdIndex(childrenArray);
// Create height/width arrays using the lengths from props and
// children, the default values from props, and finally any sparse
// arrays passed into props.
let newColumnWidths = childrenArray.map(() => defaultColumnWidth);
newColumnWidths = Utils.assignSparseValues(newColumnWidths, columnWidths);
let newRowHeights = Utils.times(numRows, () => defaultRowHeight);
newRowHeights = Utils.assignSparseValues(newRowHeights, rowHeights);
const selectedRegions = props.selectedRegions == null ? ([] as IRegion[]) : props.selectedRegions;
const focusedCell = FocusedCellUtils.getInitialFocusedCell(
props.enableFocusedCell,
props.focusedCell,
undefined,
selectedRegions,
);
this.state = {
childrenArray,
columnIdToIndex,
columnWidths: newColumnWidths,
focusedCell,
isLayoutLocked: false,
isReordering: false,
numFrozenColumnsClamped: clampNumFrozenColumns(props),
numFrozenRowsClamped: clampNumFrozenRows(props),
rowHeights: newRowHeights,
selectedRegions,
};
}
// Instance methods
// ================
/**
* __Experimental!__ Resizes all rows in the table to the approximate
* maximum height of wrapped cell content in each row. Works best when each
* cell contains plain text of a consistent font style (though font style
* may vary between cells). Since this function uses approximate
* measurements, results may not be perfect.
*
* Approximation parameters can be configured for the entire table or on a
* per-cell basis. Default values are fine-tuned to work well with default
* Table font styles.
*/
public resizeRowsByApproximateHeight(
getCellText: ICellMapper<string>,
options?: IResizeRowsByApproximateHeightOptions,
) {
const { numRows } = this.props;
const { columnWidths } = this.state;
const numColumns = columnWidths.length;
const rowHeights: number[] = [];
for (let rowIndex = 0; rowIndex < numRows; rowIndex++) {
let maxCellHeightInRow = 0;
// iterate through each cell in the row
for (let columnIndex = 0; columnIndex < numColumns; columnIndex++) {
// resolve all parameters to raw values
const {
getApproximateCharWidth: approxCharWidth,
getApproximateLineHeight: approxLineHeight,
getCellHorizontalPadding: horizontalPadding,
getNumBufferLines: numBufferLines,
} = this.resolveResizeRowsByApproximateHeightOptions(options, rowIndex, columnIndex);
const cellText = getCellText(rowIndex, columnIndex);
const approxCellHeight = Utils.getApproxCellHeight(
cellText,
columnWidths[columnIndex],
approxCharWidth,
approxLineHeight,
horizontalPadding,
numBufferLines,
);
if (approxCellHeight > maxCellHeightInRow) {
maxCellHeightInRow = approxCellHeight;
}
}
rowHeights.push(maxCellHeightInRow);
}
this.invalidateGrid();
this.setState({ rowHeights });
}
/**
* Resize all rows in the table to the height of the tallest visible cell in the specified columns.
* If no indices are provided, default to using the tallest visible cell from all columns in view.
*/
public resizeRowsByTallestCell(columnIndices?: number | number[]) {
let tallest = 0;
if (columnIndices == null) {
// Consider all columns currently in viewport
const viewportColumnIndices = this.grid.getColumnIndicesInRect(this.state.viewportRect);
for (let col = viewportColumnIndices.columnIndexStart; col <= viewportColumnIndices.columnIndexEnd; col++) {
tallest = Math.max(tallest, this.locator.getTallestVisibleCellInColumn(col));
}
} else {
const columnIndicesArray = Array.isArray(columnIndices) ? columnIndices : [columnIndices];
const tallestByColumns = columnIndicesArray.map(col => this.locator.getTallestVisibleCellInColumn(col));
tallest = Math.max(...tallestByColumns);
}
const rowHeights = Array(this.state.rowHeights.length).fill(tallest);
this.invalidateGrid();
this.setState({ rowHeights });
}
/**
* Scrolls the table to the target region in a fashion appropriate to the target region's
* cardinality:
*
* - CELLS: Scroll the top-left cell in the target region to the top-left corner of the viewport.
* - FULL_ROWS: Scroll the top-most row in the target region to the top of the viewport.
* - FULL_COLUMNS: Scroll the left-most column in the target region to the left side of the viewport.
* - FULL_TABLE: Scroll the top-left cell in the table to the top-left corner of the viewport.
*
* If there are active frozen rows and/or columns, the target region will be positioned in the
* top-left corner of the non-frozen area (unless the target region itself is in the frozen
* area).
*
* If the target region is close to the bottom-right corner of the table, this function will
* simply scroll the target region as close to the top-left as possible until the bottom-right
* corner is reached.
*/
public scrollToRegion(region: IRegion) {
const { numFrozenColumnsClamped: numFrozenColumns, numFrozenRowsClamped: numFrozenRows } = this.state;
const { left: currScrollLeft, top: currScrollTop } = this.state.viewportRect;
const { scrollLeft, scrollTop } = ScrollUtils.getScrollPositionForRegion(
region,
currScrollLeft,
currScrollTop,
this.grid.getCumulativeWidthBefore,
this.grid.getCumulativeHeightBefore,
numFrozenRows,
numFrozenColumns,
);
const correctedScrollLeft = this.shouldDisableHorizontalScroll() ? 0 : scrollLeft;
const correctedScrollTop = this.shouldDisableVerticalScroll() ? 0 : scrollTop;
// defer to the quadrant stack to keep all quadrant positions in sync
this.quadrantStackInstance.scrollToPosition(correctedScrollLeft, correctedScrollTop);
}
// React lifecycle
// ===============
public getChildContext(): IColumnInteractionBarContextTypes {
return {
enableColumnInteractionBar: this.props.enableColumnInteractionBar,
};
}
public shouldComponentUpdate(nextProps: TableProps, nextState: ITableState) {
const propKeysDenylist = { exclude: Table.SHALLOW_COMPARE_PROP_KEYS_DENYLIST };
const stateKeysDenylist = { exclude: Table.SHALLOW_COMPARE_STATE_KEYS_DENYLIST };
return (
!CoreUtils.shallowCompareKeys(this.props, nextProps, propKeysDenylist) ||
!CoreUtils.shallowCompareKeys(this.state, nextState, stateKeysDenylist) ||
!CoreUtils.deepCompareKeys(this.props, nextProps, Table.SHALLOW_COMPARE_PROP_KEYS_DENYLIST) ||
!CoreUtils.deepCompareKeys(this.state, nextState, Table.SHALLOW_COMPARE_STATE_KEYS_DENYLIST)
);
}
public render() {
const {
children,
className,
enableRowHeader,
loadingOptions,
numRows,
enableColumnInteractionBar,
} = this.props;
const { horizontalGuides, numFrozenColumnsClamped, numFrozenRowsClamped, verticalGuides } = this.state;
if (!this.gridDimensionsMatchProps()) {
// Ensure we're rendering the correct number of rows & columns
this.invalidateGrid();
}
this.validateGrid();
const classes = classNames(
Classes.TABLE_CONTAINER,
{
[Classes.TABLE_REORDERING]: this.state.isReordering,
[Classes.TABLE_NO_VERTICAL_SCROLL]: this.shouldDisableVerticalScroll(),
[Classes.TABLE_NO_HORIZONTAL_SCROLL]: this.shouldDisableHorizontalScroll(),
[Classes.TABLE_SELECTION_ENABLED]: Table.isSelectionModeEnabled(this.props, RegionCardinality.CELLS),
[Classes.TABLE_NO_ROWS]: numRows === 0,
},
className,
);
return (
<div className={classes} ref={this.refHandlers.rootTable} onScroll={this.handleRootScroll}>
<TableQuadrantStack
bodyRef={this.refHandlers.cellContainer}
bodyRenderer={this.renderBody}
columnHeaderCellRenderer={this.renderColumnHeader}
columnHeaderRef={this.refHandlers.columnHeader}
enableColumnInteractionBar={enableColumnInteractionBar}
enableRowHeader={enableRowHeader}
grid={this.grid}
handleColumnResizeGuide={this.handleColumnResizeGuide}
handleColumnsReordering={this.handleColumnsReordering}
handleRowResizeGuide={this.handleRowResizeGuide}
handleRowsReordering={this.handleRowsReordering}
isHorizontalScrollDisabled={this.shouldDisableHorizontalScroll()}
isVerticalScrollDisabled={this.shouldDisableVerticalScroll()}
loadingOptions={loadingOptions}
numColumns={React.Children.count(children)}
numFrozenColumns={numFrozenColumnsClamped}
numFrozenRows={numFrozenRowsClamped}
numRows={numRows}
onScroll={this.handleBodyScroll}
ref={this.refHandlers.quadrantStack}
menuRenderer={this.renderMenu}
rowHeaderCellRenderer={this.renderRowHeader}
rowHeaderRef={this.refHandlers.rowHeader}
scrollContainerRef={this.refHandlers.scrollContainer}
/>
<div className={classNames(Classes.TABLE_OVERLAY_LAYER, Classes.TABLE_OVERLAY_REORDERING_CURSOR)} />
<GuideLayer
className={Classes.TABLE_RESIZE_GUIDES}
verticalGuides={verticalGuides}
horizontalGuides={horizontalGuides}
/>
</div>
);
}
public renderHotkeys() {
const hotkeys = [
this.maybeRenderCopyHotkey(),
this.maybeRenderSelectAllHotkey(),
this.maybeRenderFocusHotkeys(),
this.maybeRenderSelectionResizeHotkeys(),
];
return <Hotkeys>{hotkeys.filter(element => element !== undefined)}</Hotkeys>;
}
/**
* When the component mounts, the HTML Element refs will be available, so
* we constructor the Locator, which queries the elements' bounding
* ClientRects.
*/
public componentDidMount() {
this.validateGrid();
this.locator = new Locator(this.rootTableElement, this.scrollContainerElement, this.cellContainerElement);
this.updateLocator();
this.updateViewportRect(this.locator.getViewportRect());
this.resizeSensorDetach = ResizeSensor.attach(this.rootTableElement, () => {
if (!this.state.isLayoutLocked) {
this.updateViewportRect(this.locator.getViewportRect());
}
});
}
public componentWillUnmount() {
if (this.resizeSensorDetach != null) {
this.resizeSensorDetach();
delete this.resizeSensorDetach;
}
this.didCompletelyMount = false;
}
public getSnapshotBeforeUpdate() {
const { viewportRect } = this.state;
this.validateGrid();
const tableBottom = this.grid.getCumulativeHeightAt(this.grid.numRows - 1);
const tableRight = this.grid.getCumulativeWidthAt(this.grid.numCols - 1);
const nextScrollTop =
tableBottom < viewportRect.top + viewportRect.height
? // scroll the last row into view
Math.max(0, tableBottom - viewportRect.height)
: undefined;
const nextScrollLeft =
tableRight < viewportRect.left + viewportRect.width
? // scroll the last column into view
Math.max(0, tableRight - viewportRect.width)
: undefined;
// these will only be defined if they differ from viewportRect
return { nextScrollLeft, nextScrollTop };
}
public componentDidUpdate(prevProps: TableProps, prevState: ITableState, snapshot: ITableSnapshot) {
super.componentDidUpdate(prevProps, prevState, snapshot);
const didChildrenChange =
(React.Children.toArray(this.props.children) as Array<React.ReactElement<IColumnProps>>) !==
this.state.childrenArray;
const shouldInvalidateGrid =
didChildrenChange ||
this.props.columnWidths !== prevState.columnWidths ||
this.props.rowHeights !== prevState.rowHeights ||
this.props.numRows !== prevProps.numRows ||
(this.props.forceRerenderOnSelectionChange && this.props.selectedRegions !== prevProps.selectedRegions);
if (shouldInvalidateGrid) {
this.invalidateGrid();
}
if (this.locator != null) {
this.validateGrid();
this.updateLocator();
}
// When true, we'll need to imperatively synchronize quadrant views after
// the update. This check lets us avoid expensively diff'ing columnWidths
// and rowHeights in <TableQuadrantStack> on each update.
const didUpdateColumnOrRowSizes =
!CoreUtils.arraysEqual(this.state.columnWidths, prevState.columnWidths) ||
!CoreUtils.arraysEqual(this.state.rowHeights, prevState.rowHeights);
if (didUpdateColumnOrRowSizes) {
this.quadrantStackInstance.synchronizeQuadrantViews();
this.syncViewportPosition(snapshot);
}
}
protected validateProps(props: TableProps) {
const { children, columnWidths, numFrozenColumns, numFrozenRows, numRows, rowHeights } = props;
const numColumns = React.Children.count(children);
// do cheap error-checking first.
if (numRows != null && numRows < 0) {
throw new Error(Errors.TABLE_NUM_ROWS_NEGATIVE);
}
if (numFrozenRows != null && numFrozenRows < 0) {
throw new Error(Errors.TABLE_NUM_FROZEN_ROWS_NEGATIVE);
}
if (numFrozenColumns != null && numFrozenColumns < 0) {