forked from deephaven/web-client-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIrisGridUtils.ts
More file actions
1911 lines (1744 loc) · 56.9 KB
/
IrisGridUtils.ts
File metadata and controls
1911 lines (1744 loc) · 56.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
type GridMetrics,
type GridRange,
type GridState,
GridUtils,
type ModelIndex,
type ModelSizeMap,
type MoveOperation,
type VisibleIndex,
} from '@deephaven/grid';
import type { dh as DhType } from '@deephaven/jsapi-types';
import {
DateUtils,
TableUtils,
type ReverseType,
type SortDirection,
type FormattingRule,
type SortDescriptor,
} from '@deephaven/jsapi-utils';
import Log from '@deephaven/log';
import {
assertNotNull,
bindAllMethods,
EMPTY_ARRAY,
EMPTY_MAP,
isNotNullOrUndefined,
} from '@deephaven/utils';
import AggregationUtils from './sidebar/aggregations/AggregationUtils';
import AggregationOperation from './sidebar/aggregations/AggregationOperation';
import { type FilterData, type IrisGridState } from './IrisGrid';
import {
type ColumnName,
type ReadonlyAdvancedFilterMap,
type ReadonlyQuickFilterMap,
type InputFilter,
type CellData,
type PendingDataMap,
type UIRow,
type AdvancedFilterOptions,
} from './CommonTypes';
import { type UIRollupConfig } from './sidebar/RollupRows';
import { type AggregationSettings } from './sidebar/aggregations/Aggregations';
import { type FormattingRule as SidebarFormattingRule } from './sidebar/conditional-formatting/ConditionalFormattingUtils';
import type IrisGridModel from './IrisGridModel';
import type AdvancedSettingsType from './sidebar/AdvancedSettingsType';
import AdvancedSettings from './sidebar/AdvancedSettings';
import ColumnHeaderGroup, {
type ColumnHeaderGroupConfig,
} from './ColumnHeaderGroup';
import {
isPartitionedGridModelProvider,
type PartitionConfig,
} from './PartitionedGridModel';
import { type IrisGridThemeType } from './IrisGridTheme';
const log = Log.module('IrisGridUtils');
export type HydratedIrisGridState = Pick<
IrisGridState,
| 'advancedFilters'
| 'aggregationSettings'
| 'customColumnFormatMap'
| 'columnAlignmentMap'
| 'isFilterBarShown'
| 'quickFilters'
| 'customColumns'
| 'reverse'
| 'rollupConfig'
| 'showSearchBar'
| 'searchValue'
| 'selectDistinctColumns'
| 'selectedSearchColumns'
| 'sorts'
| 'invertSearchColumns'
| 'pendingDataMap'
| 'frozenColumns'
| 'conditionalFormats'
| 'columnHeaderGroups'
| 'partitionConfig'
> & {
metrics?: Partial<GridMetrics>;
};
export type DehydratedPendingDataMap<T> = [number, { data: [string, T][] }][];
export type DehydratedAdvancedFilter = [
number,
{
options: AdvancedFilterOptions;
},
];
export type DehydratedQuickFilter = [
number,
{
text: string;
},
];
export type DehydratedCustomColumnFormat = [string, FormattingRule];
export type DehydratedUserColumnAlignment = [string, CanvasTextAlign];
export type DehydratedUserColumnWidth = [ColumnName, number];
export type DehydratedUserRowHeight = [number, number];
export type DehydratedPartitionConfig = PartitionConfig;
/** @deprecated Use `DehydratedSort` instead */
export interface LegacyDehydratedSort {
column: ModelIndex;
isAbs: boolean;
direction: SortDirection;
}
export interface DehydratedSort {
column: ColumnName;
isAbs: boolean;
direction: string;
}
export interface TableSettings {
quickFilters?: readonly DehydratedQuickFilter[];
advancedFilters?: readonly DehydratedAdvancedFilter[];
inputFilters?: readonly InputFilter[];
sorts?: readonly (DehydratedSort | LegacyDehydratedSort)[];
partitions?: unknown[];
partitionColumns?: ColumnName[];
}
export interface DehydratedIrisGridState {
advancedFilters: readonly DehydratedAdvancedFilter[];
aggregationSettings: AggregationSettings;
customColumnFormatMap: readonly DehydratedCustomColumnFormat[];
columnAlignmentMap: readonly DehydratedUserColumnAlignment[];
isFilterBarShown: boolean;
quickFilters: readonly DehydratedQuickFilter[];
sorts: readonly DehydratedSort[];
userColumnWidths: readonly DehydratedUserColumnWidth[];
userRowHeights: readonly DehydratedUserRowHeight[];
customColumns: readonly ColumnName[];
conditionalFormats: readonly SidebarFormattingRule[];
/** @deprecated use `reverse` instead. Can be removed after DHE sanluis release */
reverseType?: ReverseType;
reverse: boolean;
rollupConfig?: UIRollupConfig;
showSearchBar: boolean;
searchValue: string;
selectDistinctColumns: readonly ColumnName[];
selectedSearchColumns: readonly ColumnName[];
invertSearchColumns: boolean;
pendingDataMap: DehydratedPendingDataMap<unknown>;
frozenColumns: readonly ColumnName[];
columnHeaderGroups?: readonly DhType.ColumnGroup[];
partitionConfig?: DehydratedPartitionConfig;
}
export interface DehydratedIrisGridPanelStateV1 {
isSelectingPartition: boolean;
partition: string | null;
advancedSettings: [AdvancedSettingsType, boolean][];
}
export interface DehydratedIrisGridPanelStateV2 {
isSelectingPartition: boolean;
partitions: (string | null)[];
advancedSettings: [AdvancedSettingsType, boolean][];
}
export type DehydratedIrisGridPanelState =
| DehydratedIrisGridPanelStateV1
| DehydratedIrisGridPanelStateV2;
export function isPanelStateV1(
state: DehydratedIrisGridPanelState
): state is DehydratedIrisGridPanelStateV1 {
return (state as DehydratedIrisGridPanelStateV1).partition !== undefined;
}
export function isPanelStateV2(
state: DehydratedIrisGridPanelState
): state is DehydratedIrisGridPanelStateV2 {
return Array.isArray((state as DehydratedIrisGridPanelStateV2).partitions);
}
/**
* Checks if an index is valid for the given array
* @param x The index to check
* @param array The array
* @returns True if the index if valid within the array
*/
function isValidIndex(x: number, array: readonly unknown[]): boolean {
return x >= 0 && x < array.length;
}
function isDateWrapper(value: unknown): value is DhType.DateWrapper {
return (value as DhType.DateWrapper)?.asDate != null;
}
export type HydratedGridState = Pick<
GridState,
'isStuckToBottom' | 'isStuckToRight' | 'movedColumns' | 'movedRows'
>;
export type DehydratedGridState = {
isStuckToBottom: boolean;
isStuckToRight: boolean;
movedColumns: readonly {
from: string | [string, string] | ModelIndex | [ModelIndex, ModelIndex];
to: string | ModelIndex;
}[];
movedRows: readonly MoveOperation[];
};
class IrisGridUtils {
/**
* Exports the state from Grid component to a JSON stringifiable object.
* See IrisGridCacheUtil for memoization and comparing dehydrated states.
* @param model The table model to export the Grid state for
* @param gridState The state of the Grid to export
* @returns An object that can be stringified and imported with {{@link hydrateGridState}}
*/
static dehydrateGridState(
model: IrisGridModel,
gridState: HydratedGridState
): DehydratedGridState {
const { isStuckToBottom, isStuckToRight, movedColumns, movedRows } =
gridState;
const { columns } = model;
return {
isStuckToBottom,
isStuckToRight,
movedColumns: [...movedColumns]
.filter(
({ to, from }) =>
isValidIndex(to, columns) &&
((typeof from === 'number' && isValidIndex(from, columns)) ||
(Array.isArray(from) &&
isValidIndex(from[0], columns) &&
isValidIndex(from[1], columns)))
)
.map(({ to, from }) => ({
to: columns[to].name,
from: Array.isArray(from)
? [columns[from[0]].name, columns[from[1]].name]
: columns[from].name,
})),
movedRows: [...movedRows],
};
}
/**
* Import a state for Grid that was exported with {{@link dehydrateGridState}}
* @param model The table model to import the state for
* @param gridState The state of the panel that was saved
* @returns The gridState props to set on the Grid
*/
static hydrateGridState(
model: IrisGridModel,
gridState: DehydratedGridState,
customColumns: readonly string[] = []
): HydratedGridState {
const { isStuckToBottom, isStuckToRight, movedColumns, movedRows } =
gridState;
const { columns } = model;
const customColumnNames =
IrisGridUtils.parseCustomColumnNames(customColumns);
const columnNames = columns
.map(({ name }) => name)
.concat(customColumnNames);
return {
isStuckToBottom,
isStuckToRight,
movedColumns: [...movedColumns]
.map(({ to, from }) => {
const getIndex = (x: string | number): number =>
typeof x === 'string'
? columnNames.findIndex(name => name === x)
: x;
return {
to: getIndex(to),
from: Array.isArray(from)
? ([getIndex(from[0]), getIndex(from[1])] as [number, number])
: getIndex(from),
};
})
.filter(
({ to, from }) =>
isValidIndex(to, columnNames) &&
((typeof from === 'number' && isValidIndex(from, columnNames)) ||
(Array.isArray(from) &&
isValidIndex(from[0], columnNames) &&
isValidIndex(from[1], columnNames)))
),
movedRows: [...movedRows],
};
}
/**
* Export the IrisGridPanel state.
* @param model The table model the state is being dehydrated with
* @param irisGridPanelState The current IrisGridPanel state
* @returns The dehydrated IrisGridPanel state
*/
static dehydrateIrisGridPanelState(
model: IrisGridModel,
irisGridPanelState: {
// This needs to be changed after IrisGridPanel is done
isSelectingPartition: boolean;
partitions: (string | null)[];
advancedSettings: Map<AdvancedSettingsType, boolean>;
}
): DehydratedIrisGridPanelState {
const { isSelectingPartition, partitions, advancedSettings } =
irisGridPanelState;
// Return value will be serialized, should not contain undefined
return {
isSelectingPartition,
partitions,
advancedSettings: [...advancedSettings],
};
}
/**
* Import the saved IrisGridPanel state.
* @param model The model the state is being hydrated with
* @param irisGridPanelState Exported IrisGridPanel state
* @returns The state to apply to the IrisGridPanel
*/
static hydrateIrisGridPanelState(
model: IrisGridModel,
irisGridPanelState: DehydratedIrisGridPanelState
): {
isSelectingPartition: boolean;
partitions: (string | null)[];
advancedSettings: Map<AdvancedSettingsType, boolean>;
} {
const { isSelectingPartition, advancedSettings } = irisGridPanelState;
let partitions: (string | null)[] = [];
if (isPanelStateV2(irisGridPanelState)) {
partitions = irisGridPanelState.partitions;
} else if (irisGridPanelState.partition != null) {
partitions = [irisGridPanelState.partition];
}
return {
isSelectingPartition,
partitions,
advancedSettings: new Map([
...AdvancedSettings.DEFAULTS,
...advancedSettings,
]),
};
}
/**
* Export the quick filters to JSON striginfiable object
* @param quickFilters The quick filters to dehydrate
* @returns The dehydrated quick filters
*/
static dehydrateQuickFilters(
quickFilters: ReadonlyQuickFilterMap
): DehydratedQuickFilter[] {
return [...quickFilters].map(([columnIndex, quickFilter]) => {
const { text } = quickFilter;
return [columnIndex, { text }];
});
}
static dehydrateLong<T>(value: T): string | null {
return value != null ? `${value}` : null;
}
/**
* Export the sorts from the provided table sorts to JSON stringifiable object
* @param sorts The table sorts
* @returns The dehydrated sorts
*/
static dehydrateSort(sorts: readonly SortDescriptor[]): DehydratedSort[] {
return sorts.map(sort => {
const { column, isAbs, direction } = sort;
return {
column: column.name,
isAbs,
direction,
};
});
}
/**
* Pulls just the table settings from the panel state, eg. filters/sorts
* @param panelState The dehydrated panel state
* @returns A dehydrated table settings object, { partition, partitionColumn, advancedFilters, quickFilters, sorts }
*/
static extractTableSettings<AF, QF, S>(
panelState: {
irisGridState: { advancedFilters: AF; quickFilters: QF; sorts: S };
irisGridPanelState: DehydratedIrisGridPanelState;
},
inputFilters: InputFilter[] = []
): {
partitions: unknown[];
advancedFilters: AF;
inputFilters: InputFilter[];
quickFilters: QF;
sorts: S;
} {
const { irisGridPanelState, irisGridState } = panelState;
const partitions = isPanelStateV2(irisGridPanelState)
? irisGridPanelState.partitions
: [irisGridPanelState.partition];
const { advancedFilters, quickFilters, sorts } = irisGridState;
return {
advancedFilters,
inputFilters,
partitions,
quickFilters,
sorts,
};
}
static getInputFiltersForColumns(
columns: readonly { name: string; type: string }[],
inputFilters: readonly InputFilter[] = []
): InputFilter[] {
return inputFilters.filter(({ name, type }) =>
columns.find(
({ name: columnName, type: columnType }) =>
columnName === name && columnType === type
)
);
}
static getFiltersFromFilterMap(
filterMap: ReadonlyAdvancedFilterMap | ReadonlyQuickFilterMap
): DhType.FilterCondition[] {
const filters = [];
const keys = Array.from(filterMap.keys());
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
const item = filterMap.get(key);
if (item?.filter != null) {
filters.push(item.filter);
}
}
return filters;
}
/**
* Get array of hidden column indexes
* @param userColumnWidths Map of user column widths
* @returns Array of hidden column indexes
*/
static getHiddenColumns(userColumnWidths: ModelSizeMap): ModelIndex[] {
return [...userColumnWidths.entries()]
.filter(([, value]) => value === 0)
.map(([key]) => key);
}
static parseCustomColumnNames(
customColumns: readonly ColumnName[]
): ColumnName[] {
return customColumns.map(customColumn => customColumn.split('=')[0]);
}
static getRemovedCustomColumnNames(
oldCustomColumns: readonly ColumnName[],
customColumns: readonly ColumnName[]
): ColumnName[] {
const oldCustomColumnsNames =
IrisGridUtils.parseCustomColumnNames(oldCustomColumns);
const customColumnNames =
IrisGridUtils.parseCustomColumnNames(customColumns);
return oldCustomColumnsNames.filter(
oldCustomColumnName => !customColumnNames.includes(oldCustomColumnName)
);
}
static removeSortsInColumns(
sorts: readonly SortDescriptor[],
columnNames: readonly string[]
): readonly SortDescriptor[] {
return sorts.filter(sort => !columnNames.includes(sort.column.name));
}
static removeFiltersInColumns<T>(
columns: readonly DhType.Column[],
filters: ReadonlyMap<number, T>,
removedColumnNames: readonly ColumnName[]
): Map<number, T> {
const columnNames = columns.map(({ name }) => name);
const newFilter = new Map(filters);
removedColumnNames.forEach(columnName =>
newFilter.delete(columnNames.indexOf(columnName))
);
return newFilter;
}
static removeColumnFromMovedColumns(
columns: readonly DhType.Column[],
movedColumns: readonly MoveOperation[],
removedColumnNames: readonly ColumnName[]
): MoveOperation[] {
const columnNames = columns.map(({ name }) => name);
let newMoves = [...movedColumns];
for (let i = 0; i < removedColumnNames.length; i += 1) {
const removedColumnName = removedColumnNames[i];
let removedColumnIndex = columnNames.findIndex(
name => name === removedColumnName
);
const moves: MoveOperation[] = [];
for (let j = 0; j < newMoves.length; j += 1) {
const move = newMoves[j];
const newMove = { ...move };
let [fromStart, fromEnd] = Array.isArray(move.from)
? move.from
: [move.from, move.from];
if (removedColumnIndex <= move.to) {
newMove.to -= 1;
}
// If equal to fromStart, the new fromStart would stay the same
// It's just the next element in the range which will have the same index after deletion
if (removedColumnIndex < fromStart) {
fromStart -= 1;
}
if (removedColumnIndex <= fromEnd) {
fromEnd -= 1;
}
if (fromStart <= fromEnd && fromStart !== newMove.to) {
if (fromStart === fromEnd) {
moves.push({ ...newMove, from: fromStart });
} else {
moves.push({ ...newMove, from: [fromStart, fromEnd] });
}
}
// get the next index of the removed column after the move is applied
// eslint-disable-next-line prefer-destructuring
removedColumnIndex = GridUtils.applyItemMoves(
removedColumnIndex,
removedColumnIndex,
[move]
)[0][0];
}
newMoves = moves;
columnNames.splice(
columnNames.findIndex(name => name === removedColumnName),
1
);
}
return newMoves;
}
static removeColumnsFromSelectDistinctColumns(
selectDistinctColumns: readonly ColumnName[],
removedColumnNames: readonly ColumnName[]
): ColumnName[] {
return selectDistinctColumns.filter(
columnName => !removedColumnNames.includes(columnName)
);
}
static getVisibleColumnsInRange(
tableColumns: readonly DhType.Column[],
left: number,
right: number,
movedColumns: readonly MoveOperation[],
hiddenColumns: readonly number[]
): DhType.Column[] {
const columns: DhType.Column[] = [];
for (let i = left; i <= right; i += 1) {
const modelIndex = GridUtils.getModelIndex(i, movedColumns);
if (
modelIndex >= 0 &&
modelIndex < tableColumns.length &&
!hiddenColumns.includes(modelIndex)
) {
columns.push(tableColumns[modelIndex]);
}
}
return columns;
}
static getPrevVisibleColumns(
tableColumns: readonly DhType.Column[],
startIndex: VisibleIndex,
count: number,
movedColumns: readonly MoveOperation[],
hiddenColumns: readonly VisibleIndex[]
): DhType.Column[] {
const columns = [];
let i = startIndex;
while (i >= 0 && columns.length < count) {
const modelIndex = GridUtils.getModelIndex(i, movedColumns);
if (
modelIndex >= 0 &&
modelIndex < tableColumns.length &&
!hiddenColumns.includes(modelIndex)
) {
columns.unshift(tableColumns[modelIndex]);
}
i -= 1;
}
return columns;
}
static getNextVisibleColumns(
tableColumns: readonly DhType.Column[],
startIndex: VisibleIndex,
count: number,
movedColumns: readonly MoveOperation[],
hiddenColumns: readonly VisibleIndex[]
): DhType.Column[] {
const columns = [];
let i = startIndex;
while (i < tableColumns.length && columns.length < count) {
const modelIndex = GridUtils.getModelIndex(i, movedColumns);
if (
modelIndex >= 0 &&
modelIndex < tableColumns.length &&
!hiddenColumns.includes(modelIndex)
) {
columns.push(tableColumns[modelIndex]);
}
i += 1;
}
return columns;
}
static getColumnsToFetch(
tableColumns: readonly DhType.Column[],
viewportColumns: readonly DhType.Column[],
alwaysFetchColumnNames: readonly ColumnName[]
): DhType.Column[] {
const columnsToFetch = [...viewportColumns];
alwaysFetchColumnNames.forEach(columnName => {
const column = tableColumns.find(({ name }) => name === columnName);
if (column != null && !viewportColumns.includes(column)) {
columnsToFetch.push(column);
}
});
return columnsToFetch;
}
static getModelViewportColumns(
columns: readonly DhType.Column[],
left: number | null,
right: number | null,
movedColumns: readonly MoveOperation[],
hiddenColumns: readonly VisibleIndex[] = [],
alwaysFetchColumnNames: readonly ColumnName[] = [],
bufferPages = 0
): DhType.Column[] | undefined {
if (left == null || right == null) {
return undefined;
}
const columnsCenter = IrisGridUtils.getVisibleColumnsInRange(
columns,
left,
right,
movedColumns,
hiddenColumns
);
const bufferWidth = columnsCenter.length * bufferPages;
const columnsLeft = IrisGridUtils.getPrevVisibleColumns(
columns,
left - 1,
bufferWidth,
movedColumns,
hiddenColumns
);
const columnsRight = IrisGridUtils.getNextVisibleColumns(
columns,
right + 1,
bufferWidth,
movedColumns,
hiddenColumns
);
const bufferedColumns = [...columnsLeft, ...columnsCenter, ...columnsRight];
return IrisGridUtils.getColumnsToFetch(
columns,
bufferedColumns,
alwaysFetchColumnNames
);
}
/**
* Validate whether the ranges passed in are valid to take a snapshot from.
* Multiple selections are valid if all of the selected rows have the same columns selected.
*
* @param ranges The ranges to validate
* @returns True if the ranges are valid, false otherwise
*/
static isValidSnapshotRanges(ranges: readonly GridRange[]): boolean {
if (ranges == null || ranges.length === 0) {
return false;
}
// To verify all the rows selected have the same set of columns selected, build a map with string representations
// of each range.
const rangeMap = new Map();
for (let i = 0; i < ranges.length; i += 1) {
const range = ranges[i];
const rowMapIndex = `${range.startRow}:${range.endRow}`;
const columnMapIndex = `${range.startColumn}:${range.endColumn}`;
if (!rangeMap.has(rowMapIndex)) {
rangeMap.set(rowMapIndex, []);
}
rangeMap.get(rowMapIndex).push(columnMapIndex);
}
const keys = [...rangeMap.keys()];
const matchColumnRanges = rangeMap.get(keys[0]).sort().join(',');
for (let i = 1; i < keys.length; i += 1) {
if (rangeMap.get(keys[i]).sort().join(',') !== matchColumnRanges) {
return false;
}
}
return true;
}
/**
* Check if the provided value is a valid table index
* @param value A value to check if it's a valid table index
*/
static isValidIndex(value: unknown): boolean {
if (!Number.isInteger(value)) {
return false;
}
if (!(typeof value === 'number')) {
return false;
}
return value >= 0;
}
/**
* Returns all columns used in any of the ranges provided
* @param ranges The model ranges to get columns for
* @param allColumns All the columns to pull from
* @returns The columns selected in the range
*/
static columnsFromRanges(
ranges: readonly GridRange[],
allColumns: readonly DhType.Column[]
): DhType.Column[] {
if (ranges == null || ranges.length === 0) {
return [];
}
if (ranges[0].startColumn === null && ranges[0].endColumn === null) {
// Snapshot of all the columns
return [...allColumns];
}
const columnSet = new Set<ModelIndex>();
for (let i = 0; i < ranges.length; i += 1) {
const range = ranges[i];
assertNotNull(range.startColumn);
assertNotNull(range.endColumn);
for (
let c = range.startColumn ?? 0;
c <= (range.endColumn ?? allColumns.length - 1);
c += 1
) {
columnSet.add(c);
}
}
return [...columnSet].map(c => allColumns[c]);
}
/**
* Transforms an iris data snapshot into a simple data matrix
* @param data The Iris formatted table data
* @returns A matrix of the values of the data
*/
static snapshotDataToMatrix(data: DhType.TableData): unknown[][] {
const { columns, rows } = data;
const result = [];
for (let r = 0; r < rows.length; r += 1) {
const row = rows[r];
const rowData = [];
for (let c = 0; c < columns.length; c += 1) {
const column = columns[c];
const value = row.get(column);
rowData.push(value);
}
result.push(rowData);
}
return result;
}
/**
* Hydrate model rollup config
* @param originalColumns Original model columns
* @param config Dehydrated rollup config
* @param aggregationSettings Aggregation settings
* @returns Rollup config for the model
*/
static getModelRollupConfig(
originalColumns: readonly DhType.Column[],
config: UIRollupConfig | undefined,
aggregationSettings: AggregationSettings
): DhType.RollupConfig | null {
if ((config?.columns?.length ?? 0) === 0) {
return null;
}
const {
columns: groupingColumns = [],
showConstituents: includeConstituents = true,
showNonAggregatedColumns = true,
includeDescriptions = true,
} = config ?? {};
const { aggregations = [] } = aggregationSettings ?? {};
const filteredAggregations = aggregations.filter(
({ operation }) => !AggregationUtils.isRollupProhibited(operation)
);
const aggregationColumns = filteredAggregations.map(
({ operation, selected, invert }) =>
AggregationUtils.isRollupOperation(operation)
? []
: AggregationUtils.getOperationColumnNames(
originalColumns,
operation,
selected,
invert
)
);
const aggregationMap = {} as Record<AggregationOperation, string[]>;
// Aggregation columns should show first, add them first
for (let i = 0; i < filteredAggregations.length; i += 1) {
aggregationMap[filteredAggregations[i].operation] = aggregationColumns[i];
}
if (showNonAggregatedColumns) {
// Filter out any column that already has an aggregation or grouping
const nonAggregatedColumnSet = new Set(
originalColumns
.map(c => c.name)
.filter(name => !groupingColumns.includes(name))
);
aggregationColumns.forEach(columns => {
columns.forEach(name => nonAggregatedColumnSet.delete(name));
});
if (nonAggregatedColumnSet.size > 0) {
const existingColumns =
aggregationMap[AggregationOperation.FIRST] ?? [];
aggregationMap[AggregationOperation.FIRST] = [
...existingColumns,
...nonAggregatedColumnSet,
];
}
}
return {
groupingColumns,
includeConstituents,
includeDescriptions,
aggregations: aggregationMap,
};
}
/**
* @param pendingDataMap Map of pending data
* @returns A map with the errors in the pending data
*/
static getPendingErrors(pendingDataMap: Map<number, UIRow>): void {
pendingDataMap.forEach((row, rowIndex) => {
if (!IrisGridUtils.isValidIndex(rowIndex)) {
throw new Error(`Invalid rowIndex ${rowIndex}`);
}
const { data } = row;
data.forEach((value, columnIndex) => {
if (!IrisGridUtils.isValidIndex(columnIndex)) {
throw new Error(`Invalid columnIndex ${columnIndex}`);
}
});
});
}
/**
* Retrieves a column from the provided array at the index, or `null` and logs an error if it's invalid
*
* @param columns The columns to get the column from
* @param columnIndex The column index to get
*/
static getColumn(
columns: readonly DhType.Column[],
columnIndex: ModelIndex
): DhType.Column | null {
if (columnIndex < columns.length) {
return columns[columnIndex];
}
log.error('Unable to retrieve column', columnIndex, '>=', columns.length);
return null;
}
/**
* Retrieves a column from the provided array matching the name, or `null` and logs an error if not found
* @param columns The columns to get the column from
* @param columnName The column name to retrieve
*/
static getColumnByName(
columns: readonly DhType.Column[],
columnName: ColumnName
): DhType.Column | undefined {
// Columns can contain ColumnBy sources with negative indexes
const column = Object.values(columns).find(
({ name }) => name === columnName
);
if (column == null) {
log.error(
'Unable to retrieve column by name',
columnName,
columns.map(({ name }) => name)
);
}
return column;
}
/**
* Get filter configs with column names changed to indexes, exclude missing columns
* @param columns The columns to get column indexes from
* @param filters Filter configs
* @returns Updated filter configs with column names changed to indexes
*/
static changeFilterColumnNamesToIndexes<T>(
columns: readonly DhType.Column[],
filters: { name: ColumnName; filter: T }[]
): [number, T][] {
return filters
.map(({ name, filter }): null | [number, T] => {
const index = columns.findIndex(column => column.name === name);
return index < 0 ? null : [index, filter];
})
.filter(filterConfig => filterConfig != null) as [number, T][];
}
/**
* @param columnType The column type that the filters will be applied to.
* @param filterList The list of filters to be combined.
* @returns The combination of the filters in filterList as text.
*/
static combineFiltersFromList(
columnType: string | null,
filterList: FilterData[]
): string {
filterList.sort((a, b) => {
// move all 'equals' comparisons to end of list
if (a.operator === 'eq' && b.operator !== 'eq') {
return 1;
}
if (a.operator !== 'eq' && b.operator === 'eq') {
return -1;
}
return a.startColumnIndex - b.startColumnIndex;
});
let combinedText = '';
for (let i = 0; i < filterList.length; i += 1) {
const { text, value, operator } = filterList[i];
if (value !== undefined) {
let symbol = '';
if (operator !== undefined) {
if (value == null && operator === 'eq') {
symbol = '=';
} else if (operator !== 'eq') {
if (operator === 'startsWith' || operator === 'endsWith') {
symbol = '*';
} else {
symbol = TableUtils.getFilterOperatorString(operator);
}
}
}