-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathCorePivotTable.tsx
1216 lines (1041 loc) · 44.6 KB
/
CorePivotTable.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
// (C) 2007-2025 GoodData Corporation
import {
AgGridEvent,
AllCommunityModule,
BodyScrollEvent,
ColumnResizedEvent,
GridReadyEvent,
SortChangedEvent,
PinnedRowDataChangedEvent,
ModuleRegistry,
provideGlobalGridOptions,
} from "ag-grid-community";
import { v4 as uuidv4 } from "uuid";
import { IPreparedExecution } from "@gooddata/sdk-backend-spi";
import { AgGridReact } from "ag-grid-react";
import React from "react";
import { injectIntl } from "react-intl";
import cx from "classnames";
import {
BucketNames,
createExportErrorFunction,
DataViewFacade,
ErrorCodes,
ErrorComponent,
GoodDataSdkError,
IErrorDescriptors,
ILoadingState,
IntlWrapper,
IPushData,
LoadingComponent,
newErrorMapping,
} from "@gooddata/sdk-ui";
import { ThemeContextProvider, withTheme } from "@gooddata/sdk-ui-theme-provider";
import { getUpdatedColumnOrRowTotals } from "./impl/structure/headers/aggregationsMenuHelper.js";
import { getScrollbarWidth, sanitizeDefTotals, getTotalsForColumnsBucket } from "./impl/utils.js";
import { IScrollPosition } from "./impl/stickyRowHandler.js";
import {
ColumnHeadersPosition,
DefaultColumnWidth,
ICorePivotTableProps,
IMenu,
MeasureGroupDimension,
} from "./publicTypes.js";
import { ColumnWidthItem } from "./columnWidths.js";
import isEqual from "lodash/isEqual.js";
import noop from "lodash/noop.js";
import debounce from "lodash/debounce.js";
import { invariant } from "ts-invariant";
import { isManualResizing, scrollBarExists } from "./impl/base/agUtils.js";
import {
ColumnResizingConfig,
IMenuAggregationClickConfig,
TableAgGridCallbacks,
TableMethods,
} from "./impl/privateTypes.js";
import { createGridOptions } from "./impl/gridOptions.js";
import { TableFacadeInitializer } from "./impl/tableFacadeInitializer.js";
import { ICorePivotTableState, InternalTableState } from "./tableState.js";
import { isColumnAutoresizeEnabled } from "./impl/resizing/columnSizing.js";
import cloneDeep from "lodash/cloneDeep.js";
// Register all Community features
ModuleRegistry.registerModules([AllCommunityModule]);
// Mark all grids as using legacy themes
provideGlobalGridOptions({ theme: "legacy" });
const DEFAULT_COLUMN_WIDTH = 200;
const WATCHING_TABLE_RENDERED_INTERVAL = 500;
const AGGRID_ON_RESIZE_TIMEOUT = 300;
/**
* This class implements pivot table using the community version of ag-grid.
*
* Bear in mind that this is not a typical, standard React component implementation; the main reason
* behind that is that while ag-grid comes with a React component the ag-grid itself is not a React component
* and vast majority of its APIs are non-React as well. You will therefore find that there is a lot of non-react
* state flying around.
*
* Instead of looking at this implementation as a typical React component, look at it like a adapter between
* React and ag-grid which is used to render data obtained using GD executions.
*
* The code in this class is built to reflect the adapter nature of the integration. The responsibility of this
* component is to correctly handle the component lifecycle and orchestrate integration of React and ag-grid, React
* and GoodData, React and GoodData and ag-grid.
*
* Lifecycle
* ---------
*
* The goal of the table is to render data that it obtains from GD platform by driving an execution. To this end
* the prop 'execution' contains an instance of Prepared Execution which is all set up and ready to run.
*
* Before rendering anything, the code must first drive this prepared execution completion in order to figure out
* how the actual table should look like header-wise.
*
* Once the execution completes successfully code will process the result and the metadata included within
* to construct table headers for ag-grid and prepare an ag-grid data source that the ag-grid will use to read
* pages of data from backend. Note: while constructing table headers, the code will also apply manual column
* sizing settings.
*
* With this ready, the component can render the actual ag-grid table. It will create ag-grid options with
* all the necessary metadata and customizations.
*
* After the table is successfully rendered, the code may (depending on props) apply grow-to-width and auto-resizing
* logic on the table columns. And then finally it will determine and set the sticky row contents.
*
* At this point when the table is rendered, the users may interact with it and change sorting or add totals
* or subtotals. All of this is handled outside of React. These changes are handled in the ag-grid data source
* implementation. As it discovers that different sorts or totals are needed, it will transform the original
* prepared execution, add the extra settings and re-drive the execution. Once done, it will update the internal
* state and ping ag-grid API to re-render the table.
*
* In case the client changes props (say modifying the prepared execution) the componentDidUpdate will determine
* whether the full reinitialization is in order. If so the entire existing ag-grid and all our internal state
* is thrown out and table is initialized from scratch.
*
* Notable sub-components
* ----------------------
*
* All custom logic that we build on top of ag-grid has the entry point in `TableFacade`. The code in this component
* relies on the facade to drive our custom table logic. This facade further delegates complex pieces of work
* to other components. The most important are `TableDescriptor` and `ResizedColumnStore` + its friends.
*
* The `TableDescriptor` is responsible for figuring out how the table should look like and prepare column
* descriptors and ag-grid ColDefs.
*
* The `ResizedColumnStore` & functions in its vicinity are responsible for implementation of our custom
* table column resizing logic.
*
* Apart from these main components there is also our custom implementation of ag-grid data source - this is responsible
* for getting correct data and transforming it to form that can be consumed by ag-gird. It is the data source where
* our code has to figure out whether the sorts or totals have changed and if so update the execution to perform
* the correct execution.
*
* Finally there is the sticky row handling which contains some nasty code & at times works with ag-grid internals
* to get the job done.
*
* Control flow
* ------------
*
* To maintain some kind of sanity in this complex component there are two general rules:
*
* 1. TableMethods or its subtypes are the only way how pivot table component passes down its essential functions
* to sub-components.
*
* 2. All table functionality and features MUST be orchestrated from the pivot table component itself.
* The facade or other subcomponents merely _do the work_ but they do not make 'high level decisions' of
* what the table should be doing.
*
* These rules are in place to try and get to 'top-down' control flow.
*
*
* Known flaws
* -----------
*
* - The initial render & subsequent table column resizing is brittle and includes a async functions, timeouts, intervals
* etc.
*
* This can be currently knocked out of balance if during initial table render the data source determines
* it needs to transform the execution (to include sorts for instance; this was often the case if AD sent execution
* definition with invalid sorts).
*
* - The reinitialization of entire table is too aggressive at the moment. There are two most notable cases:
*
* 1. Client changes drills; this will lead to reinit to correctly mark cells as drillable. Perhaps all we
* need it to trigger some kind of ag-grid cell refresh?
*
* 2. Client changes prepared execution that comes in props. Any change means reinit. This is not really needed
* if only sorts or totals were added but the shape of the table looks the same.
*
* Debugging hints
* ---------------
*
* Nothing renders: check out the problem with resizing & data source interplay.
*
*
* @internal
*/
export class CorePivotTableAgImpl extends React.Component<ICorePivotTableProps, ICorePivotTableState> {
public static defaultProps: Pick<
ICorePivotTableProps,
| "locale"
| "drillableItems"
| "afterRender"
| "pushData"
| "onExportReady"
| "onLoadingChanged"
| "onError"
| "onDataView"
| "onDrill"
| "ErrorComponent"
| "LoadingComponent"
| "pageSize"
| "config"
| "onColumnResized"
> = {
locale: "en-US",
drillableItems: [],
afterRender: noop,
pushData: noop,
onExportReady: noop,
onLoadingChanged: noop,
onError: noop,
onDataView: noop,
onDrill: () => true,
ErrorComponent,
LoadingComponent,
pageSize: 100,
config: {},
onColumnResized: noop,
};
private readonly errorMap: IErrorDescriptors;
private containerRef: HTMLDivElement | undefined;
private pivotTableId: string;
private internal: InternalTableState;
private boundAgGridCallbacks: TableAgGridCallbacks;
constructor(props: ICorePivotTableProps) {
super(props);
const { execution, config } = props;
this.state = {
readyToRender: false,
columnTotals: cloneDeep(sanitizeDefTotals(execution.definition)),
rowTotals: getTotalsForColumnsBucket(execution.definition),
desiredHeight: config!.maxHeight,
resized: false,
tempExecution: execution,
isLoading: false,
};
this.errorMap = newErrorMapping(props.intl);
this.internal = new InternalTableState();
this.boundAgGridCallbacks = this.createBoundAgGridCallbacks();
this.pivotTableId = uuidv4().replace(/-/g, "");
this.onLoadingChanged = this.onLoadingChanged.bind(this);
}
//
// Lifecycle
//
private abortController: AbortController = new AbortController();
private refreshAbortController = (): void => {
if (this.props.config?.enableExecutionCancelling) {
this.abortController.abort();
this.abortController = new AbortController();
}
};
/**
* Starts initialization of table that will show results of the provided prepared execution. If there is
* already an initialization in progress for the table, this will abandon the previous initialization
* and start a new one.
*
* During the initialization the code drives the execution and obtains the first page of data. Once that
* is done, the initializer will construct the {@link TableFacade} with all the essential non-react
* table & data state in it.
*
* After the initializer completes this, the table facade and the table itself is ready to render the
* ag-grid component.
*
* @param execution - prepared execution to drive
*/
private initialize = (execution: IPreparedExecution): TableFacadeInitializer => {
this.internal.abandonInitialization();
this.refreshAbortController();
const initializer = new TableFacadeInitializer(
execution,
this.getTableMethods(),
this.props,
this.props.config?.enableExecutionCancelling ? this.abortController : undefined,
);
initializer.initialize().then((result) => {
if (!result || this.internal.initializer !== result.initializer) {
/*
* This particular initialization was abandoned.
*/
return;
}
this.internal.initializer = undefined;
this.internal.table = result.table;
this.setState({ readyToRender: true });
});
return initializer;
};
/**
* Completely re-initializes the table in order to show data for the provided prepared execution. At this point
* code has determined that the table layout for the other prepared execution differs from what is currently
* shown and the only reasonable thing to do is to throw everything away and start from scratch.
*
* This will reset all React state and non-react state and start table initialization process.
*/
private reinitialize = (execution: IPreparedExecution): void => {
this.setState(
{
readyToRender: false,
columnTotals: cloneDeep(sanitizeDefTotals(execution.definition)),
rowTotals: getTotalsForColumnsBucket(execution.definition),
error: undefined,
desiredHeight: this.props.config!.maxHeight,
resized: false,
},
() => {
this.internal.destroy();
this.internal = new InternalTableState();
this.boundAgGridCallbacks = this.createBoundAgGridCallbacks();
this.internal.initializer = this.initialize(execution);
},
);
};
public componentDidMount(): void {
this.internal.initializer = this.initialize(this.props.execution);
}
public componentWillUnmount(): void {
this.refreshAbortController();
if (this.containerRef) {
this.containerRef.removeEventListener("mousedown", this.onContainerMouseDown);
}
// this ensures any events emitted during the async initialization will be sunk. they are no longer needed.
this.internal.destroy();
}
public componentDidUpdate(prevProps: ICorePivotTableProps): void {
// reinit in progress
if (
!this.state.readyToRender &&
this.state.isLoading &&
!this.props.config?.enableExecutionCancelling
) {
return;
}
if (this.isReinitNeeded(prevProps)) {
/*
* This triggers when execution changes (new measures / attributes). In that case,
* a complete re-init of the table is in order.
*
* Everything is thrown out of the window including all the ag-grid data sources and instances and
* a completely new table will be initialized to the current props.
*
* Note: compared to v7 version of the table, this only happens if someone actually changes the
* execution-related props of the table. This branch will not hit any other time.
*/
// eslint-disable-next-line no-console
console.debug(
"triggering reinit",
this.props.execution.definition,
prevProps.execution.definition,
);
this.reinitialize(this.props.execution);
} else {
/*
* When in this branch, the ag-grid instance is up and running and is already showing some data and
* it _should_ be possible to normally use the ag-grid APIs.
*
* The currentResult and visibleData _will_ be available at this point because the component is definitely
* after a successful execution and initialization.
*/
if (this.shouldRefreshHeader(this.props, prevProps)) {
this.internal.table?.refreshHeader();
}
if (this.isGrowToFitEnabled() && !this.isGrowToFitEnabled(prevProps)) {
this.growToFit();
}
const prevColumnWidths = this.getColumnWidths(prevProps);
const columnWidths = this.getColumnWidths(this.props);
if (!isEqual(prevColumnWidths, columnWidths)) {
this.internal.table?.applyColumnSizes(this.getResizingConfig());
}
if (
this.props.config?.maxHeight &&
!isEqual(this.props.config?.maxHeight, prevProps.config?.maxHeight)
) {
this.updateDesiredHeight();
}
}
}
/**
* Tests whether reinitialization of ag-grid is needed after the update. Currently there are two
* conditions:
*
* - drilling has changed
*
* OR
*
* - prepared execution has changed AND the new prep execution definition does not match currently shown
* data.
*/
private isReinitNeeded(prevProps: ICorePivotTableProps): boolean {
const drillingIsSame = isEqual(prevProps.drillableItems, this.props.drillableItems);
const columnHeadersPositionIsSame = isEqual(
prevProps.config?.columnHeadersPosition,
this.props.config?.columnHeadersPosition,
);
if (!drillingIsSame) {
// eslint-disable-next-line no-console
console.debug("drilling is different", prevProps.drillableItems, this.props.drillableItems);
return true;
}
if (!columnHeadersPositionIsSame) {
return true;
}
if (!this.internal.table) {
// Table is not yet fully initialized. See if the initialization is in progress. If so, see if
// the init is for same execution or not. Otherwise fall back to compare props vs props.
if (this.internal.initializer) {
const initializeForSameExec = this.internal.initializer.isSameExecution(this.props.execution);
if (!initializeForSameExec) {
// eslint-disable-next-line no-console
console.debug(
"initializer for different execution",
this.props.execution,
prevProps.execution,
);
}
return !initializeForSameExec;
} else {
const prepExecutionSame =
this.props.execution.fingerprint() === prevProps.execution.fingerprint();
if (!prepExecutionSame) {
// eslint-disable-next-line no-console
console.debug("have to reinit table", this.props.execution, prevProps.execution);
}
return !prepExecutionSame;
}
}
return !this.internal.table.isMatchingExecution(this.props.execution);
}
/**
* Tests whether ag-grid's refreshHeader should be called. At the moment this is necessary when user
* turns on/off the aggregation menus through the props. The menus happen to appear in the table column headers
* so the refresh is essential to show/hide them.
*
* @param props - current table props
* @param prevProps - previous table props
* @internal
*/
private shouldRefreshHeader(props: ICorePivotTableProps, prevProps: ICorePivotTableProps): boolean {
const propsRequiringAgGridRerender: Array<(props: ICorePivotTableProps) => any> = [
(props) => props?.config?.menu,
];
return propsRequiringAgGridRerender.some(
(propGetter) => !isEqual(propGetter(props), propGetter(prevProps)),
);
}
private stopEventWhenResizeHeader(e: React.MouseEvent): void {
// Do not propagate event when it originates from the table resizer.
// This means for example that we can resize columns without triggering drag in the application.
if ((e.target as Element)?.className?.includes?.("ag-header-cell-resize")) {
e.preventDefault();
e.stopPropagation();
}
}
//
// Render
//
private setContainerRef = (container: HTMLDivElement): void => {
this.containerRef = container;
if (this.containerRef) {
this.containerRef.addEventListener("mousedown", this.onContainerMouseDown);
}
};
private renderLoading() {
const { LoadingComponent, theme } = this.props;
const color = theme?.table?.loadingIconColor ?? theme?.palette?.complementary?.c6 ?? undefined;
return (
<div className="s-loading gd-table-loading">
{LoadingComponent ? <LoadingComponent color={color} /> : null}
</div>
);
}
public render() {
const { ErrorComponent } = this.props;
const { desiredHeight, error } = this.state;
if (error) {
const errorProps =
this.errorMap[
Object.prototype.hasOwnProperty.call(this.errorMap, error)
? error
: ErrorCodes.UNKNOWN_ERROR
];
return ErrorComponent ? <ErrorComponent code={error} {...errorProps} /> : null;
}
const style: React.CSSProperties = {
height: desiredHeight || "100%",
position: "relative",
overflow: "hidden",
};
if (!this.state.readyToRender) {
return (
<div className="gd-table-component" style={style} id={this.pivotTableId}>
{this.renderLoading()}
</div>
);
}
// when table is ready, then the table facade must be set. if this bombs then there is a bug
// in the initialization logic
invariant(this.internal.table);
if (!this.internal.gridOptions) {
this.internal.gridOptions = createGridOptions(
this.internal.table,
this.getTableMethods(),
this.props,
);
}
/*
* Show loading overlay until all the resizing is done. This is because the various resizing operations
* have to happen asynchronously - they must wait until ag-grid fires onFirstDataRendered, before our code
* can start reliably interfacing with the autosizing features.
*/
const shouldRenderLoadingOverlay =
(this.isColumnAutoresizeEnabled() || this.isGrowToFitEnabled()) && !this.state.resized;
const classNames = cx("gd-table-component", {
"gd-table-header-hide":
this.props.config?.columnHeadersPosition === "left" &&
this.internal.table.tableDescriptor.isTransposed(),
});
return (
<div
className={classNames}
style={style}
id={this.pivotTableId}
onMouseDown={this.stopEventWhenResizeHeader}
onDragStart={this.stopEventWhenResizeHeader}
>
<div
className="gd-table ag-theme-balham s-pivot-table"
style={style}
ref={this.setContainerRef}
>
<AgGridReact {...this.internal.gridOptions} modules={[AllCommunityModule]} />
{shouldRenderLoadingOverlay ? this.renderLoading() : null}
</div>
</div>
);
}
//
// event handlers
//
private onGridReady = (event: GridReadyEvent) => {
invariant(this.internal.table);
this.internal.table.finishInitialization(event.api, event.api);
this.updateDesiredHeight();
if (this.getGroupRows()) {
this.internal.table.initializeStickyRow();
}
this.internal.table.setTooltipFields();
// when table contains only headers, the onFirstDataRendered
// is not triggered; trigger it manually
if (this.internal.table.isEmpty()) {
this.onFirstDataRendered();
}
};
private onFirstDataRendered = async (_event?: AgGridEvent) => {
invariant(this.internal.table);
if (this.internal.firstDataRendered) {
console.error("onFirstDataRendered called multiple times");
}
this.internal.firstDataRendered = true;
// Since issue here is not resolved, https://github.com/ag-grid/ag-grid/issues/3263,
// work-around by using 'setInterval'
this.internal.startWatching(this.startWatchingTableRendered, WATCHING_TABLE_RENDERED_INTERVAL);
/*
* At this point data from backend is available, some of it is rendered and auto-resize can be done.
*
* See: https://www.ag-grid.com/javascript-grid-resizing/#resize-after-data
*
* I suspect now that the table life-cycle is somewhat more sane, we can follow the docs. For a good
* measure, let's throw in a mild timeout. I have observed different results (slightly less space used)
* when the timeout was not in place.
*/
if (this.isColumnAutoresizeEnabled()) {
await this.autoresizeColumns();
} else if (this.isGrowToFitEnabled()) {
this.growToFit();
}
this.updateStickyRow();
};
private onModelUpdated = () => {
this.updateStickyRow();
};
private onGridColumnsChanged = () => {
this.updateStickyRow();
};
private onGridSizeChanged = (gridSizeChangedEvent: any): void => {
if (!this.internal.firstDataRendered) {
// ag-grid does emit the grid size changed even before first data gets rendered (i suspect this is
// to cater for the initial render where it goes from nothing to something that has the headers, and then
// it starts rendering the data itself)
//
// Don't do anything, the resizing will be triggered after the first data is rendered
return;
}
if (!this.internal.table) {
return;
}
if (this.internal.table.isResizing()) {
// don't do anything if the table is already resizing. this copies what we have in v7 line however
// I think it opens room for racy/timing behavior. if the window is resized _while_ the table is resizing
// it is likely that it will not respect current window size.
//
// keeping it like this for now. if needed, we can enqueue an auto-resize request somewhere and process
// it after resizing finishes.
return;
}
if (
this.internal.checkAndUpdateLastSize(
gridSizeChangedEvent.clientWidth,
gridSizeChangedEvent.clientHeight,
)
) {
this.autoresizeColumns(true);
}
};
private onGridColumnResized = async (columnEvent: ColumnResizedEvent) => {
invariant(this.internal.table);
if (!columnEvent.finished) {
return; // only update the height once the user is done setting the column size
}
this.updateDesiredHeight();
if (isManualResizing(columnEvent)) {
this.internal.table.onManualColumnResize(this.getResizingConfig(), columnEvent.columns!);
}
};
private onSortChanged = (event: SortChangedEvent): void => {
if (!this.internal.table) {
console.warn("changing sorts without prior execution cannot work");
return;
}
const sortItems = this.internal.table.createSortItems(event.api.getAllGridColumns()!);
// Changing sort may cause subtotals to no longer be reasonably placed - remove them if that is the case
// This applies only to totals in ATTRIBUTE bucket, column totals are not affected by sorting
const executionDefinition = this.getExecutionDefinition();
const totals = sanitizeDefTotals(executionDefinition, sortItems);
// eslint-disable-next-line no-console
console.debug("onSortChanged", sortItems);
this.pushDataGuard({
properties: {
sortItems,
totals,
bucketType: BucketNames.ATTRIBUTE,
},
});
this.setState({ columnTotals: totals }, () => {
this.internal.table?.refreshData();
});
};
private onPinnedRowDataChanged = async (event: PinnedRowDataChangedEvent) => {
if (event?.api.getPinnedBottomRowCount() > 0) {
await this.autoresizeColumns(true);
}
};
private onBodyScroll = (event: BodyScrollEvent) => {
const scrollPosition: IScrollPosition = {
top: Math.max(event.top, 0),
left: event.left,
};
this.updateStickyRowContent(scrollPosition);
};
private onContainerMouseDown = (event: MouseEvent) => {
this.internal.isMetaOrCtrlKeyPressed = event.metaKey || event.ctrlKey;
this.internal.isAltKeyPressed = event.altKey;
};
private onPageLoaded = (dv: DataViewFacade, newResult: boolean): void => {
this.props.onDataView?.(dv);
if (!this.internal.table) {
return;
}
if (newResult) {
this.props.onExportReady?.(this.internal.table.createExportFunction(this.props.exportTitle));
}
this.updateStickyRow();
this.updateDesiredHeight();
};
/**
* This will be called when user changes sorts or adds totals. This means complete re-execution with
* new sorts or totals. Loading indicators will be shown instead of all rendered rows thanks to the
* LoadingRenderer used in all cells of the left-most column.
*
* The table must take care to remove the sticky (top-pinned) row - it is treated differently by
* ag-grid and will be literally sticking there on its own with the loading indicators.
*
* Once transformation finishes - indicated by call to onPageLoaded, table can re-instance the sticky row.
*
* @param newExecution - the new execution which is being run and will be used to populate the table
*/
private onExecutionTransformed = (newExecution: IPreparedExecution): void => {
if (!this.internal.table) {
return;
}
this.internal.table.clearStickyRow();
// Force double execution only when totals/subtotals for columns change, so table is render properly.
if (!isEqual(this.state.tempExecution.definition.buckets[2], newExecution.definition.buckets[2])) {
this.setState({
tempExecution: newExecution,
});
this.reinitialize(newExecution);
}
};
private onMenuAggregationClick = (menuAggregationClickConfig: IMenuAggregationClickConfig) => {
const sortItems = this.internal.table?.getSortItems();
const { isColumn } = menuAggregationClickConfig;
if (isColumn) {
const newColumnTotals = sanitizeDefTotals(
this.getExecutionDefinition(),
sortItems,
getUpdatedColumnOrRowTotals(this.getColumnTotals(), menuAggregationClickConfig),
);
this.pushDataGuard({
properties: {
totals: newColumnTotals,
bucketType: BucketNames.ATTRIBUTE,
},
});
this.setState({ columnTotals: newColumnTotals }, () => {
this.internal.table?.refreshData();
});
} else {
const newRowTotals = getUpdatedColumnOrRowTotals(this.getRowTotals(), menuAggregationClickConfig);
this.setState({ rowTotals: newRowTotals }, () => {
this.internal.table?.refreshData();
});
this.pushDataGuard({
properties: {
totals: newRowTotals,
bucketType: BucketNames.COLUMNS,
},
});
}
};
private onLoadingChanged = (loadingState: ILoadingState): void => {
const { onLoadingChanged } = this.props;
if (onLoadingChanged) {
onLoadingChanged(loadingState);
this.setState({ isLoading: loadingState.isLoading });
}
};
private onError = (error: GoodDataSdkError, execution = this.props.execution) => {
const { onExportReady } = this.props;
if (this.props.execution.fingerprint() === execution.fingerprint()) {
this.setState({ error: error.getMessage(), readyToRender: true });
// update loading state when an error occurs
this.onLoadingChanged({ isLoading: false });
onExportReady!(createExportErrorFunction(error));
this.props.onError?.(error);
}
};
//
// Table resizing
//
private growToFit = () => {
invariant(this.internal.table);
if (!this.isGrowToFitEnabled()) {
return;
}
this.internal.table.growToFit(this.getResizingConfig());
if (!this.state.resized && !this.internal.table.isResizing()) {
this.setState({
resized: true,
});
}
};
private autoresizeColumns = async (force: boolean = false) => {
if (this.state.resized && !force) {
return;
}
const didResize = await this.internal.table?.autoresizeColumns(this.getResizingConfig(), force);
if (didResize) {
// after column resizing, horizontal scroolbar may change and table height may need resizing
this.updateDesiredHeight();
}
if (didResize && !this.state.resized) {
this.setState({
resized: true,
});
}
};
private shouldAutoResizeColumns = () => {
const columnAutoresize = this.isColumnAutoresizeEnabled();
const growToFit = this.isGrowToFitEnabled();
return columnAutoresize || growToFit;
};
private startWatchingTableRendered = () => {
if (!this.internal.table) {
return;
}
const missingContainerRef = !this.containerRef; // table having no data will be unmounted, it causes ref null
const isTableRendered = this.shouldAutoResizeColumns()
? this.state.resized
: this.internal.table.isPivotTableReady();
const shouldCallAutoresizeColumns =
this.internal.table.isPivotTableReady() &&
!this.state.resized &&
!this.internal.table.isResizing();
if (this.shouldAutoResizeColumns() && shouldCallAutoresizeColumns) {
this.autoresizeColumns();
}
if (missingContainerRef || isTableRendered) {
this.stopWatchingTableRendered();
}
};
private stopWatchingTableRendered = () => {
this.internal.stopWatching();
this.props.afterRender!();
};
//
// Sticky row handling
//
private isStickyRowAvailable = (): boolean => {
invariant(this.internal.table);
return Boolean(this.getGroupRows() && this.internal.table.stickyRowExists());
};
private updateStickyRow = (): void => {
if (!this.internal.table) {
return;
}
if (this.isStickyRowAvailable()) {
const scrollPosition: IScrollPosition = { ...this.internal.lastScrollPosition };
this.internal.lastScrollPosition = {
top: 0,
left: 0,
};
this.updateStickyRowContent(scrollPosition);
}
};
private updateStickyRowContent = (scrollPosition: IScrollPosition): void => {
invariant(this.internal.table);
if (this.isStickyRowAvailable()) {
// Position update was moved here because in some complicated cases with totals,
// it was not behaving properly. This was mainly visible in storybook, but it may happen
// in other environments as well.
this.internal.table.updateStickyRowPosition();
this.internal.table.updateStickyRowContent({
scrollPosition,
lastScrollPosition: this.internal.lastScrollPosition,
});
}
this.internal.lastScrollPosition = { ...scrollPosition };
};
//
// Desired height updating
//
private getScrollBarPadding = (): number => {
if (!this.internal.table?.isFullyInitialized()) {
return 0;
}
if (!this.containerRef) {
return 0;
}
// check for scrollbar presence
return scrollBarExists(this.containerRef) ? getScrollbarWidth() : 0;
};
private calculateDesiredHeight = (): number | undefined => {
const { maxHeight } = this.props.config!;
if (!maxHeight) {
return;
}
const bodyHeight = this.internal.table?.getTotalBodyHeight() ?? 0;
const totalHeight = bodyHeight + this.getScrollBarPadding();
return Math.min(totalHeight, maxHeight);
};
private updateDesiredHeight = (): void => {
if (!this.internal.table) {
return;
}
const desiredHeight = this.calculateDesiredHeight();