-
Notifications
You must be signed in to change notification settings - Fork 9
/
GridModel.ts
1840 lines (1568 loc) · 61.6 KB
/
GridModel.ts
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
/*
* This file belongs to Hoist, an application development toolkit
* developed by Extremely Heavy Industries (www.xh.io | [email protected])
*
* Copyright © 2024 Extremely Heavy Industries Inc.
*/
import {
CellClickedEvent,
CellContextMenuEvent,
CellDoubleClickedEvent,
ColumnEvent,
RowClickedEvent,
RowDoubleClickedEvent
} from '@ag-grid-community/core';
import {AgGridModel} from '@xh/hoist/cmp/ag-grid';
import {
Column,
ColumnCellClassRuleFn,
ColumnGroup,
ColumnGroupSpec,
ColumnSpec,
GridAutosizeMode,
GridFilterModelConfig,
GridGroupSortFn,
TreeStyle
} from '@xh/hoist/cmp/grid';
import {GridFilterModel} from '@xh/hoist/cmp/grid/filter/GridFilterModel';
import {fragment, p} from '@xh/hoist/cmp/layout';
import {
Awaitable,
HoistModel,
HSide,
managed,
PlainObject,
SizingMode,
Some,
TaskObserver,
VSide,
XH
} from '@xh/hoist/core';
import {
FieldSpec,
Store,
StoreConfig,
StoreRecord,
StoreRecordId,
StoreRecordOrId,
StoreSelectionConfig,
StoreSelectionModel,
StoreTransaction
} from '@xh/hoist/data';
import {ColChooserModel as DesktopColChooserModel} from '@xh/hoist/dynamics/desktop';
import {ColChooserModel as MobileColChooserModel} from '@xh/hoist/dynamics/mobile';
import {Icon} from '@xh/hoist/icon';
import {action, bindable, makeObservable, observable, when} from '@xh/hoist/mobx';
import {wait, waitFor} from '@xh/hoist/promise';
import {ExportOptions} from '@xh/hoist/svc/GridExportService';
import {SECONDS} from '@xh/hoist/utils/datetime';
import {
deepFreeze,
executeIfFunction,
logWithDebug,
throwIf,
warnIf,
withDefault
} from '@xh/hoist/utils/js';
import equal from 'fast-deep-equal';
import {
castArray,
clone,
cloneDeep,
compact,
defaults,
defaultsDeep,
every,
find,
first,
forEach,
isArray,
isEmpty,
isFunction,
isNil,
isPlainObject,
isString,
isUndefined,
keysIn,
last,
max,
min,
omit,
pick,
pull
} from 'lodash';
import {ReactNode} from 'react';
import {GridAutosizeOptions} from './GridAutosizeOptions';
import {GridContextMenuSpec} from './GridContextMenu';
import {GridSorter, GridSorterLike} from './GridSorter';
import {initPersist} from './impl/InitPersist';
import {managedRenderer} from './impl/Utils';
import {
ColChooserConfig,
ColumnState,
GridModelPersistOptions,
GroupRowRenderer,
RowClassFn,
RowClassRuleFn
} from './Types';
export interface GridConfig {
/** Columns for this grid. */
columns?: Array<ColumnSpec | ColumnGroupSpec>;
/** Column configs to be set on all columns. Merges deeply. */
colDefaults?: Partial<ColumnSpec>;
/**
* A Store instance, or a config with which to create a Store. If not supplied,
* store fields will be inferred from columns config.
*/
store?: Store | StoreConfig;
/** True if grid is a tree grid (default false). */
treeMode?: boolean;
/** Location for docked summary row(s). Requires `store.summaryRecords` to be populated. */
showSummary?: boolean | VSide;
/** Specification of selection behavior. Defaults to 'single' (desktop) and 'disabled' (mobile) */
selModel?: StoreSelectionModel | StoreSelectionConfig | 'single' | 'multiple' | 'disabled';
/** Config with which to create a GridFilterModel, or `true` to enable default. Desktop only.*/
filterModel?: GridFilterModelConfig | boolean;
/** Config with which to create a ColChooserModel, or boolean `true` to enable default.*/
colChooserModel?: ColChooserConfig | boolean;
/**
* Function to be called when the user triggers GridModel.restoreDefaultsAsync(). This
* function will be called after the built-in defaults have been restored, and can be
* used to restore application specific defaults.
*/
restoreDefaultsFn?: () => Awaitable<void>;
/**
* Confirmation warning to be presented to user before restoring default grid state. Set to
* null to skip user confirmation.
*/
restoreDefaultsWarning?: ReactNode;
/** Options governing persistence. */
persistWith?: GridModelPersistOptions;
/**
* Text/element to display if grid has no records. Defaults to null, in which case no empty
* text will be shown.
*/
emptyText?: ReactNode;
/** True (default) to hide empty text until after the Store has been loaded at least once. */
hideEmptyTextBeforeLoad?: boolean;
/** Initial sort to apply to grid data. */
sortBy?: Some<GridSorterLike>;
/** Column ID(s) by which to do full-width grouping. */
groupBy?: Some<string>;
/** True (default) to show a count of group member rows within each full-width group row. */
showGroupRowCounts?: boolean;
/** Size of text in grid. If undefined, will default and bind to `XH.sizingMode`. */
sizingMode?: SizingMode;
/** True to highlight the currently hovered row. */
showHover?: boolean;
/** True to render row borders. */
rowBorders?: boolean;
/** Specify treeMode-specific styling. */
treeStyle?: TreeStyle;
/** True to use alternating backgrounds for rows. */
stripeRows?: boolean;
/** True to render cell borders. */
cellBorders?: boolean;
/** True to highlight the focused cell with a border. */
showCellFocus?: boolean;
/** True to suppress display of the grid's header row. */
hideHeaders?: boolean;
/** 'hover' to only show column header menu icons on hover. */
headerMenuDisplay?: 'always' | 'hover';
/** True to disallow moving columns outside of their groups. */
lockColumnGroups?: boolean;
/** True to allow the user to manually pin / unpin columns via UI affordances. */
enableColumnPinning?: boolean;
/** True to enable exporting this grid and install default context menu items. */
enableExport?: boolean;
/** Default export options. */
exportOptions?: ExportOptions;
/**
* Closure to generate CSS class names for a row.
* NOTE that, once added, classes will *not* be removed if the data changes.
* Use `rowClassRules` instead if StoreRecord data can change across refreshes.
*/
rowClassFn?: RowClassFn;
/**
* Object keying CSS class names to functions determining if they should be added or
* removed from the row. See Ag-Grid docs on "row styles" for details.
*/
rowClassRules?: Record<string, RowClassRuleFn>;
/** Height (in px) of a group row. Note that this will override `sizingMode` for group rows. */
groupRowHeight?: number;
/** Function used to render group rows. */
groupRowRenderer?: GroupRowRenderer;
/**
* Function to use to sort full-row groups. Called with two group values to compare
* in the form of a standard JS comparator. Default is an ascending string sort.
* Set to `null` to prevent sorting of groups.
*/
groupSortFn?: GridGroupSortFn;
/**
* Callback when a key down event is detected on the grid. Note that the ag-Grid API provides
* limited ability to customize keyboard handling. This handler is designed to allow
* applications to work around this.
*/
onKeyDown?: (e: KeyboardEvent) => void;
/**
* Callback when a row is clicked. (Note that the event received may be null - e.g. for
* clicks on full-width group rows.)
*/
onRowClicked?: (e: RowClickedEvent) => void;
/**
* Callback when a row is double-clicked. (Note that the event received may be null - e.g.
* for clicks on full-width group rows.)
*/
onRowDoubleClicked?: (e: RowDoubleClickedEvent) => void;
/**
* Callback when a cell is clicked.
*/
onCellClicked?: (e: CellClickedEvent) => void;
/**
* Callback when a cell is double-clicked.
*/
onCellDoubleClicked?: (e: CellDoubleClickedEvent) => void;
/**
* Callback when the context menu is opened. Note that the event received can also be
* triggered via a long press (aka tap and hold) on mobile devices.
*/
onCellContextMenu?: (e: CellContextMenuEvent) => void;
/**
* Number of clicks required to expand / collapse a parent row in a tree grid. Defaults
* to 2 for desktop, 1 for mobile. Any other value prevents clicks on row body from
* expanding / collapsing (requires click on tree col affordance to expand/collapse).
*/
clicksToExpand?: number;
/**
* Array of RecordActions, dividers, or token strings with which to create a context menu.
* May also be specified as a function returning same or false to omit context menu from grid.
*/
contextMenu?: GridContextMenuSpec | false;
/**
* Governs if the grid should reuse a limited set of DOM elements for columns visible in the
* scroll area (versus rendering all columns). Consider this performance optimization for
* grids with a very large number of columns obscured by horizontal scrolling. Note that
* setting this value to true may limit the ability of the grid to autosize offscreen columns
* effectively. Default false.
*/
useVirtualColumns?: boolean;
/** Default autosize options. */
autosizeOptions?: GridAutosizeOptions;
/** True to enable full row editing. Default false. */
fullRowEditing?: boolean;
/**
* Number of clicks required to begin inline-editing a cell. May be 2 (default) or 1 - any
* other value prevents user clicks from starting an edit.
*/
clicksToEdit?: number;
/**
* Set to true to if application will be reloading data when the sortBy property changes on
* this model (either programmatically, or via user-click.) Useful for applications with large
* data sets that are performing external, or server-side sorting and filtering. Setting this
* flag means that the grid should not immediately respond to user or programmatic changes to
* the sortBy property, but will instead wait for the next load of data, which is assumed to be
* pre-sorted. Default false.
*/
externalSort?: boolean;
/**
* Set to true to highlight a row on click. Intended to provide feedback to users in grids
* without selection. Note this setting overrides the styling used by Column.highlightOnChange,
* and is not recommended for use alongside that feature. Default true for mobiles,
* otherwise false.
*/
highlightRowOnClick?: boolean;
/**
* Flags for experimental features. These features are designed for early client-access and
* testing, but are not yet part of the Hoist API.
*/
experimental?: PlainObject;
/** Extra app-specific data for the GridModel. */
appData?: PlainObject;
/** @internal */
xhImpl?: boolean;
}
/**
* Core Model for a Grid, specifying the grid's data store, column definitions,
* sorting/grouping/selection state, and context menu configuration.
*
* This is the primary application entry-point for specifying Grid component options and behavior.
*
* This model also supports nested tree data. To show a tree:
* 1) Bind this model to a store with hierarchical records.
* 2) Set `treeMode: true` on this model.
* 3) Include a single column with `isTreeColumn: true`. This column will provide expand /
* collapse controls and indent child columns in addition to displaying its own data.
*
*/
export class GridModel extends HoistModel {
static DEFAULT_RESTORE_DEFAULTS_WARNING = fragment(
p(
'This action will clear any customizations you have made to this grid, including filters, column selection, ordering, and sizing.'
),
p('OK to proceed?')
);
static DEFAULT_AUTOSIZE_MODE: GridAutosizeMode = 'onSizingModeChange';
//------------------------
// Immutable public properties
//------------------------
store: Store;
selModel: StoreSelectionModel;
treeMode: boolean;
colChooserModel: HoistModel;
rowClassFn: RowClassFn;
rowClassRules: Record<string, RowClassRuleFn>;
contextMenu: GridContextMenuSpec;
groupRowHeight: number;
groupRowRenderer: GroupRowRenderer;
groupSortFn: GridGroupSortFn;
showGroupRowCounts: boolean;
enableColumnPinning: boolean;
enableExport: boolean;
externalSort: boolean;
exportOptions: ExportOptions;
useVirtualColumns: boolean;
autosizeOptions: GridAutosizeOptions;
restoreDefaultsFn: () => Awaitable<void>;
restoreDefaultsWarning: ReactNode;
fullRowEditing: boolean;
hideEmptyTextBeforeLoad: boolean;
highlightRowOnClick: boolean;
clicksToExpand: number;
clicksToEdit: number;
lockColumnGroups: boolean;
headerMenuDisplay: 'always' | 'hover';
colDefaults: Partial<ColumnSpec>;
experimental: PlainObject;
onKeyDown: (e: KeyboardEvent) => void;
onRowClicked: (e: RowClickedEvent) => void;
onRowDoubleClicked: (e: RowDoubleClickedEvent) => void;
onCellClicked: (e: CellClickedEvent) => void;
onCellDoubleClicked: (e: CellDoubleClickedEvent) => void;
onCellContextMenu: (e: CellContextMenuEvent) => void;
appData: PlainObject;
@managed filterModel: GridFilterModel;
@managed agGridModel: AgGridModel;
//------------------------
// Observable API
//------------------------
@observable.ref columns: Array<ColumnGroup | Column> = [];
@observable.ref columnState: ColumnState[] = [];
@observable.ref expandState: any = {};
@observable.ref sortBy: GridSorter[] = [];
@observable.ref groupBy: string[] = null;
get persistableColumnState(): ColumnState[] {
return this.cleanColumnState(this.columnState);
}
@bindable showSummary: boolean | VSide = false;
@bindable.ref emptyText: ReactNode;
@bindable treeStyle: TreeStyle;
/**
* Flag to track inline editing at a granular level. Will toggle each time row
* or cell editing is activated or ended.
*/
@observable isEditing = false;
/**
* Flag to track inline editing at a general level.
* Will not change during transient navigation from cell to cell or row to row,
* but rather is debounced such that grid editing will need to "settle" for a
* short time before toggling.
*/
@observable isInEditingMode: boolean = false;
static defaultContextMenu = [
'filter',
'-',
'copy',
'copyWithHeaders',
'copyCell',
'-',
'expandCollapseAll',
'-',
'exportExcel',
'exportCsv',
'-',
'restoreDefaults',
'-',
'colChooser',
'autosizeColumns'
];
private _defaultState; // initial state provided to ctor - powers restoreDefaults().
/**
* Is autosizing enabled on this grid?
* To disable autosizing, set autosizeOptions.mode to GridAutosizeMode.DISABLED.
*/
get autosizeEnabled(): boolean {
return this.autosizeOptions.mode !== 'disabled';
}
/** Tracks execution of filtering operations.*/
@managed filterTask = TaskObserver.trackAll();
/** Tracks execution of autosize operations. */
@managed autosizeTask = TaskObserver.trackAll();
/** @internal - used internally by any GridFindField that is bound to this GridModel. */
@bindable xhFindQuery: string = null;
constructor(config: GridConfig) {
super();
makeObservable(this);
let {
store,
columns,
colDefaults = {},
treeMode = false,
showSummary = false,
selModel,
filterModel,
colChooserModel,
emptyText = null,
hideEmptyTextBeforeLoad = true,
sortBy = [],
groupBy = null,
showGroupRowCounts = true,
externalSort = false,
persistWith,
sizingMode,
showHover = false,
rowBorders = XH.isMobileApp,
rowClassFn = null,
rowClassRules = {},
cellBorders = false,
treeStyle = 'highlights',
stripeRows = !treeMode || treeStyle === 'none',
showCellFocus = false,
hideHeaders = false,
headerMenuDisplay = 'always',
lockColumnGroups = true,
enableColumnPinning = true,
enableExport = false,
exportOptions = {},
groupRowHeight,
groupRowRenderer,
groupSortFn,
onKeyDown,
onRowClicked,
onRowDoubleClicked,
onCellClicked,
onCellDoubleClicked,
onCellContextMenu,
clicksToExpand = XH.isMobileApp ? 1 : 2,
contextMenu,
useVirtualColumns = false,
autosizeOptions = {},
restoreDefaultsFn,
restoreDefaultsWarning = GridModel.DEFAULT_RESTORE_DEFAULTS_WARNING,
fullRowEditing = false,
clicksToEdit = 2,
highlightRowOnClick = XH.isMobileApp,
experimental,
appData,
xhImpl,
...rest
}: GridConfig = config;
this.xhImpl = xhImpl;
this._defaultState = {columns, sortBy, groupBy};
this.treeMode = treeMode;
this.treeStyle = treeStyle;
this.showSummary = showSummary;
this.emptyText = emptyText;
this.hideEmptyTextBeforeLoad = hideEmptyTextBeforeLoad;
this.headerMenuDisplay = headerMenuDisplay;
this.rowClassFn = rowClassFn;
this.rowClassRules = rowClassRules;
this.groupRowHeight = groupRowHeight;
this.groupRowRenderer = managedRenderer(groupRowRenderer, 'GROUP_ROW');
this.groupSortFn = withDefault(groupSortFn, this.defaultGroupSortFn);
this.showGroupRowCounts = showGroupRowCounts;
this.contextMenu =
contextMenu === false ? [] : withDefault(contextMenu, GridModel.defaultContextMenu);
this.useVirtualColumns = useVirtualColumns;
this.externalSort = externalSort;
this.autosizeOptions = defaults(
{...autosizeOptions},
{
mode: GridModel.DEFAULT_AUTOSIZE_MODE,
renderedRowsOnly: false,
includeCollapsedChildren: false,
showMask: false,
// Larger buffer on mobile (perhaps counterintuitively) to minimize clipping due to
// any autosize mis-calc. Manual col resizing on mobile is super annoying!
bufferPx: XH.isMobileApp ? 10 : 5,
fillMode: 'none'
}
);
this.restoreDefaultsFn = restoreDefaultsFn;
this.restoreDefaultsWarning = restoreDefaultsWarning;
this.fullRowEditing = fullRowEditing;
this.clicksToExpand = clicksToExpand;
this.clicksToEdit = clicksToEdit;
this.highlightRowOnClick = highlightRowOnClick;
throwIf(
autosizeOptions.fillMode &&
!['all', 'left', 'right', 'none'].includes(autosizeOptions.fillMode),
`Unsupported value for fillMode.`
);
this.lockColumnGroups = lockColumnGroups;
this.enableColumnPinning = enableColumnPinning;
this.enableExport = enableExport;
this.exportOptions = exportOptions;
Object.assign(this, rest);
this.colDefaults = colDefaults;
this.parseAndSetColumnsAndStore(columns, store);
this.setGroupBy(groupBy);
this.setSortBy(sortBy);
sizingMode = this.parseSizingMode(sizingMode);
this.agGridModel = new AgGridModel({
sizingMode,
showHover,
rowBorders,
stripeRows,
cellBorders,
showCellFocus,
hideHeaders,
xhImpl
});
this.colChooserModel = this.parseChooserModel(colChooserModel);
this.selModel = this.parseSelModel(selModel);
this.filterModel = this.parseFilterModel(filterModel);
if (persistWith) initPersist(this, persistWith);
this.experimental = this.parseExperimental(experimental);
this.onKeyDown = onKeyDown;
this.onRowClicked = onRowClicked;
this.onRowDoubleClicked = onRowDoubleClicked;
this.onCellClicked = onCellClicked;
this.onCellDoubleClicked = onCellDoubleClicked;
this.onCellContextMenu = onCellContextMenu;
this.appData = appData ? clone(appData) : {};
this.addReaction({
track: () => this.isEditing,
run: isEditing => (this.isInEditingMode = isEditing),
debounce: 500
});
if (!isEmpty(rest)) {
const keys = keysIn(rest);
throw XH.exception(
`Key(s) '${keys}' not supported in GridModel. For custom data, use the 'appData' property.`
);
}
}
/**
* Restore the column, sorting, and grouping configs as specified by the application at
* construction time. This is the state without any saved grid state or user changes applied.
* This method will clear the persistent grid state saved for this grid, if any.
*
* @returns true if defaults were restored
*/
async restoreDefaultsAsync(): Promise<boolean> {
if (this.restoreDefaultsWarning) {
const confirmed = await XH.confirm({
message: this.restoreDefaultsWarning,
confirmProps: {
text: 'Yes, restore defaults',
icon: Icon.reset(),
intent: 'primary'
}
});
if (!confirmed) return false;
}
const {columns, sortBy, groupBy} = this._defaultState;
this.setColumns(columns);
this.setSortBy(sortBy);
this.setGroupBy(groupBy);
this.filterModel?.clear();
if (this.autosizeOptions.mode === 'managed') {
await this.autosizeAsync();
}
if (this.restoreDefaultsFn) {
await this.restoreDefaultsFn();
}
return true;
}
/**
* Export grid data using Hoist's server-side export.
*
* @param options - overrides of default export options to use for this export.
*/
async exportAsync(options: ExportOptions = {}) {
throwIf(!this.enableExport, 'Export not enabled for this grid. See GridModel.enableExport');
return XH.gridExportService.exportAsync(this, {...this.exportOptions, ...options});
}
/**
* Export grid data using ag-Grid's built-in client-side export.
*
* @param filename - name for exported file.
* @param type - type of export - either 'excel' or 'csv'.
* @param params - passed to agGrid's export functions.
*/
localExport(filename: string, type: 'excel' | 'csv', params: PlainObject = {}) {
const {agApi} = this.agGridModel;
if (!agApi) return;
params = defaults(
{...params},
{
fileName: filename,
processCellCallback: this.formatValuesForExport
}
);
if (type === 'excel') {
agApi.exportDataAsExcel(params);
} else if (type === 'csv') {
agApi.exportDataAsCsv(params);
}
}
/**
* Select records in the grid.
*
* @param records - one or more record(s) / ID(s) to select.
* @param options - additional options containing the following keys:
* ensureVisible - true to make selection visible if it is within a
* collapsed node or outside of the visible scroll window. Default true.
* clearSelection - true to clear previous selection (rather than
* add to it). Default true.
*/
async selectAsync(
records: Some<StoreRecordOrId>,
opts?: {ensureVisible?: boolean; clearSelection?: boolean}
) {
const {ensureVisible = true, clearSelection = true} = opts ?? {};
this.selModel.select(records, clearSelection);
if (ensureVisible) await this.ensureSelectionVisibleAsync();
}
/**
* Select the first row in the grid.
*
* See {@link preSelectFirstAsync} for a useful variant of this method. preSelectFirstAsync()
* will not change the selection if there is already a selection, which is what applications
* typically want to do when loading/reloading a grid.
*
* @param opts - set key 'ensureVisible' to true to make selection visible if it is within a
* collapsed node or outside of the visible scroll window. Default true.
*/
async selectFirstAsync(opts?: {ensureVisible?: boolean}) {
const {ensureVisible = true} = opts ?? {};
await this.whenReadyAsync();
if (!this.isReady) return;
// Get first displayed row with data - i.e. backed by a record, not a full-width group row.
const {selModel} = this,
id = this.agGridModel.getFirstSelectableRowNode()?.data.id;
if (id != null) {
selModel.select(id);
if (ensureVisible) await this.ensureSelectionVisibleAsync();
}
}
/**
* Select the first row in the grid, if no other selection present.
*
* This method delegates to {@link selectFirstAsync}.
*/
async preSelectFirstAsync() {
if (!this.hasSelection) return this.selectFirstAsync();
}
/** Deselect all rows. */
clearSelection() {
this.selModel.clear();
}
/**
* Scroll to ensure the selected record or records are visible.
*
* If multiple records are selected, scroll to the first record and then the last. This will do
* the minimum scrolling necessary to display the start of the selection and as much as
* possible of the rest.
*
* Any selected records that are hidden because their parent rows are collapsed will first
* be revealed by expanding their parent rows.
*/
async ensureSelectionVisibleAsync() {
await this.whenReadyAsync();
if (!this.isReady) return;
return this.ensureRecordsVisibleAsync(this.selectedRecords);
}
/**
* Scroll to ensure the provided record or records are visible.
*
* If multiple records are specified, scroll to the first record and then the last. This will do
* the minimum scrolling necessary to display the start of the provided record and as much as
* possible of the rest.
*
* Any provided records that are hidden because their parent rows are collapsed will first
* be revealed by expanding their parent rows.
*
* @param records - one or more record(s) for which to ensure visibility.
*/
async ensureRecordsVisibleAsync(records: Some<StoreRecord>) {
await this.whenReadyAsync();
if (!this.isReady) return;
records = castArray(records);
const {agApi} = this,
indices = [];
// 1) Expand any nodes that are collapsed
const expandedRows = new Set<string>();
records.forEach(({agId}) => {
for (let row = agApi.getRowNode(agId)?.parent; row; row = row.parent) {
if (!row.expanded) {
agApi.setRowNodeExpanded(row, true);
expandedRows.add(agId);
}
}
});
if (expandedRows.size) {
await waitFor(() =>
every([...expandedRows], it => !isNil(agApi.getRowNode(it).rowIndex))
);
}
// 2) Scroll to all nodes
records.forEach(({agId}) => {
const rowIndex = agApi.getRowNode(agId)?.rowIndex;
if (!isNil(rowIndex)) indices.push(rowIndex);
});
const indexCount = indices.length;
if (indexCount !== records.length) {
this.logWarn('Grid row nodes not found for all provided records.');
}
if (indexCount === 1) {
agApi.ensureIndexVisible(indices[0]);
} else if (indexCount > 1) {
agApi.ensureIndexVisible(max(indices));
agApi.ensureIndexVisible(min(indices));
}
}
/** True if any records are selected. */
get hasSelection(): boolean {
return !this.selModel.isEmpty;
}
/** Currently selected records. */
get selectedRecords(): StoreRecord[] {
return this.selModel.selectedRecords;
}
/** IDs of currently selected records. */
get selectedIds(): StoreRecordId[] {
return this.selModel.selectedIds;
}
/**
* Single selected record, or null if multiple/no records selected.
*
* Note that this getter will also change if just the data of selected record is changed
* due to store loading or editing. Applications only interested in the identity
* of the selection should use {@link selectedId} instead.
*/
get selectedRecord(): StoreRecord {
return this.selModel.selectedRecord;
}
/**
* ID of selected record, or null if multiple/no records selected.
*
* Note that this getter will *not* change if just the data of selected record is changed
* due to store loading or editing. Applications also interested in the contents of the
* of the selection should use the {@link selectedRecord} getter instead.
*/
get selectedId(): StoreRecordId {
return this.selModel.selectedId;
}
/** True if this grid has no records to show in its store. */
get empty(): boolean {
return this.store.empty;
}
get isReady(): boolean {
return this.agGridModel.isReady;
}
get agApi() {
return this.agGridModel.agApi;
}
get sizingMode(): SizingMode {
return this.agGridModel.sizingMode;
}
set sizingMode(v: SizingMode) {
this.agGridModel.sizingMode = v;
}
setSizingMode(v: SizingMode) {
this.agGridModel.sizingMode = v;
}
get showHover(): boolean {
return this.agGridModel.showHover;
}
set showHover(v: boolean) {
this.agGridModel.showHover = v;
}
setShowHover(v: boolean) {
this.agGridModel.showHover = v;
}
get rowBorders(): boolean {
return this.agGridModel.rowBorders;
}
set rowBorders(v: boolean) {
this.agGridModel.rowBorders = v;
}
setRowBorders(v: boolean) {
this.agGridModel.rowBorders = v;
}
get stripeRows(): boolean {
return this.agGridModel.stripeRows;
}
set stripeRows(v: boolean) {
this.agGridModel.stripeRows = v;
}
setStripeRows(v: boolean) {
this.agGridModel.stripeRows = v;
}
get cellBorders(): boolean {
return this.agGridModel.cellBorders;
}
set cellBorders(v: boolean) {
this.agGridModel.cellBorders = v;
}
setCellBorders(v: boolean) {
this.agGridModel.cellBorders = v;
}
get showCellFocus(): boolean {
return this.agGridModel.showCellFocus;
}
set showCellFocus(v: boolean) {
this.agGridModel.showCellFocus = v;
}
setShowCellFocus(v: boolean) {
this.agGridModel.showCellFocus = v;
}
get hideHeaders(): boolean {
return this.agGridModel.hideHeaders;
}
set hideHeaders(v: boolean) {
this.agGridModel.hideHeaders = v;
}
setHideHeaders(v: boolean) {
this.agGridModel.hideHeaders = v;
}
/**
* Apply full-width row-level grouping to the grid for the given column ID(s).
* This method will clear grid grouping if provided any ids without a corresponding column.
* @param colIds - ID(s) for row grouping, null to ungroup.
*/
@action
setGroupBy(colIds: Some<string>) {
colIds = isNil(colIds) ? [] : castArray(colIds);
const invalidColIds = colIds.filter(it => !this.findColumn(this.columns, it));
if (invalidColIds.length) {
this.logWarn(
'Unknown colId specified in groupBy - grid will not be grouped.',
invalidColIds
);
colIds = [];
}
this.groupBy = colIds;
}
/** Expand all parent rows in grouped or tree grid. (Note, this is recursive for trees!) */
expandAll() {
const {agApi} = this;
if (agApi) {
agApi.expandAll();
this.noteAgExpandStateChange();
}
}
/** Collapse all parent rows in grouped or tree grid. */
collapseAll() {
const {agApi} = this;
if (agApi) {
agApi.collapseAll();