/
mutableTable.tsx
1124 lines (1001 loc) · 40.3 KB
/
mutableTable.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 2017 Palantir Technologies, Inc. All rights reserved.
*
* Licensed under the terms of the LICENSE file distributed with this project.
*/
import {
Button,
Classes,
FocusStyleManager,
IButtonProps,
Intent,
Menu,
MenuDivider,
MenuItem,
Switch,
} from "@blueprintjs/core";
import classNames from "classnames";
import * as React from "react";
import {
Cell,
Column,
ColumnHeaderCell,
EditableCell,
EditableName,
IStyledRegionGroup,
JSONFormat,
RegionCardinality,
Regions,
RowHeaderCell,
Table,
TableLoadingOption,
TruncatedFormat,
TruncatedPopoverMode,
Utils,
} from "@blueprintjs/table/src";
import { IFocusedCellCoordinates } from "@blueprintjs/table/src/common/cell";
import { IColumnIndices, IRowIndices } from "@blueprintjs/table/src/common/grid";
import { RenderMode } from "@blueprintjs/table/src/common/renderMode";
import { IRegion } from "@blueprintjs/table/src/regions";
import { DenseGridMutableStore } from "./denseGridMutableStore";
import { LocalStore } from "./localStore";
import { SlowLayoutStack } from "./slowLayoutStack";
export enum FocusStyle {
TAB = "tab",
TAB_OR_CLICK = "tab-or-click",
}
export enum CellContent {
EMPTY = "empty",
CELL_NAMES = "cell-names",
LONG_TEXT = "long-text",
LARGE_JSON = "large-json",
}
type IMutableStateUpdateCallback = (
stateKey: keyof IMutableTableState,
) => ((event: React.FormEvent<HTMLElement>) => void);
const COLUMN_COUNTS = [0, 1, 5, 20, 100, 1000];
const ROW_COUNTS = [0, 1, 5, 20, 100, 1000, 100000];
const FROZEN_COLUMN_COUNTS = [0, 1, 2, 5, 20, 100, 1000];
const FROZEN_ROW_COUNTS = [0, 1, 2, 5, 20, 100, 1000];
const REGION_CARDINALITIES: RegionCardinality[] = [
RegionCardinality.CELLS,
RegionCardinality.FULL_ROWS,
RegionCardinality.FULL_COLUMNS,
RegionCardinality.FULL_TABLE,
];
const RENDER_MODES: RenderMode[] = [RenderMode.BATCH_ON_UPDATE, RenderMode.BATCH, RenderMode.NONE];
const CELL_CONTENTS: CellContent[] = [
CellContent.EMPTY,
CellContent.CELL_NAMES,
CellContent.LONG_TEXT,
CellContent.LARGE_JSON,
];
const TRUNCATED_POPOVER_MODES: TruncatedPopoverMode[] = [
TruncatedPopoverMode.ALWAYS,
TruncatedPopoverMode.NEVER,
TruncatedPopoverMode.WHEN_TRUNCATED,
TruncatedPopoverMode.WHEN_TRUNCATED_APPROX,
];
const TRUNCATION_LENGTHS: number[] = [20, 80, 100, 1000];
const TRUNCATION_LENGTH_DEFAULT_INDEX = 1;
const SLOW_LAYOUT_STACK_DEPTH = 120;
const COLUMN_COUNT_DEFAULT_INDEX = 3;
const ROW_COUNT_DEFAULT_INDEX = 4;
const FROZEN_COLUMN_COUNT_DEFAULT_INDEX = 0;
const FROZEN_ROW_COUNT_DEFAULT_INDEX = 0;
const LONG_TEXT_MIN_LENGTH = 5;
const LONG_TEXT_MAX_LENGTH = 120;
const LONG_TEXT_WORD_SPLIT_REGEXP = /.{1,5}/g;
const LARGE_JSON_PROP_COUNT = 3;
const LARGE_JSON_OBJECT_DEPTH = 2;
const CELL_CONTENT_GENERATORS: { [name: string]: (ri: number, ci: number) => string | object } = {
[CellContent.CELL_NAMES]: Utils.toBase26CellName,
[CellContent.EMPTY]: () => "",
[CellContent.LONG_TEXT]: () => {
const randomLength = getRandomInteger(LONG_TEXT_MIN_LENGTH, LONG_TEXT_MAX_LENGTH);
return getRandomString(randomLength)
.match(LONG_TEXT_WORD_SPLIT_REGEXP)
.join(" ");
},
[CellContent.LARGE_JSON]: () => {
return getRandomObject(LARGE_JSON_PROP_COUNT, LARGE_JSON_OBJECT_DEPTH);
},
};
// TODO: Pull these from @blueprintjs/docs
/** Event handler that exposes the target element's value as a boolean. */
function handleBooleanChange(handler: (checked: boolean) => void) {
return (event: React.FormEvent<HTMLElement>) => handler((event.target as HTMLInputElement).checked);
}
/** Event handler that exposes the target element's value as a string. */
function handleStringChange(handler: (value: string) => void) {
return (event: React.FormEvent<HTMLElement>) => handler((event.target as HTMLInputElement).value);
}
/** Event handler that exposes the target element's value as a number. */
function handleNumberChange(handler: (value: number) => void) {
return handleStringChange(value => handler(+value));
}
function getRandomObject(propCount: number, depth = 0): object {
const childPropCount = propCount;
const obj: any = {};
for (let i = 0; i < propCount; i++) {
obj[getRandomString(5)] = depth === 0 ? getRandomValue() : getRandomObject(childPropCount, depth - 1);
}
return obj;
}
function getRandomValue(): number | string | number[] | string[] | null {
switch (getRandomInteger(0, 4)) {
case 0:
return Math.random();
case 1:
return getRandomString(5);
case 2:
return Utils.times(5, () => Math.random());
case 3:
return Utils.times(5, () => getRandomString(5));
default:
return null;
}
}
function getRandomInteger(min: number, max: number): number {
// min and max are inclusive
return Math.floor(min + Math.random() * (max - min + 1));
}
function getRandomString(length: number): string {
let str = "";
while (str.length < length) {
str += Math.random()
.toString(36)
.substr(2);
}
return str.substr(0, length);
}
function contains(arr: any[], value: any) {
return arr.indexOf(value) >= 0;
}
export interface IMutableTableState {
cellContent?: CellContent;
cellTruncatedPopoverMode?: TruncatedPopoverMode;
cellTruncationLength?: number;
enableCellEditing?: boolean;
enableCellSelection?: boolean;
enableCellTruncation?: boolean;
enableCellTruncationFixed?: boolean;
enableCellWrap?: boolean;
enableColumnCustomHeaders?: boolean;
enableColumnNameEditing?: boolean;
enableColumnReordering?: boolean;
enableColumnResizing?: boolean;
enableColumnSelection?: boolean;
enableContextMenu?: boolean;
enableFullTableSelection?: boolean;
enableLayoutBoundary?: boolean;
enableMultiSelection?: boolean;
enableRowReordering?: boolean;
enableRowResizing?: boolean;
enableRowSelection?: boolean;
enableSlowLayout?: boolean;
numCols?: number;
numFrozenCols?: number;
numFrozenRows?: number;
numRows?: number;
renderMode?: RenderMode;
scrollToColumnIndex?: number;
scrollToRegionType?: RegionCardinality;
scrollToRowIndex?: number;
selectedFocusStyle?: FocusStyle;
showCallbackLogs?: boolean;
showCellsLoading?: boolean;
showColumnHeadersLoading?: boolean;
showColumnMenus?: boolean;
showCustomRegions?: boolean;
showFocusCell?: boolean;
showGhostCells?: boolean;
showInline?: boolean;
showRowHeaders?: boolean;
showRowHeadersLoading?: boolean;
showTableInteractionBar?: boolean;
showZebraStriping?: boolean;
}
const DEFAULT_STATE: IMutableTableState = {
cellContent: CellContent.LONG_TEXT,
cellTruncatedPopoverMode: TruncatedPopoverMode.WHEN_TRUNCATED,
cellTruncationLength: TRUNCATION_LENGTHS[TRUNCATION_LENGTH_DEFAULT_INDEX],
enableCellEditing: false,
enableCellSelection: true,
enableCellTruncation: false,
enableCellTruncationFixed: false,
enableCellWrap: false,
enableColumnCustomHeaders: true,
enableColumnNameEditing: false,
enableColumnReordering: true,
enableColumnResizing: true,
enableColumnSelection: true,
enableContextMenu: false,
enableFullTableSelection: true,
enableLayoutBoundary: false,
enableMultiSelection: true,
enableRowReordering: false,
enableRowResizing: false,
enableRowSelection: true,
enableSlowLayout: false,
numCols: COLUMN_COUNTS[COLUMN_COUNT_DEFAULT_INDEX],
numFrozenCols: FROZEN_COLUMN_COUNTS[FROZEN_COLUMN_COUNT_DEFAULT_INDEX],
numFrozenRows: FROZEN_ROW_COUNTS[FROZEN_ROW_COUNT_DEFAULT_INDEX],
numRows: ROW_COUNTS[ROW_COUNT_DEFAULT_INDEX],
renderMode: RenderMode.BATCH_ON_UPDATE,
scrollToColumnIndex: 0,
scrollToRegionType: RegionCardinality.CELLS,
scrollToRowIndex: 0,
selectedFocusStyle: FocusStyle.TAB,
showCallbackLogs: true,
showCellsLoading: false,
showColumnHeadersLoading: false,
showColumnMenus: false,
showCustomRegions: false,
showFocusCell: false,
showGhostCells: true,
showInline: false,
showRowHeaders: true,
showRowHeadersLoading: false,
showTableInteractionBar: false,
showZebraStriping: false,
};
export class MutableTable extends React.Component<{}, IMutableTableState> {
private store = new DenseGridMutableStore<any>();
private tableInstance: Table;
private stateStore: LocalStore<IMutableTableState>;
private refHandlers = {
table: (ref: Table) => (this.tableInstance = ref),
};
public constructor(props: any, context?: any) {
super(props, context);
this.stateStore = new LocalStore<IMutableTableState>("BP_TABLE_MUTABLE_TABLE_DEV_PREVIEW", true);
this.state = this.stateStore.getWithDefaults(DEFAULT_STATE);
}
// React Lifecycle
// ===============
public render() {
const layoutBoundary = this.state.enableLayoutBoundary;
return (
<div className="container">
<SlowLayoutStack
depth={SLOW_LAYOUT_STACK_DEPTH}
enabled={this.state.enableSlowLayout}
rootClassName={classNames("table", { "is-inline": this.state.showInline })}
branchClassName={"layout-passthrough-fill"}
>
<div className={layoutBoundary ? "layout-boundary" : "layout-passthrough-fill"}>
{this.renderTable()}
</div>
</SlowLayoutStack>
{this.renderSidebar()}
</div>
);
}
public componentWillMount() {
this.resetCellContent();
}
public componentDidMount() {
this.syncFocusStyle();
}
public componentWillUpdate(_nextProps: {}, nextState: IMutableTableState) {
if (
nextState.cellContent !== this.state.cellContent ||
nextState.numRows !== this.state.numRows ||
nextState.numCols !== this.state.numCols
) {
this.resetCellContent(nextState);
}
}
public componentDidUpdate() {
this.syncFocusStyle();
this.syncDependentBooleanStates();
this.stateStore.set(this.state);
}
// Generators
// ==========
private generateColumnKey = () => {
return Math.random()
.toString(36)
.substring(7);
};
// Renderers
// =========
private renderTable() {
return (
<Table
bodyContextMenuRenderer={this.renderBodyContextMenu}
enableColumnInteractionBar={this.state.showTableInteractionBar}
enableColumnReordering={this.state.enableColumnReordering}
enableColumnResizing={this.state.enableColumnResizing}
enableFocusedCell={this.state.showFocusCell}
enableGhostCells={this.state.showGhostCells}
enableMultipleSelection={this.state.enableMultiSelection}
enableRowHeader={this.state.showRowHeaders}
enableRowReordering={this.state.enableRowReordering}
enableRowResizing={this.state.enableRowResizing}
getCellClipboardData={this.getCellValue}
loadingOptions={this.getEnabledLoadingOptions()}
numFrozenColumns={this.state.numFrozenCols}
numFrozenRows={this.state.numFrozenRows}
numRows={this.state.numRows}
onColumnsReordered={this.onColumnsReordered}
onColumnWidthChanged={this.onColumnWidthChanged}
onCompleteRender={this.onCompleteRender}
onCopy={this.onCopy}
onFocusedCell={this.onFocus}
onRowHeightChanged={this.onRowHeightChanged}
onRowsReordered={this.onRowsReordered}
onSelection={this.onSelection}
onVisibleCellsChange={this.onVisibleCellsChange}
ref={this.refHandlers.table}
renderMode={this.state.renderMode}
rowHeaderCellRenderer={this.renderRowHeader}
selectionModes={this.getEnabledSelectionModes()}
styledRegionGroups={this.getStyledRegionGroups()}
>
{this.renderColumns()}
</Table>
);
}
private renderColumns() {
return Utils.times(this.state.numCols, columnIndex => {
return (
<Column
key={this.store.getColumnKey(columnIndex)}
columnHeaderCellRenderer={this.renderColumnHeaderCell}
cellRenderer={this.renderCell}
/>
);
});
}
private renderColumnHeaderCell = (columnIndex: number) => {
return (
<ColumnHeaderCell
index={columnIndex}
name={this.store.getColumnName(columnIndex)}
menuRenderer={this.state.showColumnMenus ? this.renderColumnMenu : undefined}
nameRenderer={this.getColumnNameRenderer()}
/>
);
};
private getColumnNameRenderer = () => {
if (this.state.enableColumnCustomHeaders) {
return this.renderCustomColumnName;
} else if (this.state.enableColumnNameEditing) {
return this.renderEditableColumnName;
} else {
return undefined;
}
};
private renderCustomColumnName = (name: string, index: number) => {
// show taller, multi-line column names after an arbitrary threshold
// just to allow us to check if column headers resize appropriately.
const COLUMN_Z_INDEX = 25; // 0-indexed
const maybeMultilineName =
index > COLUMN_Z_INDEX ? [<span key="1">{name}</span>, <br key="2" />, <span key="3">{name}</span>] : name;
return (
<div className="tbl-custom-column-header">
<div className="tbl-custom-column-header-name">{maybeMultilineName}</div>
<div className="tbl-custom-column-header-type">string</div>
</div>
);
};
private renderEditableColumnName = (name: string) => {
return <EditableName name={name == null ? "" : name} onConfirm={this.handleEditableColumnCellConfirm} />;
};
private renderColumnMenu = (columnIndex: number) => {
// tslint:disable:jsx-no-multiline-js jsx-no-lambda
const menu = (
<Menu>
<MenuItem
icon="insert"
onClick={() => {
this.store.addColumnBefore(columnIndex);
this.setState({ numCols: this.state.numCols + 1 });
}}
text="Insert column before"
/>
<MenuItem
icon="insert"
onClick={() => {
this.store.addColumnAfter(columnIndex);
this.setState({ numCols: this.state.numCols + 1 });
}}
text="Insert column after"
/>
<MenuItem
icon="remove"
onClick={() => {
this.store.removeColumn(columnIndex);
this.setState({ numCols: this.state.numCols - 1 });
}}
text="Remove column"
/>
</Menu>
);
return this.state.showColumnMenus ? menu : undefined;
};
private renderRowHeader = (rowIndex: number) => {
return <RowHeaderCell index={rowIndex} name={`${rowIndex + 1}`} menuRenderer={this.renderRowMenu} />;
};
private renderRowMenu = (rowIndex: number) => {
return (
<Menu>
<MenuItem
icon="insert"
onClick={() => {
this.store.addRowBefore(rowIndex);
this.setState({ numRows: this.state.numRows + 1 });
}}
text="Insert row before"
/>
<MenuItem
icon="insert"
onClick={() => {
this.store.addRowAfter(rowIndex);
this.setState({ numRows: this.state.numRows + 1 });
}}
text="Insert row after"
/>
<MenuItem
icon="remove"
onClick={() => {
this.store.removeRow(rowIndex);
this.setState({ numRows: this.state.numRows - 1 });
}}
text="Remove row"
/>
</Menu>
);
// tslint:enable:jsx-no-multiline-js jsx-no-lambda
};
private getCellValue = (rowIndex: number, columnIndex: number) => {
return this.store.get(rowIndex, columnIndex);
};
private renderCell = (rowIndex: number, columnIndex: number) => {
const value = this.store.get(rowIndex, columnIndex);
const valueAsString = value == null ? "" : value;
const isEvenRow = rowIndex % 2 === 0;
const classes = classNames({ "tbl-zebra-stripe": this.state.showZebraStriping && isEvenRow });
if (this.state.enableCellEditing) {
return (
<EditableCell
className={classes}
columnIndex={columnIndex}
loading={this.state.showCellsLoading}
onConfirm={this.handleEditableBodyCellConfirm}
rowIndex={rowIndex}
value={valueAsString}
/>
);
} else if (this.state.cellContent === CellContent.LARGE_JSON) {
return (
<Cell className={classes} wrapText={this.state.enableCellWrap}>
<JSONFormat
detectTruncation={this.state.enableCellTruncation}
preformatted={true}
showPopover={this.state.cellTruncatedPopoverMode}
truncateLength={1e10}
>
{valueAsString}
</JSONFormat>
</Cell>
);
} else if (this.state.enableCellTruncation) {
return (
<Cell className={classes} wrapText={this.state.enableCellWrap}>
<TruncatedFormat
detectTruncation={!this.state.enableCellTruncationFixed}
preformatted={false}
showPopover={this.state.cellTruncatedPopoverMode}
truncateLength={this.state.cellTruncationLength}
truncationSuffix="..."
>
{valueAsString}
</TruncatedFormat>
</Cell>
);
} else {
return (
<Cell
className={classes}
columnIndex={columnIndex}
rowIndex={rowIndex}
wrapText={this.state.enableCellWrap}
>
{valueAsString}
</Cell>
);
}
};
private renderSidebar() {
const renderModeMenu = this.renderSelectMenu(
"Render mode",
"renderMode",
RENDER_MODES,
this.toRenderModeLabel,
this.handleNumberStateChange,
);
const cellContentMenu = this.renderSelectMenu(
"Cell content",
"cellContent",
CELL_CONTENTS,
this.toCellContentLabel,
this.handleNumberStateChange,
);
const truncatedPopoverModeMenu = this.renderSelectMenu(
"Popover",
"cellTruncatedPopoverMode",
TRUNCATED_POPOVER_MODES,
this.toTruncatedPopoverModeLabel,
this.handleNumberStateChange,
"enableCellTruncation",
true,
);
const truncatedLengthMenu = this.renderSelectMenu(
"Length",
"cellTruncationLength",
TRUNCATION_LENGTHS,
this.toValueLabel,
this.handleNumberStateChange,
"enableCellTruncationFixed",
true,
);
return (
<div className="sidebar pt-elevation-0">
<h4>Table</h4>
<h6>Display</h6>
{this.renderSwitch("Inline", "showInline")}
{this.renderSwitch("Focus cell", "showFocusCell")}
{this.renderSwitch("Ghost cells", "showGhostCells")}
{renderModeMenu}
{this.renderSwitch("Interaction bar", "showTableInteractionBar")}
<h6>Interactions</h6>
{this.renderSwitch("Body context menu", "enableContextMenu")}
{this.renderSwitch("Callback logs", "showCallbackLogs")}
{this.renderSwitch("Full-table selection", "enableFullTableSelection")}
{this.renderSwitch("Multi-selection", "enableMultiSelection")}
<h6>Scroll to</h6>
{this.renderScrollToSection()}
<h4>Columns</h4>
<h6>Display</h6>
{this.renderNumberSelectMenu("Num. columns", "numCols", COLUMN_COUNTS)}
{this.renderNumberSelectMenu("Num. frozen columns", "numFrozenCols", FROZEN_COLUMN_COUNTS)}
{this.renderSwitch("Loading state", "showColumnHeadersLoading")}
{this.renderSwitch("Menus", "showColumnMenus")}
{this.renderSwitch("Custom headers", "enableColumnCustomHeaders")}
<h6>Interactions</h6>
{this.renderSwitch("Editing", "enableColumnNameEditing", "enableColumnCustomHeaders", false)}
{this.renderSwitch("Reordering", "enableColumnReordering")}
{this.renderSwitch("Resizing", "enableColumnResizing")}
{this.renderSwitch("Selection", "enableColumnSelection")}
<h4>Rows</h4>
<h6>Display</h6>
{this.renderNumberSelectMenu("Num. rows", "numRows", ROW_COUNTS)}
{this.renderNumberSelectMenu("Num. frozen rows", "numFrozenRows", FROZEN_ROW_COUNTS)}
{this.renderSwitch("Headers", "showRowHeaders")}
{this.renderSwitch("Loading state", "showRowHeadersLoading")}
{this.renderSwitch("Zebra striping", "showZebraStriping")}
<h6>Interactions</h6>
{this.renderSwitch("Reordering", "enableRowReordering")}
{this.renderSwitch("Resizing", "enableRowResizing")}
{this.renderSwitch("Selection", "enableRowSelection")}
<h6>Instance methods</h6>
{this.renderButton("Resize rows by tallest cell", {
onClick: this.handleResizeRowsByTallestCellButtonClick,
})}
{this.renderButton("Resize rows by approx height", {
onClick: this.handleResizeRowsByApproxHeightButtonClick,
})}
<h4>Cells</h4>
<h6>Display</h6>
{cellContentMenu}
{this.renderSwitch("Loading state", "showCellsLoading")}
{this.renderSwitch("Custom regions", "showCustomRegions")}
<h6>Interactions</h6>
{this.renderSwitch("Editing", "enableCellEditing")}
{this.renderSwitch("Selection", "enableCellSelection")}
<h6>Text Layout</h6>
{this.renderSwitch("Truncation", "enableCellTruncation", "enableCellEditing", false)}
<div className="sidebar-indented-group">{truncatedPopoverModeMenu}</div>
{this.renderSwitch("Fixed truncation", "enableCellTruncationFixed", "enableCellTruncation", true)}
<div className="sidebar-indented-group">{truncatedLengthMenu}</div>
{this.renderSwitch("Wrap text", "enableCellWrap")}
<h4>Page</h4>
<h6>Display</h6>
{this.renderFocusStyleSelectMenu()}
<h6>Perf</h6>
{this.renderSwitch("Slow layout", "enableSlowLayout")}
{this.renderSwitch("Isolate layout boundary", "enableLayoutBoundary")}
<h4>Settings</h4>
{this.renderButton("Reset all", { icon: "undo", onClick: this.handleDefaultsButtonClick })}
</div>
);
}
private renderButton(label: string, props: IButtonProps) {
return (
<Button intent={Intent.PRIMARY} className={classNames(Classes.FILL)} {...props}>
{label}
</Button>
);
}
private renderScrollToSection() {
const { scrollToRegionType } = this.state;
const scrollToRegionTypeSelectMenu = this.renderSelectMenu(
"Region type",
"scrollToRegionType",
REGION_CARDINALITIES,
this.getRegionCardinalityLabel,
this.handleRegionCardinalityChange,
);
const scrollToRowSelectMenu = this.renderSelectMenu(
"Row",
"scrollToRowIndex",
Utils.times(this.state.numRows, rowIndex => rowIndex),
rowIndex => `${rowIndex + 1}`,
this.handleNumberStateChange,
);
const scrollToColumnSelectMenu = this.renderSelectMenu(
"Column",
"scrollToColumnIndex",
Utils.times(this.state.numCols, columnIndex => columnIndex),
columnIndex => this.store.getColumnName(columnIndex),
this.handleNumberStateChange,
);
const ROW_MENU_CARDINALITIES = [RegionCardinality.CELLS, RegionCardinality.FULL_ROWS];
const COLUMN_MENU_CARDINALITIES = [RegionCardinality.CELLS, RegionCardinality.FULL_COLUMNS];
const shouldShowRowSelectMenu = contains(ROW_MENU_CARDINALITIES, scrollToRegionType);
const shouldShowColumnSelectMenu = contains(COLUMN_MENU_CARDINALITIES, scrollToRegionType);
return (
<div>
{scrollToRegionTypeSelectMenu}
<div className="sidebar-indented-group">
{shouldShowRowSelectMenu ? scrollToRowSelectMenu : undefined}
{shouldShowColumnSelectMenu ? scrollToColumnSelectMenu : undefined}
</div>
<Button intent={Intent.PRIMARY} className={Classes.FILL} onClick={this.handleScrollToButtonClick}>
Scroll
</Button>
</div>
);
}
private getRegionCardinalityLabel(cardinality: RegionCardinality) {
switch (cardinality) {
case RegionCardinality.CELLS:
return "Cell";
case RegionCardinality.FULL_ROWS:
return "Row";
case RegionCardinality.FULL_COLUMNS:
return "Column";
case RegionCardinality.FULL_TABLE:
return "Full table";
default:
return "";
}
}
private renderSwitch(
label: string,
stateKey: keyof IMutableTableState,
prereqStateKey?: keyof IMutableTableState,
prereqStateKeyValue?: any,
) {
const isDisabled = !this.isPrereqStateKeySatisfied(prereqStateKey, prereqStateKeyValue);
const child = (
<Switch
checked={this.state[stateKey] as boolean}
className={Classes.ALIGN_RIGHT}
disabled={isDisabled}
label={label}
onChange={this.handleBooleanStateChange(stateKey)}
/>
);
if (isDisabled) {
return this.wrapDisabledControlWithTooltip(child, prereqStateKey, prereqStateKeyValue);
} else {
return child;
}
}
private renderFocusStyleSelectMenu() {
const { selectedFocusStyle } = this.state;
return (
<label className={classNames(Classes.LABEL, Classes.INLINE, "tbl-select-label")}>
{"Focus outlines"}
<div className={Classes.SELECT}>
<select onChange={this.updateFocusStyleState()} value={selectedFocusStyle}>
<option value={"tab"}>On tab</option>
<option value={"tabOrClick"}>On tab or click</option>
</select>
</div>
</label>
);
}
private renderNumberSelectMenu(label: string, stateKey: keyof IMutableTableState, values: number[]) {
return this.renderSelectMenu(label, stateKey, values, this.toValueLabel, this.handleNumberStateChange);
}
private renderSelectMenu<T>(
label: string,
stateKey: keyof IMutableTableState,
values: T[],
generateValueLabel: (value: any) => string,
handleChange: IMutableStateUpdateCallback,
prereqStateKey?: keyof IMutableTableState,
prereqStateKeyValue?: any,
) {
const isDisabled = !this.isPrereqStateKeySatisfied(prereqStateKey, prereqStateKeyValue);
// need to explicitly cast generic type T to string
const selectedValue = this.state[stateKey].toString();
const options = values.map(value => {
return (
<option key={value.toString()} value={value.toString()}>
{generateValueLabel(value)}
</option>
);
});
const labelClasses = classNames(Classes.LABEL, Classes.INLINE, "tbl-select-label", {
[Classes.DISABLED]: isDisabled,
});
const child = (
<label className={labelClasses}>
{label}
<div className={Classes.SELECT}>
<select onChange={handleChange(stateKey)} value={selectedValue} disabled={isDisabled}>
{options}
</select>
</div>
</label>
);
if (isDisabled) {
return this.wrapDisabledControlWithTooltip(child, prereqStateKey, prereqStateKeyValue);
} else {
return child;
}
}
// Disabled control helpers
// ========================
private isPrereqStateKeySatisfied(key?: keyof IMutableTableState, value?: any) {
return key == null || this.state[key] === value;
}
private wrapDisabledControlWithTooltip(
element: JSX.Element,
prereqStateKey: keyof IMutableTableState,
prereqStateKeyValue: any,
) {
// Blueprint Tooltip affects the layout, so just show a native title on hover
return <div title={`Requires ${prereqStateKey}=${prereqStateKeyValue}`}>{element}</div>;
}
// Select menu - label generators
// ==============================
private toRenderModeLabel(renderMode: RenderMode) {
switch (renderMode) {
case RenderMode.BATCH:
return "Batch";
case RenderMode.BATCH_ON_UPDATE:
return "Batch on update";
default:
return "None";
}
}
private toCellContentLabel(cellContent: CellContent) {
switch (cellContent) {
case CellContent.CELL_NAMES:
return "Cell names";
case CellContent.EMPTY:
return "Empty";
case CellContent.LONG_TEXT:
return "Long text";
case CellContent.LARGE_JSON:
return "Large JSON (~5KB)";
default:
return "";
}
}
private toTruncatedPopoverModeLabel(truncatedPopoverMode: TruncatedPopoverMode) {
switch (truncatedPopoverMode) {
case TruncatedPopoverMode.ALWAYS:
return "Always";
case TruncatedPopoverMode.NEVER:
return "Never";
case TruncatedPopoverMode.WHEN_TRUNCATED:
return "When truncated";
case TruncatedPopoverMode.WHEN_TRUNCATED_APPROX:
return "Truncated approx";
default:
return "";
}
}
private toValueLabel(value: any) {
return value.toString();
}
// Callbacks
// =========
private onCompleteRender = () => {
this.maybeLogCallback("[onCompleteRender]");
};
private onSelection = (selectedRegions: IRegion[]) => {
this.maybeLogCallback(`[onSelection] selectedRegions =`, ...selectedRegions);
};
private onColumnsReordered = (oldIndex: number, newIndex: number, length: number) => {
this.maybeLogCallback(`[onColumnsReordered] oldIndex = ${oldIndex} newIndex = ${newIndex} length = ${length}`);
this.store.reorderColumns(oldIndex, newIndex, length);
this.forceUpdate();
};
private onRowsReordered = (oldIndex: number, newIndex: number, length: number) => {
this.maybeLogCallback(`[onRowsReordered] oldIndex = ${oldIndex} newIndex = ${newIndex} length = ${length}`);
this.store.reorderRows(oldIndex, newIndex, length);
this.forceUpdate();
};
private onColumnWidthChanged = (index: number, size: number) => {
this.maybeLogCallback(`[onColumnWidthChanged] index = ${index} size = ${size}`);
};
private onRowHeightChanged = (index: number, size: number) => {
this.maybeLogCallback(`[onRowHeightChanged] index = ${index} size = ${size}`);
};
private onFocus = (focusedCell: IFocusedCellCoordinates) => {
this.maybeLogCallback("[onFocusedCell] focusedCell =", focusedCell);
};
private onCopy = (success: boolean) => {
this.maybeLogCallback(`[onCopy] success = ${success}`);
};
private onVisibleCellsChange = (rowIndices: IRowIndices, columnIndices: IColumnIndices) => {
const { rowIndexStart, rowIndexEnd } = rowIndices;
const { columnIndexStart, columnIndexEnd } = columnIndices;
this.maybeLogCallback(
`[onVisibleCellsChange] rowIndexStart=${rowIndexStart} rowIndexEnd=${rowIndexEnd} ` +
`columnIndexStart=${columnIndexStart} columnIndexEnd=${columnIndexEnd}`,
);
};
private maybeLogCallback = (message?: any, ...optionalParams: any[]) => {
if (this.state.showCallbackLogs) {
// allow console.log for these callbacks so devs can see exactly when they fire
// tslint:disable-next-line no-console
console.log(message, ...optionalParams);
}
};
private handleEditableBodyCellConfirm = (value: string, rowIndex?: number, columnIndex?: number) => {
this.store.set(rowIndex, columnIndex, value);
};
private handleEditableColumnCellConfirm = (value: string, columnIndex?: number) => {
this.store.setColumnName(columnIndex, value);
};
private handleDefaultsButtonClick = () => {
this.setState(DEFAULT_STATE);
};
private handleScrollToButtonClick = () => {
const { scrollToRowIndex, scrollToColumnIndex, scrollToRegionType } = this.state;
let region: IRegion;
switch (scrollToRegionType) {
case RegionCardinality.CELLS:
region = Regions.cell(scrollToRowIndex, scrollToColumnIndex);
break;
case RegionCardinality.FULL_ROWS:
region = Regions.row(scrollToRowIndex);
break;
case RegionCardinality.FULL_COLUMNS:
region = Regions.column(scrollToColumnIndex);
break;
case RegionCardinality.FULL_TABLE:
region = Regions.table();
break;
default:
return;
}
this.tableInstance.scrollToRegion(region);
};
private handleResizeRowsByTallestCellButtonClick = () => {
this.tableInstance.resizeRowsByTallestCell();
};
private handleResizeRowsByApproxHeightButtonClick = () => {
this.tableInstance.resizeRowsByApproximateHeight(this.getCellText);
};
private getCellText = (rowIndex: number, columnIndex: number) => {
const content = this.store.get(rowIndex, columnIndex);