@slickgrid-universal/vanilla-bundle 4.0.2 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1483 @@
1
+ import { dequal } from 'dequal/lite';
2
+ import 'flatpickr/dist/l10n/fr';
3
+ import type {
4
+ BackendServiceApi,
5
+ BackendServiceOption,
6
+ Column,
7
+ ColumnEditor,
8
+ DataViewOption,
9
+ ExtensionList,
10
+ ExternalResource,
11
+ GridOption,
12
+ Metrics,
13
+ Pagination,
14
+ SelectEditor,
15
+ ServicePagination,
16
+ Subscription,
17
+ RxJsFacade,
18
+ } from '@slickgrid-universal/common';
19
+
20
+ import {
21
+ autoAddEditorFormatterToColumnsWithEditor,
22
+ AutocompleterEditor,
23
+ GlobalGridOptions,
24
+ GridStateType,
25
+ SlickGroupItemMetadataProvider,
26
+
27
+ // services
28
+ BackendUtilityService,
29
+ CollectionService,
30
+ ExtensionService,
31
+ ExtensionUtility,
32
+ FilterFactory,
33
+ FilterService,
34
+ GridEventService,
35
+ GridService,
36
+ GridStateService,
37
+ GroupingAndColspanService,
38
+ Observable,
39
+ PaginationService,
40
+ ResizerService,
41
+ SharedService,
42
+ SortService,
43
+ SlickgridConfig,
44
+ TranslaterService,
45
+ TreeDataService,
46
+
47
+ // utilities
48
+ deepCopy,
49
+ emptyElement,
50
+ unsubscribeAll,
51
+ SlickEventHandler,
52
+ SlickDataView,
53
+ SlickGrid
54
+ } from '@slickgrid-universal/common';
55
+ import { EventNamingStyle, EventPubSubService } from '@slickgrid-universal/event-pub-sub';
56
+ import { SlickEmptyWarningComponent } from '@slickgrid-universal/empty-warning-component';
57
+ import { SlickFooterComponent } from '@slickgrid-universal/custom-footer-component';
58
+ import { SlickPaginationComponent } from '@slickgrid-universal/pagination-component';
59
+ import { extend } from '@slickgrid-universal/utils';
60
+
61
+ import { SlickerGridInstance } from '../interfaces/slickerGridInstance.interface';
62
+ import { UniversalContainerService } from '../services/universalContainer.service';
63
+
64
+ export class SlickVanillaGridBundle<TData = any> {
65
+ protected _currentDatasetLength = 0;
66
+ protected _eventPubSubService!: EventPubSubService;
67
+ protected _columnDefinitions?: Column<TData>[];
68
+ protected _gridOptions?: GridOption;
69
+ protected _gridContainerElm!: HTMLElement;
70
+ protected _gridParentContainerElm!: HTMLElement;
71
+ protected _hideHeaderRowAfterPageLoad = false;
72
+ protected _isDatasetInitialized = false;
73
+ protected _isDatasetHierarchicalInitialized = false;
74
+ protected _isGridInitialized = false;
75
+ protected _isLocalGrid = true;
76
+ protected _isPaginationInitialized = false;
77
+ protected _eventHandler!: SlickEventHandler;
78
+ protected _extensions: ExtensionList<any> | undefined;
79
+ protected _paginationOptions: Pagination | undefined;
80
+ protected _registeredResources: ExternalResource[] = [];
81
+ protected _slickgridInitialized = false;
82
+ protected _slickerGridInstances: SlickerGridInstance | undefined;
83
+ backendServiceApi: BackendServiceApi | undefined;
84
+ dataView?: SlickDataView<TData>;
85
+ slickGrid?: SlickGrid;
86
+ metrics?: Metrics;
87
+ customDataView = false;
88
+ paginationData?: {
89
+ gridOptions: GridOption;
90
+ paginationService: PaginationService;
91
+ };
92
+ totalItems = 0;
93
+ groupItemMetadataProvider?: SlickGroupItemMetadataProvider;
94
+ resizerService!: ResizerService;
95
+ subscriptions: Subscription[] = [];
96
+ showPagination = false;
97
+
98
+ // extensions
99
+ extensionUtility!: ExtensionUtility;
100
+
101
+ // services
102
+ backendUtilityService!: BackendUtilityService;
103
+ collectionService!: CollectionService;
104
+ extensionService!: ExtensionService;
105
+ filterFactory!: FilterFactory;
106
+ filterService!: FilterService;
107
+ gridClass!: string;
108
+ gridClassName!: string;
109
+ gridEventService!: GridEventService;
110
+ gridService!: GridService;
111
+ gridStateService!: GridStateService;
112
+ groupingService!: GroupingAndColspanService;
113
+ paginationService!: PaginationService;
114
+ rxjs?: RxJsFacade;
115
+ sharedService!: SharedService;
116
+ sortService!: SortService;
117
+ translaterService: TranslaterService | undefined;
118
+ treeDataService!: TreeDataService;
119
+ universalContainerService!: UniversalContainerService;
120
+
121
+ // components
122
+ slickEmptyWarning: SlickEmptyWarningComponent | undefined;
123
+ slickFooter: SlickFooterComponent | undefined;
124
+ slickPagination: SlickPaginationComponent | undefined;
125
+
126
+ get eventHandler(): SlickEventHandler {
127
+ return this._eventHandler;
128
+ }
129
+
130
+ get columnDefinitions(): Column<TData>[] {
131
+ return this._columnDefinitions || [];
132
+ }
133
+ set columnDefinitions(columnDefinitions: Column<TData>[]) {
134
+ this._columnDefinitions = columnDefinitions;
135
+ if (this._slickgridInitialized) {
136
+ this.updateColumnDefinitionsList(this._columnDefinitions);
137
+ }
138
+ if (columnDefinitions.length > 0) {
139
+ this.copyColumnWidthsReference(columnDefinitions);
140
+ }
141
+ }
142
+
143
+ get dataset(): any[] {
144
+ return this.dataView?.getItems() || [];
145
+ }
146
+ set dataset(newDataset: any[]) {
147
+ const prevDatasetLn = this._currentDatasetLength;
148
+ const isDatasetEqual = dequal(newDataset, this.dataset || []);
149
+ const isDeepCopyDataOnPageLoadEnabled = !!(this._gridOptions?.enableDeepCopyDatasetOnPageLoad);
150
+ let data = isDeepCopyDataOnPageLoadEnabled ? deepCopy(newDataset || []) : newDataset;
151
+
152
+ // when Tree Data is enabled and we don't yet have the hierarchical dataset filled, we can force a convert+sort of the array
153
+ if (this.slickGrid && this.gridOptions?.enableTreeData && Array.isArray(newDataset) && (newDataset.length > 0 || newDataset.length !== prevDatasetLn || !isDatasetEqual)) {
154
+ this._isDatasetHierarchicalInitialized = false;
155
+ data = this.sortTreeDataset(newDataset, !isDatasetEqual); // if dataset changed, then force a refresh anyway
156
+ }
157
+
158
+ this.refreshGridData(data || []);
159
+ this._currentDatasetLength = (newDataset || []).length;
160
+
161
+ // expand/autofit columns on first page load
162
+ // we can assume that if the prevDataset was empty then we are on first load
163
+ if (this.slickGrid && this.gridOptions.autoFitColumnsOnFirstLoad && prevDatasetLn === 0) {
164
+ this.slickGrid.autosizeColumns();
165
+ }
166
+ }
167
+
168
+ get datasetHierarchical(): any[] | undefined {
169
+ return this.sharedService.hierarchicalDataset;
170
+ }
171
+
172
+ set datasetHierarchical(newHierarchicalDataset: any[] | undefined) {
173
+ const isDatasetEqual = dequal(newHierarchicalDataset, this.sharedService.hierarchicalDataset || []);
174
+ const prevFlatDatasetLn = this._currentDatasetLength;
175
+ this.sharedService.hierarchicalDataset = newHierarchicalDataset;
176
+
177
+ if (newHierarchicalDataset && this.columnDefinitions && this.filterService?.clearFilters) {
178
+ this.filterService.clearFilters();
179
+ }
180
+
181
+ // when a hierarchical dataset is set afterward, we can reset the flat dataset and call a tree data sort that will overwrite the flat dataset
182
+ if (this.dataView && newHierarchicalDataset && this.slickGrid && this.sortService?.processTreeDataInitialSort) {
183
+ this.sortService.processTreeDataInitialSort();
184
+
185
+ // we also need to reset/refresh the Tree Data filters because if we inserted new item(s) then it might not show up without doing this refresh
186
+ // however we need 1 cpu cycle before having the DataView refreshed, so we need to wrap this check in a setTimeout
187
+ setTimeout(() => {
188
+ const flatDatasetLn = this.dataView?.getItemCount() ?? 0;
189
+ if (flatDatasetLn > 0 && (flatDatasetLn !== prevFlatDatasetLn || !isDatasetEqual)) {
190
+ this.filterService.refreshTreeDataFilters();
191
+ }
192
+ });
193
+ }
194
+
195
+ this._isDatasetHierarchicalInitialized = true;
196
+ }
197
+
198
+ set eventPubSubService(pubSub: EventPubSubService) {
199
+ this._eventPubSubService = pubSub;
200
+ }
201
+
202
+ get gridOptions(): GridOption {
203
+ return this._gridOptions || {} as GridOption;
204
+ }
205
+
206
+ set gridOptions(options: GridOption) {
207
+ let mergedOptions: GridOption;
208
+
209
+ // if we already have grid options, when grid was already initialized, we'll merge with those options
210
+ // else we'll merge with global grid options
211
+ if (this.slickGrid?.getOptions) {
212
+ mergedOptions = (extend<GridOption>(true, {} as GridOption, this.slickGrid.getOptions() as GridOption, options)) as GridOption;
213
+ } else {
214
+ mergedOptions = this.mergeGridOptions(options);
215
+ }
216
+ if (this.sharedService?.gridOptions && this.slickGrid?.setOptions) {
217
+ this.sharedService.gridOptions = mergedOptions;
218
+ this.slickGrid.setOptions(mergedOptions as any, false, true); // make sure to supressColumnCheck (3rd arg) to avoid problem with changeColumnsArrangement() and custom grid view
219
+ this.slickGrid.reRenderColumns(true); // then call a re-render since we did supressColumnCheck on previous setOptions
220
+ }
221
+ this._gridOptions = mergedOptions;
222
+ }
223
+
224
+ get paginationOptions(): Pagination | undefined {
225
+ return this._paginationOptions;
226
+ }
227
+ set paginationOptions(newPaginationOptions: Pagination | undefined) {
228
+ if (newPaginationOptions && this._paginationOptions) {
229
+ this._paginationOptions = { ...this._paginationOptions, ...newPaginationOptions };
230
+ } else {
231
+ this._paginationOptions = newPaginationOptions;
232
+ }
233
+ this.gridOptions.pagination = this._paginationOptions;
234
+ this.paginationService.updateTotalItems(newPaginationOptions?.totalItems ?? 0, true);
235
+ }
236
+
237
+ get isDatasetInitialized(): boolean {
238
+ return this._isDatasetInitialized;
239
+ }
240
+ set isDatasetInitialized(isInitialized: boolean) {
241
+ this._isDatasetInitialized = isInitialized;
242
+ }
243
+ get isGridInitialized(): boolean {
244
+ return this._isGridInitialized;
245
+ }
246
+
247
+ get instances(): SlickerGridInstance | undefined {
248
+ return this._slickerGridInstances;
249
+ }
250
+
251
+ get extensions(): ExtensionList<any> | undefined {
252
+ return this._extensions;
253
+ }
254
+
255
+ get registeredResources(): any[] {
256
+ return this._registeredResources;
257
+ }
258
+
259
+ /**
260
+ * Slicker Grid Bundle constructor
261
+ * @param {Object} gridParentContainerElm - div HTML DOM element container
262
+ * @param {Array<Column>} columnDefs - Column Definitions
263
+ * @param {Object} options - Grid Options
264
+ * @param {Array<Object>} dataset - Dataset
265
+ * @param {Array<Object>} hierarchicalDataset - Hierarchical Dataset
266
+ * @param {Object} services - Typically only used for Unit Testing when we want to pass Mocked/Stub Services
267
+ */
268
+ constructor(
269
+ gridParentContainerElm: HTMLElement,
270
+ columnDefs?: Column<TData>[],
271
+ options?: Partial<GridOption>,
272
+ dataset?: any[],
273
+ hierarchicalDataset?: any[],
274
+ services?: {
275
+ backendUtilityService?: BackendUtilityService,
276
+ collectionService?: CollectionService,
277
+ eventPubSubService?: EventPubSubService,
278
+ extensionService?: ExtensionService,
279
+ extensionUtility?: ExtensionUtility,
280
+ filterService?: FilterService,
281
+ gridEventService?: GridEventService,
282
+ gridService?: GridService,
283
+ gridStateService?: GridStateService,
284
+ groupingAndColspanService?: GroupingAndColspanService,
285
+ paginationService?: PaginationService,
286
+ resizerService?: ResizerService,
287
+ rxjs?: RxJsFacade,
288
+ sharedService?: SharedService,
289
+ sortService?: SortService,
290
+ treeDataService?: TreeDataService,
291
+ translaterService?: TranslaterService,
292
+ universalContainerService?: UniversalContainerService,
293
+ }
294
+ ) {
295
+ // make sure that the grid container doesn't already have the "slickgrid-container" css class
296
+ // if it does then we won't create yet another grid, just stop there
297
+ if (gridParentContainerElm.querySelectorAll('.slickgrid-container').length !== 0) {
298
+ return;
299
+ }
300
+
301
+ gridParentContainerElm.classList.add('grid-pane');
302
+ this._gridParentContainerElm = gridParentContainerElm as HTMLDivElement;
303
+ this._gridContainerElm = document.createElement('div') as HTMLDivElement;
304
+ this._gridContainerElm.classList.add('slickgrid-container');
305
+ gridParentContainerElm.appendChild(this._gridContainerElm);
306
+
307
+ // check if the user wants to hide the header row from the start
308
+ // we only want to do this check once in the constructor
309
+ this._hideHeaderRowAfterPageLoad = (options?.showHeaderRow === false);
310
+
311
+ this._columnDefinitions = columnDefs || [];
312
+ if (this._columnDefinitions.length > 0) {
313
+ this.copyColumnWidthsReference(this._columnDefinitions);
314
+ }
315
+
316
+ // save resource refs to register before the grid options are merged and possibly deep copied
317
+ // since a deep copy of grid options would lose original resource refs but we want to keep them as singleton
318
+ this._registeredResources = options?.externalResources || [];
319
+
320
+ this._gridOptions = this.mergeGridOptions(options || {});
321
+ const isDeepCopyDataOnPageLoadEnabled = !!(this._gridOptions?.enableDeepCopyDatasetOnPageLoad);
322
+
323
+ this.universalContainerService = services?.universalContainerService ?? new UniversalContainerService();
324
+
325
+ // if user is providing a Translate Service, it has to be passed under the "translater" grid option
326
+ this.translaterService = services?.translaterService ?? this._gridOptions?.translater;
327
+
328
+ // initialize and assign all Service Dependencies
329
+ this._eventPubSubService = services?.eventPubSubService ?? new EventPubSubService(gridParentContainerElm);
330
+ this._eventPubSubService.eventNamingStyle = this._gridOptions?.eventNamingStyle ?? EventNamingStyle.camelCase;
331
+
332
+ const slickgridConfig = new SlickgridConfig();
333
+ this.backendUtilityService = services?.backendUtilityService ?? new BackendUtilityService();
334
+ this.gridEventService = services?.gridEventService ?? new GridEventService();
335
+ this.sharedService = services?.sharedService ?? new SharedService();
336
+ this.collectionService = services?.collectionService ?? new CollectionService(this.translaterService);
337
+ this.extensionUtility = services?.extensionUtility ?? new ExtensionUtility(this.sharedService, this.backendUtilityService, this.translaterService);
338
+ this.filterFactory = new FilterFactory(slickgridConfig, this.translaterService, this.collectionService);
339
+ this.filterService = services?.filterService ?? new FilterService(this.filterFactory, this._eventPubSubService, this.sharedService, this.backendUtilityService);
340
+ this.resizerService = services?.resizerService ?? new ResizerService(this._eventPubSubService);
341
+ this.sortService = services?.sortService ?? new SortService(this.sharedService, this._eventPubSubService, this.backendUtilityService);
342
+ this.treeDataService = services?.treeDataService ?? new TreeDataService(this._eventPubSubService, this.sharedService, this.sortService);
343
+ this.paginationService = services?.paginationService ?? new PaginationService(this._eventPubSubService, this.sharedService, this.backendUtilityService);
344
+
345
+ this.extensionService = services?.extensionService ?? new ExtensionService(
346
+ this.extensionUtility,
347
+ this.filterService,
348
+ this._eventPubSubService,
349
+ this.sharedService,
350
+ this.sortService,
351
+ this.treeDataService,
352
+ this.translaterService,
353
+ );
354
+
355
+ this.gridStateService = services?.gridStateService ?? new GridStateService(this.extensionService, this.filterService, this._eventPubSubService, this.sharedService, this.sortService, this.treeDataService);
356
+ this.gridService = services?.gridService ?? new GridService(this.gridStateService, this.filterService, this._eventPubSubService, this.paginationService, this.sharedService, this.sortService, this.treeDataService);
357
+ this.groupingService = services?.groupingAndColspanService ?? new GroupingAndColspanService(this.extensionUtility, this._eventPubSubService);
358
+
359
+ if (hierarchicalDataset) {
360
+ this.sharedService.hierarchicalDataset = (isDeepCopyDataOnPageLoadEnabled ? deepCopy(hierarchicalDataset || []) : hierarchicalDataset) || [];
361
+ }
362
+ const eventHandler = new SlickEventHandler();
363
+
364
+ // register all service instances in the container
365
+ this.universalContainerService.registerInstance('PubSubService', this._eventPubSubService); // external resources require this one registration (ExcelExport, TextExport)
366
+ this.universalContainerService.registerInstance('EventPubSubService', this._eventPubSubService);
367
+ this.universalContainerService.registerInstance('ExtensionUtility', this.extensionUtility);
368
+ this.universalContainerService.registerInstance('FilterService', this.filterService);
369
+ this.universalContainerService.registerInstance('CollectionService', this.collectionService);
370
+ this.universalContainerService.registerInstance('ExtensionService', this.extensionService);
371
+ this.universalContainerService.registerInstance('GridEventService', this.gridEventService);
372
+ this.universalContainerService.registerInstance('GridService', this.gridService);
373
+ this.universalContainerService.registerInstance('GridStateService', this.gridStateService);
374
+ this.universalContainerService.registerInstance('GroupingAndColspanService', this.groupingService);
375
+ this.universalContainerService.registerInstance('PaginationService', this.paginationService);
376
+ this.universalContainerService.registerInstance('ResizerService', this.resizerService);
377
+ this.universalContainerService.registerInstance('SharedService', this.sharedService);
378
+ this.universalContainerService.registerInstance('SortService', this.sortService);
379
+ this.universalContainerService.registerInstance('TranslaterService', this.translaterService);
380
+ this.universalContainerService.registerInstance('TreeDataService', this.treeDataService);
381
+
382
+ this.initialization(this._gridContainerElm, eventHandler);
383
+ if (!hierarchicalDataset && !this.gridOptions.backendServiceApi) {
384
+ this.dataset = dataset || [];
385
+ this._currentDatasetLength = this.dataset.length;
386
+ }
387
+ }
388
+
389
+ emptyGridContainerElm() {
390
+ const gridContainerId = this.gridOptions?.gridContainerId ?? 'grid1';
391
+ const gridContainerElm = document.querySelector(`#${gridContainerId}`);
392
+ emptyElement(gridContainerElm);
393
+ }
394
+
395
+ /** Dispose of the Component */
396
+ dispose(shouldEmptyDomElementContainer = false) {
397
+ this._eventPubSubService?.publish('onBeforeGridDestroy', this.slickGrid);
398
+ this._eventHandler?.unsubscribeAll();
399
+ this._eventPubSubService?.publish('onAfterGridDestroyed', true);
400
+
401
+ // dispose the Services
402
+ this.extensionService?.dispose();
403
+ this.filterService?.dispose();
404
+ this.gridEventService?.dispose();
405
+ this.gridService?.dispose();
406
+ this.gridStateService?.dispose();
407
+ this.groupingService?.dispose();
408
+ this.paginationService?.dispose();
409
+ this.resizerService?.dispose();
410
+ this.sortService?.dispose();
411
+ this.treeDataService?.dispose();
412
+ this.universalContainerService?.dispose();
413
+
414
+ // dispose all registered external resources
415
+ this.disposeExternalResources();
416
+
417
+ // dispose the Components
418
+ this.slickFooter?.dispose();
419
+ this.slickEmptyWarning?.dispose();
420
+ this.slickPagination?.dispose();
421
+
422
+ unsubscribeAll(this.subscriptions);
423
+ this._eventPubSubService?.unsubscribeAll();
424
+ this.dataView?.setItems([]);
425
+ if (typeof this.dataView?.destroy === 'function') {
426
+ this.dataView?.destroy();
427
+ }
428
+ this.slickGrid?.destroy(true);
429
+ this.slickGrid = null as any;
430
+
431
+ emptyElement(this._gridContainerElm);
432
+ emptyElement(this._gridParentContainerElm);
433
+ this._gridContainerElm?.remove();
434
+ this._gridParentContainerElm?.remove();
435
+
436
+ if (this.backendServiceApi) {
437
+ for (const prop of Object.keys(this.backendServiceApi)) {
438
+ this.backendServiceApi[prop as keyof BackendServiceApi] = null;
439
+ }
440
+ this.backendServiceApi = undefined;
441
+ }
442
+ for (const prop of Object.keys(this.columnDefinitions)) {
443
+ (this.columnDefinitions as any)[prop] = null;
444
+ }
445
+ for (const prop of Object.keys(this.sharedService)) {
446
+ (this.sharedService as any)[prop] = null;
447
+ }
448
+ this.datasetHierarchical = undefined;
449
+ this._columnDefinitions = [];
450
+
451
+ // we could optionally also empty the content of the grid container DOM element
452
+ if (shouldEmptyDomElementContainer) {
453
+ this.emptyGridContainerElm();
454
+ }
455
+ this._eventPubSubService?.dispose();
456
+ this._slickerGridInstances = null as any;
457
+ }
458
+
459
+ disposeExternalResources() {
460
+ if (Array.isArray(this._registeredResources)) {
461
+ while (this._registeredResources.length > 0) {
462
+ const res = this._registeredResources.pop();
463
+ if (res?.dispose) {
464
+ res.dispose();
465
+ }
466
+ }
467
+ }
468
+ this._registeredResources = [];
469
+ }
470
+
471
+ initialization(gridContainerElm: HTMLElement, eventHandler: SlickEventHandler) {
472
+ // when detecting a frozen grid, we'll automatically enable the mousewheel scroll handler so that we can scroll from both left/right frozen containers
473
+ if (this.gridOptions && ((this.gridOptions.frozenRow !== undefined && this.gridOptions.frozenRow >= 0) || this.gridOptions.frozenColumn !== undefined && this.gridOptions.frozenColumn >= 0) && this.gridOptions.enableMouseWheelScrollHandler === undefined) {
474
+ this.gridOptions.enableMouseWheelScrollHandler = true;
475
+ }
476
+
477
+ // create the slickgrid container and add it to the user's grid container
478
+ this._gridContainerElm = gridContainerElm;
479
+ this._eventPubSubService.publish('onBeforeGridCreate', true);
480
+
481
+ this._eventHandler = eventHandler;
482
+ this._gridOptions = this.mergeGridOptions(this._gridOptions || {} as GridOption);
483
+ this.backendServiceApi = this._gridOptions?.backendServiceApi;
484
+ this._isLocalGrid = !this.backendServiceApi; // considered a local grid if it doesn't have a backend service set
485
+ this._eventPubSubService.eventNamingStyle = this._gridOptions?.eventNamingStyle ?? EventNamingStyle.camelCase;
486
+ this._paginationOptions = this.gridOptions?.pagination;
487
+
488
+ this.createBackendApiInternalPostProcessCallback(this._gridOptions);
489
+
490
+ if (!this.customDataView) {
491
+ const dataviewInlineFilters = this._gridOptions?.dataView?.inlineFilters ?? false;
492
+ let dataViewOptions: Partial<DataViewOption> = { ...this._gridOptions.dataView, inlineFilters: dataviewInlineFilters };
493
+
494
+ if (this.gridOptions.draggableGrouping || this.gridOptions.enableGrouping) {
495
+ this.groupItemMetadataProvider = new SlickGroupItemMetadataProvider();
496
+ this.sharedService.groupItemMetadataProvider = this.groupItemMetadataProvider;
497
+ dataViewOptions = { ...dataViewOptions, groupItemMetadataProvider: this.groupItemMetadataProvider };
498
+ }
499
+ this.dataView = new SlickDataView<TData>(dataViewOptions as Partial<DataViewOption>, this._eventPubSubService);
500
+ this._eventPubSubService.publish('onDataviewCreated', this.dataView);
501
+ }
502
+
503
+ // get any possible Services that user want to register which don't require SlickGrid to be instantiated
504
+ // RxJS Resource is in this lot because it has to be registered before anything else and doesn't require SlickGrid to be initialized
505
+ this.preRegisterResources();
506
+
507
+ // for convenience to the user, we provide the property "editor" as an Slickgrid-Universal editor complex object
508
+ // however "editor" is used internally by SlickGrid for it's own Editor Factory
509
+ // so in our lib we will swap "editor" and copy it into a new property called "internalColumnEditor"
510
+ // then take back "editor.model" and make it the new "editor" so that SlickGrid Editor Factory still works
511
+ this._columnDefinitions = this.swapInternalEditorToSlickGridFactoryEditor(this._columnDefinitions || []);
512
+
513
+ // if the user wants to automatically add a Custom Editor Formatter, we need to call the auto add function again
514
+ if (this._gridOptions?.autoAddCustomEditorFormatter) {
515
+ autoAddEditorFormatterToColumnsWithEditor(this._columnDefinitions, this._gridOptions.autoAddCustomEditorFormatter);
516
+ }
517
+
518
+ // save reference for all columns before they optionally become hidden/visible
519
+ this.sharedService.allColumns = this._columnDefinitions;
520
+ this.sharedService.visibleColumns = this._columnDefinitions;
521
+
522
+ // TODO: revisit later, this is conflicting with Grid State & Presets
523
+ // before certain extentions/plugins potentially adds extra columns not created by the user itself (RowMove, RowDetail, RowSelections)
524
+ // we'll subscribe to the event and push back the change to the user so they always use full column defs array including extra cols
525
+ // this.subscriptions.push(
526
+ // this._eventPubSubService.subscribe<{ columns: Column[]; pluginName: string }>('onPluginColumnsChanged', data => {
527
+ // this._columnDefinitions = this.columnDefinitions = data.columns;
528
+ // })
529
+ // );
530
+
531
+ // after subscribing to potential columns changed, we are ready to create these optional extensions
532
+ // when we did find some to create (RowMove, RowDetail, RowSelections), it will automatically modify column definitions (by previous subscribe)
533
+ this.extensionService.createExtensionsBeforeGridCreation(this._columnDefinitions, this._gridOptions);
534
+
535
+ // if user entered some Pinning/Frozen "presets", we need to apply them in the grid options
536
+ if (this.gridOptions.presets?.pinning) {
537
+ this.gridOptions = { ...this.gridOptions, ...this.gridOptions.presets.pinning };
538
+ }
539
+
540
+ this.slickGrid = new SlickGrid<TData, Column<TData>, GridOption<Column<TData>>>(gridContainerElm, this.dataView as SlickDataView<TData>, this._columnDefinitions, this._gridOptions, this._eventPubSubService);
541
+ this.sharedService.dataView = this.dataView as SlickDataView;
542
+ this.sharedService.slickGrid = this.slickGrid as SlickGrid;
543
+ this.sharedService.gridContainerElement = this._gridContainerElm;
544
+ if (this.groupItemMetadataProvider) {
545
+ this.slickGrid.registerPlugin(this.groupItemMetadataProvider); // register GroupItemMetadataProvider when Grouping is enabled
546
+ }
547
+
548
+ this.extensionService.bindDifferentExtensions();
549
+ this.bindDifferentHooks(this.slickGrid, this._gridOptions, this.dataView as SlickDataView);
550
+ this._slickgridInitialized = true;
551
+
552
+ // when it's a frozen grid, we need to keep the frozen column id for reference if we ever show/hide column from ColumnPicker/GridMenu afterward
553
+ const frozenColumnIndex = this._gridOptions?.frozenColumn ?? -1;
554
+ if (frozenColumnIndex >= 0 && frozenColumnIndex <= this._columnDefinitions.length && this._columnDefinitions.length > 0) {
555
+ this.sharedService.frozenVisibleColumnId = this._columnDefinitions[frozenColumnIndex]?.id ?? '';
556
+ }
557
+
558
+ // get any possible Services that user want to register
559
+ this.registerResources();
560
+
561
+ // initialize the SlickGrid grid
562
+ this.slickGrid.init();
563
+
564
+ // initialized the resizer service only after SlickGrid is initialized
565
+ // if we don't we end up binding our resize to a grid element that doesn't yet exist in the DOM and the resizer service will fail silently (because it has a try/catch that unbinds the resize without throwing back)
566
+ this.resizerService.init(this.slickGrid, this._gridParentContainerElm);
567
+
568
+ // user could show a custom footer with the data metrics (dataset length and last updated timestamp)
569
+ if (!this.gridOptions.enablePagination && this.gridOptions.showCustomFooter && this.gridOptions.customFooterOptions) {
570
+ this.slickFooter = new SlickFooterComponent(this.slickGrid, this.gridOptions.customFooterOptions, this._eventPubSubService, this.translaterService);
571
+ this.slickFooter.renderFooter(this._gridParentContainerElm);
572
+ }
573
+
574
+ // load the data in the DataView (unless it's a hierarchical dataset, if so it will be loaded after the initial tree sort)
575
+ if (Array.isArray(this.dataset)) {
576
+ const initialDataset = this.gridOptions?.enableTreeData ? this.sortTreeDataset(this.dataset) : this.dataset;
577
+ this.dataView?.setItems(initialDataset, this._gridOptions.datasetIdPropertyName);
578
+ }
579
+
580
+ // if you don't want the items that are not visible (due to being filtered out or being on a different page)
581
+ // to stay selected, pass 'false' to the second arg
582
+ const selectionModel = this.slickGrid?.getSelectionModel();
583
+ if (selectionModel && this._gridOptions?.dataView && this._gridOptions.dataView.hasOwnProperty('syncGridSelection')) {
584
+ // if we are using a Backend Service, we will do an extra flag check, the reason is because it might have some unintended behaviors
585
+ // with the BackendServiceApi because technically the data in the page changes the DataView on every page change.
586
+ let preservedRowSelectionWithBackend = false;
587
+ if (this._gridOptions.backendServiceApi && this._gridOptions.dataView.hasOwnProperty('syncGridSelectionWithBackendService')) {
588
+ preservedRowSelectionWithBackend = this._gridOptions.dataView.syncGridSelectionWithBackendService as boolean;
589
+ }
590
+
591
+ const syncGridSelection = this._gridOptions.dataView.syncGridSelection;
592
+ if (typeof syncGridSelection === 'boolean') {
593
+ let preservedRowSelection = syncGridSelection;
594
+ if (!this._isLocalGrid) {
595
+ // when using BackendServiceApi, we'll be using the "syncGridSelectionWithBackendService" flag BUT "syncGridSelection" must also be set to True
596
+ preservedRowSelection = syncGridSelection && preservedRowSelectionWithBackend;
597
+ }
598
+ this.dataView?.syncGridSelection(this.slickGrid, preservedRowSelection);
599
+ } else if (typeof syncGridSelection === 'object') {
600
+ this.dataView?.syncGridSelection(this.slickGrid, syncGridSelection.preserveHidden, syncGridSelection.preserveHiddenOnSelectionChange);
601
+ }
602
+ }
603
+
604
+ this.slickGrid.invalidate();
605
+
606
+ if ((this.dataView?.getLength() ?? 0) > 0) {
607
+ if (!this._isDatasetInitialized && (this._gridOptions.enableCheckboxSelector || this._gridOptions.enableRowSelection)) {
608
+ this.loadRowSelectionPresetWhenExists();
609
+ }
610
+ this.loadFilterPresetsWhenDatasetInitialized();
611
+ this._isDatasetInitialized = true;
612
+ }
613
+
614
+ // user might want to hide the header row on page load but still have `enableFiltering: true`
615
+ // if that is the case, we need to hide the headerRow ONLY AFTER all filters got created & dataView exist
616
+ if (this._hideHeaderRowAfterPageLoad) {
617
+ this.showHeaderRow(false);
618
+ this.sharedService.hideHeaderRowAfterPageLoad = this._hideHeaderRowAfterPageLoad;
619
+ }
620
+
621
+ // on cell click, mainly used with the columnDef.action callback
622
+ this.gridEventService.bindOnBeforeEditCell(this.slickGrid);
623
+ this.gridEventService.bindOnCellChange(this.slickGrid);
624
+ this.gridEventService.bindOnClick(this.slickGrid);
625
+
626
+ // bind the Backend Service API callback functions only after the grid is initialized
627
+ // because the preProcess() and onInit() might get triggered
628
+ if (this.gridOptions?.backendServiceApi) {
629
+ this.bindBackendCallbackFunctions(this.gridOptions);
630
+ }
631
+
632
+ // publish & dispatch certain events
633
+ this._eventPubSubService.publish('onGridCreated', this.slickGrid);
634
+
635
+ // after the DataView is created & updated execute some processes & dispatch some events
636
+ if (!this.customDataView) {
637
+ this.executeAfterDataviewCreated(this.gridOptions);
638
+ }
639
+
640
+ // bind resize ONLY after the dataView is ready
641
+ this.bindResizeHook(this.slickGrid, this.gridOptions);
642
+
643
+ // once the grid is created, we'll return its instance (we do this to return Transient Services from DI)
644
+ this._slickerGridInstances = {
645
+ // Slick Grid & DataView objects
646
+ dataView: this.dataView as SlickDataView,
647
+ slickGrid: this.slickGrid,
648
+
649
+ // public methods
650
+ dispose: this.dispose.bind(this),
651
+
652
+ // return all available Services (non-singleton)
653
+ backendService: this.gridOptions?.backendServiceApi?.service,
654
+ eventPubSubService: this._eventPubSubService,
655
+ filterService: this.filterService,
656
+ gridEventService: this.gridEventService,
657
+ gridStateService: this.gridStateService,
658
+ gridService: this.gridService,
659
+ groupingService: this.groupingService,
660
+ extensionService: this.extensionService,
661
+ extensionUtility: this.extensionUtility,
662
+ paginationService: this.paginationService,
663
+ resizerService: this.resizerService,
664
+ sortService: this.sortService,
665
+ treeDataService: this.treeDataService,
666
+ };
667
+
668
+ // addons (SlickGrid extra plugins/controls)
669
+ this._extensions = this.extensionService?.extensionList;
670
+
671
+ // all instances (SlickGrid, DataView & all Services)
672
+ this._eventPubSubService.publish('onSlickerGridCreated', this.instances);
673
+ this._isGridInitialized = true;
674
+ }
675
+
676
+ mergeGridOptions(gridOptions: GridOption) {
677
+ const options = extend<GridOption>(true, {}, GlobalGridOptions, gridOptions);
678
+
679
+ // also make sure to show the header row if user have enabled filtering
680
+ if (options.enableFiltering && !options.showHeaderRow) {
681
+ options.showHeaderRow = options.enableFiltering;
682
+ }
683
+
684
+ // using copy extend to do a deep clone has an unwanted side on objects and pageSizes but ES6 spread has other worst side effects
685
+ // so we will just overwrite the pageSizes when needed, this is the only one causing issues so far.
686
+ // On a deep extend, Object and Array are extended, but object wrappers on primitive types such as String, Boolean, and Number are not.
687
+ if (options?.pagination && (gridOptions.enablePagination || gridOptions.backendServiceApi) && gridOptions.pagination && Array.isArray(gridOptions.pagination.pageSizes)) {
688
+ options.pagination.pageSizes = gridOptions.pagination.pageSizes;
689
+ }
690
+
691
+ // when we use Pagination on Local Grid, it doesn't seem to work without enableFiltering
692
+ // so we'll enable the filtering but we'll keep the header row hidden
693
+ if (this.sharedService && !options.enableFiltering && options.enablePagination && this._isLocalGrid) {
694
+ options.enableFiltering = true;
695
+ options.showHeaderRow = false;
696
+ this._hideHeaderRowAfterPageLoad = true;
697
+ this.sharedService.hideHeaderRowAfterPageLoad = true;
698
+ }
699
+
700
+ return options;
701
+ }
702
+
703
+ /**
704
+ * Define our internal Post Process callback, it will execute internally after we get back result from the Process backend call
705
+ * For now, this is GraphQL Service ONLY feature and it will basically
706
+ * refresh the Dataset & Pagination without having the user to create his own PostProcess every time
707
+ */
708
+ createBackendApiInternalPostProcessCallback(gridOptions?: GridOption) {
709
+ const backendApi = gridOptions?.backendServiceApi;
710
+ if (backendApi?.service) {
711
+ const backendApiService = backendApi.service;
712
+
713
+ // internalPostProcess only works (for now) with a GraphQL Service, so make sure it is of that type
714
+ if (/* backendApiService instanceof GraphqlService || */ typeof backendApiService.getDatasetName === 'function') {
715
+ backendApi.internalPostProcess = (processResult: any) => {
716
+ const datasetName = (backendApi && backendApiService && typeof backendApiService.getDatasetName === 'function') ? backendApiService.getDatasetName() : '';
717
+ if (processResult && processResult.data && processResult.data[datasetName]) {
718
+ const data = processResult.data[datasetName].hasOwnProperty('nodes') ? (processResult as any).data[datasetName].nodes : (processResult as any).data[datasetName];
719
+ const totalCount = processResult.data[datasetName].hasOwnProperty('totalCount') ? (processResult as any).data[datasetName].totalCount : (processResult as any).data[datasetName].length;
720
+ this.refreshGridData(data, totalCount || 0);
721
+ }
722
+ };
723
+ }
724
+ }
725
+ }
726
+
727
+ bindDifferentHooks(grid: SlickGrid, gridOptions: GridOption, dataView: SlickDataView<TData>) {
728
+ // if user is providing a Translate Service, we need to add our PubSub Service (but only after creating all dependencies)
729
+ // so that we can later subscribe to the "onLanguageChange" event and translate any texts whenever that get triggered
730
+ if (gridOptions.enableTranslate && this.translaterService?.addPubSubMessaging) {
731
+ this.translaterService.addPubSubMessaging(this._eventPubSubService);
732
+ }
733
+
734
+ // translate them all on first load, then on each language change
735
+ if (gridOptions.enableTranslate) {
736
+ this.extensionService.translateAllExtensions();
737
+ this.translateColumnHeaderTitleKeys();
738
+ this.translateColumnGroupKeys();
739
+ }
740
+
741
+ // on locale change, we have to manually translate the Headers, GridMenu
742
+ this.subscriptions.push(
743
+ this._eventPubSubService.subscribe('onLanguageChange', () => {
744
+ if (gridOptions.enableTranslate) {
745
+ this.extensionService.translateAllExtensions();
746
+ this.translateColumnHeaderTitleKeys();
747
+ this.translateColumnGroupKeys();
748
+ if (gridOptions.createPreHeaderPanel && !gridOptions.enableDraggableGrouping) {
749
+ this.groupingService.translateGroupingAndColSpan();
750
+ }
751
+ }
752
+ })
753
+ );
754
+
755
+ // if user set an onInit Backend, we'll run it right away (and if so, we also need to run preProcess, internalPostProcess & postProcess)
756
+ if (gridOptions.backendServiceApi) {
757
+ const backendApi = gridOptions.backendServiceApi;
758
+
759
+ if (backendApi?.service?.init) {
760
+ backendApi.service.init(backendApi.options, gridOptions.pagination, this.slickGrid, this.sharedService);
761
+ }
762
+ }
763
+
764
+ if (dataView && grid) {
765
+ // after all events are exposed
766
+ // we can bind external filter (backend) when available or default onFilter (dataView)
767
+ if (gridOptions.enableFiltering) {
768
+ this.filterService.init(grid);
769
+
770
+ // bind external filter (backend) unless specified to use the local one
771
+ if (gridOptions.backendServiceApi && !gridOptions.backendServiceApi.useLocalFiltering) {
772
+ this.filterService.bindBackendOnFilter(grid);
773
+ } else {
774
+ this.filterService.bindLocalOnFilter(grid);
775
+ }
776
+ }
777
+
778
+ // bind external sorting (backend) when available or default onSort (dataView)
779
+ if (gridOptions.enableSorting) {
780
+ // bind external sorting (backend) unless specified to use the local one
781
+ if (gridOptions.backendServiceApi && !gridOptions.backendServiceApi.useLocalSorting) {
782
+ this.sortService.bindBackendOnSort(grid);
783
+ } else {
784
+ this.sortService.bindLocalOnSort(grid);
785
+ }
786
+ }
787
+
788
+ // When data changes in the DataView, we need to refresh the metrics and/or display a warning if the dataset is empty
789
+ this._eventHandler.subscribe(dataView.onRowCountChanged, () => {
790
+ grid.invalidate();
791
+ this.handleOnItemCountChanged(this.dataView?.getFilteredItemCount() || 0, this.dataView?.getItemCount() ?? 0);
792
+ });
793
+ this._eventHandler.subscribe(dataView.onSetItemsCalled, (_e, args) => {
794
+ this.handleOnItemCountChanged(this.dataView?.getFilteredItemCount() || 0, args.itemCount);
795
+
796
+ // when user has resize by content enabled, we'll force a full width calculation since we change our entire dataset
797
+ if (args.itemCount > 0 && (this.gridOptions.autosizeColumnsByCellContentOnFirstLoad || this.gridOptions.enableAutoResizeColumnsByCellContent)) {
798
+ this.resizerService.resizeColumnsByCellContent(!this.gridOptions?.resizeByContentOnlyOnFirstLoad);
799
+ }
800
+ });
801
+
802
+ // when filtering data with local dataset, we need to update each row else it will not always show correctly in the UI
803
+ // also don't use "invalidateRows" since it destroys the entire row and as bad user experience when updating a row
804
+ if (gridOptions && gridOptions.enableFiltering && !gridOptions.enableRowDetailView) {
805
+ this._eventHandler.subscribe(dataView.onRowsChanged, (_e, args) => {
806
+ if (args?.rows && Array.isArray(args.rows)) {
807
+ args.rows.forEach((row: number) => grid.updateRow(row));
808
+ grid.render();
809
+ }
810
+ });
811
+ }
812
+
813
+ // when column are reordered, we need to update the visibleColumn array
814
+ this._eventHandler.subscribe(grid.onColumnsReordered, (_e, args) => {
815
+ this.sharedService.hasColumnsReordered = true;
816
+ this.sharedService.visibleColumns = args.impactedColumns;
817
+ });
818
+
819
+ // load any presets if any (after dataset is initialized)
820
+ this.loadColumnPresetsWhenDatasetInitialized();
821
+ this.loadFilterPresetsWhenDatasetInitialized();
822
+ }
823
+
824
+ // did the user add a colspan callback? If so, hook it into the DataView getItemMetadata
825
+ if (gridOptions?.colspanCallback && dataView?.getItem && dataView?.getItemMetadata) {
826
+ dataView.getItemMetadata = (rowNumber: number) => {
827
+ let callbackResult = null;
828
+ if (gridOptions.colspanCallback) {
829
+ callbackResult = gridOptions.colspanCallback(dataView.getItem(rowNumber));
830
+ }
831
+ return callbackResult;
832
+ };
833
+ }
834
+ }
835
+
836
+ bindBackendCallbackFunctions(gridOptions: GridOption) {
837
+ const backendApi = gridOptions.backendServiceApi;
838
+ const backendApiService = backendApi?.service;
839
+ const serviceOptions: BackendServiceOption = backendApiService?.options ?? {};
840
+ const isExecuteCommandOnInit = (!serviceOptions) ? false : ((serviceOptions?.hasOwnProperty('executeProcessCommandOnInit')) ? serviceOptions['executeProcessCommandOnInit'] : true);
841
+
842
+ if (backendApiService) {
843
+ // update backend filters (if need be) BEFORE the query runs (via the onInit command a few lines below)
844
+ // if user entered some any "presets", we need to reflect them all in the grid
845
+ if (gridOptions?.presets) {
846
+ // Filters "presets"
847
+ if (backendApiService.updateFilters && Array.isArray(gridOptions.presets.filters) && gridOptions.presets.filters.length > 0) {
848
+ backendApiService.updateFilters(gridOptions.presets.filters, true);
849
+ }
850
+ // Sorters "presets"
851
+ if (backendApiService.updateSorters && Array.isArray(gridOptions.presets.sorters) && gridOptions.presets.sorters.length > 0) {
852
+ // when using multi-column sort, we can have multiple but on single sort then only grab the first sort provided
853
+ const sortColumns = this._gridOptions?.multiColumnSort ? gridOptions.presets.sorters : gridOptions.presets.sorters.slice(0, 1);
854
+ backendApiService.updateSorters(undefined, sortColumns);
855
+ }
856
+ // Pagination "presets"
857
+ if (backendApiService.updatePagination && gridOptions.presets.pagination) {
858
+ const { pageNumber, pageSize } = gridOptions.presets.pagination;
859
+ backendApiService.updatePagination(pageNumber, pageSize);
860
+ }
861
+ } else {
862
+ const columnFilters = this.filterService.getColumnFilters();
863
+ if (columnFilters && backendApiService.updateFilters) {
864
+ backendApiService.updateFilters(columnFilters, false);
865
+ }
866
+ }
867
+
868
+ // execute onInit command when necessary
869
+ if (backendApi && backendApiService && (backendApi.onInit || isExecuteCommandOnInit)) {
870
+ const query = (typeof backendApiService.buildQuery === 'function') ? backendApiService.buildQuery() : '';
871
+ const process = isExecuteCommandOnInit ? (backendApi.process?.(query) ?? null) : (backendApi.onInit?.(query) ?? null);
872
+
873
+ // wrap this inside a setTimeout to avoid timing issue since the gridOptions needs to be ready before running this onInit
874
+ setTimeout(() => {
875
+ const backendUtilityService = this.backendUtilityService as BackendUtilityService;
876
+ // keep start time & end timestamps & return it after process execution
877
+ const startTime = new Date();
878
+
879
+ // run any pre-process, if defined, for example a spinner
880
+ if (backendApi.preProcess) {
881
+ backendApi.preProcess();
882
+ }
883
+
884
+ // the processes can be a Promise (like Http)
885
+ const totalItems = this.gridOptions?.pagination?.totalItems ?? 0;
886
+ if (process instanceof Promise) {
887
+ process
888
+ .then((processResult: any) => backendUtilityService.executeBackendProcessesCallback(startTime, processResult, backendApi, totalItems))
889
+ .catch((error) => backendUtilityService.onBackendError(error, backendApi));
890
+ } else if (process && this.rxjs?.isObservable(process)) {
891
+ this.subscriptions.push(
892
+ (process as Observable<any>).subscribe(
893
+ (processResult: any) => backendUtilityService.executeBackendProcessesCallback(startTime, processResult, backendApi, totalItems),
894
+ (error: any) => backendUtilityService.onBackendError(error, backendApi)
895
+ )
896
+ );
897
+ }
898
+ });
899
+ }
900
+ }
901
+ }
902
+
903
+ bindResizeHook(grid: SlickGrid, options: GridOption) {
904
+ if ((options.autoFitColumnsOnFirstLoad && options.autosizeColumnsByCellContentOnFirstLoad) || (options.enableAutoSizeColumns && options.enableAutoResizeColumnsByCellContent)) {
905
+ throw new Error(`[Slickgrid-Universal] You cannot enable both autosize/fit viewport & resize by content, you must choose which resize technique to use. You can enable these 2 options ("autoFitColumnsOnFirstLoad" and "enableAutoSizeColumns") OR these other 2 options ("autosizeColumnsByCellContentOnFirstLoad" and "enableAutoResizeColumnsByCellContent").`);
906
+ }
907
+
908
+ if (grid && options.autoFitColumnsOnFirstLoad && options.enableAutoSizeColumns && typeof grid.autosizeColumns === 'function') {
909
+ // expand/autofit columns on first page load
910
+ grid.autosizeColumns();
911
+ }
912
+
913
+ // auto-resize grid on browser resize (optionally provide grid height or width)
914
+ if (options.gridHeight || options.gridWidth) {
915
+ this.resizerService.resizeGrid(0, { height: options.gridHeight, width: options.gridWidth });
916
+ } else {
917
+ this.resizerService.resizeGrid();
918
+ }
919
+
920
+ if (grid && options?.enableAutoResize) {
921
+ if (options.autoFitColumnsOnFirstLoad && options.enableAutoSizeColumns && typeof grid.autosizeColumns === 'function') {
922
+ grid.autosizeColumns();
923
+ }
924
+ }
925
+ }
926
+
927
+ executeAfterDataviewCreated(gridOptions: GridOption) {
928
+ // if user entered some Sort "presets", we need to reflect them all in the DOM
929
+ if (gridOptions.enableSorting) {
930
+ if (gridOptions.presets && Array.isArray(gridOptions.presets.sorters)) {
931
+ // when using multi-column sort, we can have multiple but on single sort then only grab the first sort provided
932
+ const sortColumns = this._gridOptions?.multiColumnSort ? gridOptions.presets.sorters : gridOptions.presets.sorters.slice(0, 1);
933
+ this.sortService.loadGridSorters(sortColumns);
934
+ }
935
+ }
936
+ }
937
+
938
+ /**
939
+ * On a Pagination changed, we will trigger a Grid State changed with the new pagination info
940
+ * Also if we use Row Selection or the Checkbox Selector with a Backend Service (Odata, GraphQL), we need to reset any selection
941
+ */
942
+ paginationChanged(pagination: ServicePagination) {
943
+ const isSyncGridSelectionEnabled = this.gridStateService?.needToPreserveRowSelection() ?? false;
944
+ if (this.slickGrid && !isSyncGridSelectionEnabled && this._gridOptions?.backendServiceApi && (this.gridOptions.enableRowSelection || this.gridOptions.enableCheckboxSelector)) {
945
+ this.slickGrid.setSelectedRows([]);
946
+ }
947
+ const { pageNumber, pageSize } = pagination;
948
+ if (this.sharedService) {
949
+ if (pageSize !== undefined && pageNumber !== undefined) {
950
+ this.sharedService.currentPagination = { pageNumber, pageSize };
951
+ }
952
+ }
953
+ this._eventPubSubService.publish('onGridStateChanged', {
954
+ change: { newValues: { pageNumber, pageSize }, type: GridStateType.pagination },
955
+ gridState: this.gridStateService.getCurrentGridState()
956
+ });
957
+ }
958
+
959
+ /**
960
+ * When dataset changes, we need to refresh the entire grid UI & possibly resize it as well
961
+ * @param dataset
962
+ */
963
+ refreshGridData(dataset: any[], totalCount?: number) {
964
+ // local grid, check if we need to show the Pagination
965
+ // if so then also check if there's any presets and finally initialize the PaginationService
966
+ // a local grid with Pagination presets will potentially have a different total of items, we'll need to get it from the DataView and update our total
967
+ if (this.slickGrid && this._gridOptions) {
968
+ if (this._gridOptions.enablePagination && this._isLocalGrid) {
969
+ this.showPagination = true;
970
+ this.loadLocalGridPagination(dataset);
971
+ }
972
+
973
+ if (this._gridOptions.enableEmptyDataWarningMessage && Array.isArray(dataset)) {
974
+ const finalTotalCount = totalCount || dataset.length;
975
+ this.displayEmptyDataWarning(finalTotalCount < 1);
976
+ }
977
+
978
+ if (Array.isArray(dataset) && this.slickGrid && this.dataView?.setItems) {
979
+ this.dataView.setItems(dataset, this._gridOptions.datasetIdPropertyName);
980
+ if (!this._gridOptions.backendServiceApi && !this._gridOptions.enableTreeData) {
981
+ this.dataView.reSort();
982
+ }
983
+
984
+ if (dataset.length > 0) {
985
+ if (!this._isDatasetInitialized) {
986
+ this.loadFilterPresetsWhenDatasetInitialized();
987
+
988
+ if (this._gridOptions.enableCheckboxSelector) {
989
+ this.loadRowSelectionPresetWhenExists();
990
+ }
991
+ }
992
+ this._isDatasetInitialized = true;
993
+ }
994
+
995
+ if (dataset) {
996
+ this.slickGrid.invalidate();
997
+ }
998
+
999
+ // display the Pagination component only after calling this refresh data first, we call it here so that if we preset pagination page number it will be shown correctly
1000
+ this.showPagination = (this._gridOptions && (this._gridOptions.enablePagination || (this._gridOptions.backendServiceApi && this._gridOptions.enablePagination === undefined))) ? true : false;
1001
+
1002
+ if (this._paginationOptions && this._gridOptions?.pagination && this._gridOptions?.backendServiceApi) {
1003
+ const paginationOptions = this.setPaginationOptionsWhenPresetDefined(this._gridOptions, this._paginationOptions);
1004
+
1005
+ // when we have a totalCount use it, else we'll take it from the pagination object
1006
+ // only update the total items if it's different to avoid refreshing the UI
1007
+ const totalRecords = (totalCount !== undefined) ? totalCount : (this._gridOptions?.pagination?.totalItems);
1008
+ if (totalRecords !== undefined && totalRecords !== this.totalItems) {
1009
+ this.totalItems = +totalRecords;
1010
+ }
1011
+ // initialize the Pagination Service with new pagination options (which might have presets)
1012
+ if (!this._isPaginationInitialized) {
1013
+ this.initializePaginationService(paginationOptions);
1014
+ } else {
1015
+ // update the pagination service with the new total
1016
+ this.paginationService.updateTotalItems(this.totalItems);
1017
+ }
1018
+ }
1019
+
1020
+ // resize the grid inside a slight timeout, in case other DOM element changed prior to the resize (like a filter/pagination changed)
1021
+ if (this.slickGrid && this._gridOptions.enableAutoResize) {
1022
+ const delay = this._gridOptions.autoResize && this._gridOptions.autoResize.delay;
1023
+ this.resizerService.resizeGrid(delay || 10);
1024
+ }
1025
+ }
1026
+ }
1027
+ }
1028
+
1029
+ /**
1030
+ * Dynamically change or update the column definitions list.
1031
+ * We will re-render the grid so that the new header and data shows up correctly.
1032
+ * If using translater, we also need to trigger a re-translate of the column headers
1033
+ */
1034
+ updateColumnDefinitionsList(newColumnDefinitions: Column<TData>[]) {
1035
+ if (this.slickGrid && this._gridOptions && Array.isArray(newColumnDefinitions)) {
1036
+ // map/swap the internal library Editor to the SlickGrid Editor factory
1037
+ newColumnDefinitions = this.swapInternalEditorToSlickGridFactoryEditor(newColumnDefinitions);
1038
+
1039
+ // if the user wants to automatically add a Custom Editor Formatter, we need to call the auto add function again
1040
+ if (this._gridOptions.autoAddCustomEditorFormatter) {
1041
+ autoAddEditorFormatterToColumnsWithEditor(newColumnDefinitions, this._gridOptions.autoAddCustomEditorFormatter);
1042
+ }
1043
+
1044
+ if (this._gridOptions.enableTranslate) {
1045
+ this.extensionService.translateColumnHeaders(false, newColumnDefinitions);
1046
+ } else {
1047
+ this.extensionService.renderColumnHeaders(newColumnDefinitions, true);
1048
+ }
1049
+
1050
+ if (this.slickGrid && this._gridOptions?.enableAutoSizeColumns) {
1051
+ this.slickGrid.autosizeColumns();
1052
+ } else if (this._gridOptions?.enableAutoResizeColumnsByCellContent && this.resizerService?.resizeColumnsByCellContent) {
1053
+ this.resizerService.resizeColumnsByCellContent();
1054
+ }
1055
+ }
1056
+ }
1057
+
1058
+ /**
1059
+ * Show the filter row displayed on first row, we can optionally pass false to hide it.
1060
+ * @param showing
1061
+ */
1062
+ showHeaderRow(showing = true) {
1063
+ this.slickGrid?.setHeaderRowVisibility(showing);
1064
+ if (this.slickGrid && showing === true && this._isGridInitialized) {
1065
+ this.slickGrid.setColumns(this.columnDefinitions);
1066
+ }
1067
+ return showing;
1068
+ }
1069
+
1070
+ /**
1071
+ * Check if there's any Pagination Presets defined in the Grid Options,
1072
+ * if there are then load them in the paginationOptions object
1073
+ */
1074
+ setPaginationOptionsWhenPresetDefined(gridOptions: GridOption, paginationOptions: Pagination): Pagination {
1075
+ if (gridOptions.presets?.pagination && paginationOptions && !this._isPaginationInitialized) {
1076
+ paginationOptions.pageSize = gridOptions.presets.pagination.pageSize;
1077
+ paginationOptions.pageNumber = gridOptions.presets.pagination.pageNumber;
1078
+ }
1079
+ return paginationOptions;
1080
+ }
1081
+
1082
+ // --
1083
+ // protected functions
1084
+ // ------------------
1085
+
1086
+ /**
1087
+ * Loop through all column definitions and copy the original optional `width` properties optionally provided by the user.
1088
+ * We will use this when doing a resize by cell content, if user provided a `width` it won't override it.
1089
+ */
1090
+ protected copyColumnWidthsReference(columnDefinitions: Column<TData>[]) {
1091
+ columnDefinitions.forEach(col => col.originalWidth = col.width);
1092
+ }
1093
+
1094
+ protected displayEmptyDataWarning(showWarning = true) {
1095
+ this.slickEmptyWarning?.showEmptyDataMessage(showWarning);
1096
+ }
1097
+
1098
+ /** When data changes in the DataView, we'll refresh the metrics and/or display a warning if the dataset is empty */
1099
+ protected handleOnItemCountChanged(currentPageRowItemCount: number, totalItemCount: number) {
1100
+ this._currentDatasetLength = totalItemCount;
1101
+ this.metrics = {
1102
+ startTime: new Date(),
1103
+ endTime: new Date(),
1104
+ itemCount: currentPageRowItemCount,
1105
+ totalItemCount
1106
+ };
1107
+ // if custom footer is enabled, then we'll update its metrics
1108
+ if (this.slickFooter) {
1109
+ this.slickFooter.metrics = this.metrics;
1110
+ }
1111
+
1112
+ // when using local (in-memory) dataset, we'll display a warning message when filtered data is empty
1113
+ if (this._isLocalGrid && this._gridOptions?.enableEmptyDataWarningMessage) {
1114
+ this.displayEmptyDataWarning(currentPageRowItemCount === 0);
1115
+ }
1116
+ }
1117
+
1118
+ /** Initialize the Pagination Service once */
1119
+ protected initializePaginationService(paginationOptions: Pagination) {
1120
+ if (this.slickGrid && this.gridOptions) {
1121
+ this.paginationData = {
1122
+ gridOptions: this.gridOptions,
1123
+ paginationService: this.paginationService,
1124
+ };
1125
+ this.paginationService.totalItems = this.totalItems;
1126
+ this.paginationService.init(this.slickGrid, paginationOptions, this.backendServiceApi);
1127
+ this.subscriptions.push(
1128
+ this._eventPubSubService.subscribe<ServicePagination>('onPaginationChanged', paginationChanges => this.paginationChanged(paginationChanges)),
1129
+ this._eventPubSubService.subscribe<{ visible: boolean; }>('onPaginationVisibilityChanged', visibility => {
1130
+ this.showPagination = visibility?.visible ?? false;
1131
+ if (this.gridOptions?.backendServiceApi) {
1132
+ this.backendUtilityService?.refreshBackendDataset(this.gridOptions);
1133
+ }
1134
+ this.renderPagination(this.showPagination);
1135
+ })
1136
+ );
1137
+
1138
+ // also initialize (render) the pagination component
1139
+ this.renderPagination();
1140
+ this._isPaginationInitialized = true;
1141
+ }
1142
+ }
1143
+
1144
+ /**
1145
+ * Render (or dispose) the Pagination Component, user can optionally provide False (to not show it) which will in term dispose of the Pagination,
1146
+ * also while disposing we can choose to omit the disposable of the Pagination Service (if we are simply toggling the Pagination, we want to keep the Service alive)
1147
+ * @param {Boolean} showPagination - show (new render) or not (dispose) the Pagination
1148
+ * @param {Boolean} shouldDisposePaginationService - when disposing the Pagination, do we also want to dispose of the Pagination Service? (defaults to True)
1149
+ */
1150
+ protected renderPagination(showPagination = true) {
1151
+ if (this._gridOptions?.enablePagination && !this._isPaginationInitialized && showPagination) {
1152
+ this.slickPagination = new SlickPaginationComponent(this.paginationService, this._eventPubSubService, this.sharedService, this.translaterService);
1153
+ this.slickPagination.renderPagination(this._gridParentContainerElm);
1154
+ this._isPaginationInitialized = true;
1155
+ } else if (!showPagination) {
1156
+ if (this.slickPagination) {
1157
+ this.slickPagination.dispose();
1158
+ }
1159
+ this._isPaginationInitialized = false;
1160
+ }
1161
+ }
1162
+
1163
+ /** Load the Editor Collection asynchronously and replace the "collection" property when Promise resolves */
1164
+ protected loadEditorCollectionAsync(column: Column<TData>) {
1165
+ const collectionAsync = (column?.editor as ColumnEditor).collectionAsync;
1166
+ (column?.editor as ColumnEditor).disabled = true; // disable the Editor DOM element, we'll re-enable it after receiving the collection with "updateEditorCollection()"
1167
+
1168
+ if (collectionAsync instanceof Promise) {
1169
+ // wait for the "collectionAsync", once resolved we will save it into the "collection"
1170
+ // the collectionAsync can be of 3 types HttpClient, HttpFetch or a Promise
1171
+ collectionAsync.then((response: any | any[]) => {
1172
+ if (Array.isArray(response)) {
1173
+ this.updateEditorCollection(column, response); // from Promise
1174
+ } else if (response?.status >= 200 && response.status < 300 && typeof response.json === 'function') {
1175
+ if (response.bodyUsed) {
1176
+ console.warn(`[SlickGrid-Universal] The response body passed to collectionAsync was already read.`
1177
+ + `Either pass the dataset from the Response or clone the response first using response.clone()`);
1178
+ } else {
1179
+ // from Fetch
1180
+ (response as Response).json().then(data => this.updateEditorCollection(column, data));
1181
+ }
1182
+ } else if (response?.content) {
1183
+ this.updateEditorCollection(column, response['content']); // from http-client
1184
+ }
1185
+ });
1186
+ } else if (this.rxjs?.isObservable(collectionAsync)) {
1187
+ // wrap this inside a setTimeout to avoid timing issue since updateEditorCollection requires to call SlickGrid getColumns() method
1188
+ setTimeout(() => {
1189
+ this.subscriptions.push(
1190
+ (collectionAsync as Observable<any>).subscribe((resolvedCollection) => this.updateEditorCollection(column, resolvedCollection))
1191
+ );
1192
+ });
1193
+ }
1194
+ }
1195
+
1196
+ protected insertDynamicPresetColumns(columnId: string, gridPresetColumns: Column<TData>[]) {
1197
+ if (this._columnDefinitions) {
1198
+ const columnPosition = this._columnDefinitions.findIndex(c => c.id === columnId);
1199
+ if (columnPosition >= 0) {
1200
+ const dynColumn = this._columnDefinitions[columnPosition];
1201
+ if (dynColumn?.id === columnId && !gridPresetColumns.some(c => c.id === columnId)) {
1202
+ columnPosition > 0
1203
+ ? gridPresetColumns.splice(columnPosition, 0, dynColumn)
1204
+ : gridPresetColumns.unshift(dynColumn);
1205
+ }
1206
+ }
1207
+ }
1208
+ }
1209
+
1210
+ /** Load any possible Columns Grid Presets */
1211
+ protected loadColumnPresetsWhenDatasetInitialized() {
1212
+ // if user entered some Columns "presets", we need to reflect them all in the grid
1213
+ if (this.slickGrid && this.gridOptions.presets && Array.isArray(this.gridOptions.presets.columns) && this.gridOptions.presets.columns.length > 0) {
1214
+ const gridPresetColumns: Column<TData>[] = this.gridStateService.getAssociatedGridColumns(this.slickGrid, this.gridOptions.presets.columns);
1215
+ if (gridPresetColumns && Array.isArray(gridPresetColumns) && gridPresetColumns.length > 0 && Array.isArray(this._columnDefinitions)) {
1216
+ // make sure that the dynamic columns are included in presets (1.Row Move, 2. Row Selection, 3. Row Detail)
1217
+ if (this.gridOptions.enableRowMoveManager) {
1218
+ const rmmColId = this.gridOptions?.rowMoveManager?.columnId ?? '_move';
1219
+ this.insertDynamicPresetColumns(rmmColId, gridPresetColumns);
1220
+ }
1221
+ if (this.gridOptions.enableCheckboxSelector) {
1222
+ const chkColId = this.gridOptions?.checkboxSelector?.columnId ?? '_checkbox_selector';
1223
+ this.insertDynamicPresetColumns(chkColId, gridPresetColumns);
1224
+ }
1225
+ if (this.gridOptions.enableRowDetailView) {
1226
+ const rdvColId = this.gridOptions?.rowDetailView?.columnId ?? '_detail_selector';
1227
+ this.insertDynamicPresetColumns(rdvColId, gridPresetColumns);
1228
+ }
1229
+
1230
+ // keep copy the original optional `width` properties optionally provided by the user.
1231
+ // We will use this when doing a resize by cell content, if user provided a `width` it won't override it.
1232
+ gridPresetColumns.forEach(col => col.originalWidth = col.width);
1233
+
1234
+ // finally set the new presets columns (including checkbox selector if need be)
1235
+ this.slickGrid.setColumns(gridPresetColumns);
1236
+ this.sharedService.visibleColumns = gridPresetColumns;
1237
+ }
1238
+ }
1239
+ }
1240
+
1241
+ /** Load any possible Filters Grid Presets */
1242
+ protected loadFilterPresetsWhenDatasetInitialized() {
1243
+ if (this.gridOptions && !this.customDataView) {
1244
+ // if user entered some Filter "presets", we need to reflect them all in the DOM
1245
+ // also note that a presets of Tree Data Toggling will also call this method because Tree Data toggling does work with data filtering
1246
+ // (collapsing a parent will basically use Filter for hidding (aka collapsing) away the child underneat it)
1247
+ if (this.gridOptions.presets && (Array.isArray(this.gridOptions.presets.filters) || Array.isArray(this.gridOptions.presets?.treeData?.toggledItems))) {
1248
+ this.filterService.populateColumnFilterSearchTermPresets(this.gridOptions.presets?.filters || []);
1249
+ }
1250
+ }
1251
+ }
1252
+
1253
+ /**
1254
+ * local grid, check if we need to show the Pagination
1255
+ * if so then also check if there's any presets and finally initialize the PaginationService
1256
+ * a local grid with Pagination presets will potentially have a different total of items, we'll need to get it from the DataView and update our total
1257
+ */
1258
+ protected loadLocalGridPagination(dataset?: any[]) {
1259
+ if (this.gridOptions && this._paginationOptions) {
1260
+ this.totalItems = Array.isArray(dataset) ? dataset.length : 0;
1261
+ if (this._paginationOptions && this.dataView?.getPagingInfo) {
1262
+ const slickPagingInfo = this.dataView.getPagingInfo();
1263
+ if (slickPagingInfo?.hasOwnProperty('totalRows') && this._paginationOptions.totalItems !== slickPagingInfo.totalRows) {
1264
+ this.totalItems = slickPagingInfo?.totalRows || 0;
1265
+ }
1266
+ }
1267
+ this._paginationOptions.totalItems = this.totalItems;
1268
+ const paginationOptions = this.setPaginationOptionsWhenPresetDefined(this.gridOptions, this._paginationOptions);
1269
+ this.initializePaginationService(paginationOptions);
1270
+ }
1271
+ }
1272
+
1273
+ /** Load any Row Selections into the DataView that were presets by the user */
1274
+ protected loadRowSelectionPresetWhenExists() {
1275
+ // if user entered some Row Selections "presets"
1276
+ const presets = this.gridOptions?.presets;
1277
+ const selectionModel = this.slickGrid?.getSelectionModel();
1278
+ const enableRowSelection = this.gridOptions && (this.gridOptions.enableCheckboxSelector || this.gridOptions.enableRowSelection);
1279
+ if (this.slickGrid && this.dataView && enableRowSelection && selectionModel && presets?.rowSelection && (Array.isArray(presets.rowSelection.gridRowIndexes) || Array.isArray(presets.rowSelection.dataContextIds))) {
1280
+ let dataContextIds = presets.rowSelection.dataContextIds;
1281
+ let gridRowIndexes = presets.rowSelection.gridRowIndexes;
1282
+
1283
+ // maps the IDs to the Grid Rows and vice versa, the "dataContextIds" has precedence over the other
1284
+ if (Array.isArray(dataContextIds) && dataContextIds.length > 0) {
1285
+ gridRowIndexes = this.dataView.mapIdsToRows(dataContextIds) || [];
1286
+ } else if (Array.isArray(gridRowIndexes) && gridRowIndexes.length > 0) {
1287
+ dataContextIds = this.dataView.mapRowsToIds(gridRowIndexes) || [];
1288
+ }
1289
+
1290
+ // apply row selection when defined as grid presets
1291
+ if (this.slickGrid && Array.isArray(gridRowIndexes)) {
1292
+ this.slickGrid.setSelectedRows(gridRowIndexes);
1293
+ this.dataView!.setSelectedIds(dataContextIds || [], {
1294
+ isRowBeingAdded: true,
1295
+ shouldTriggerEvent: false, // do not trigger when presetting the grid
1296
+ applyRowSelectionToGrid: true
1297
+ });
1298
+ }
1299
+ }
1300
+ }
1301
+
1302
+ /** Add a register a new external resource, user could also optional dispose all previous resources before pushing any new resources to the resources array list. */
1303
+ registerExternalResources(resources: ExternalResource[], disposePreviousResources = false) {
1304
+ if (disposePreviousResources) {
1305
+ this.disposeExternalResources();
1306
+ }
1307
+ resources.forEach(res => this._registeredResources.push(res));
1308
+ this.initializeExternalResources(resources);
1309
+ }
1310
+
1311
+ resetExternalResources() {
1312
+ this._registeredResources = [];
1313
+ }
1314
+
1315
+ /** Pre-Register any Resource that don't require SlickGrid to be instantiated (for example RxJS Resource) */
1316
+ protected preRegisterResources() {
1317
+ // bind & initialize all Components/Services that were tagged as enabled
1318
+ // register all services by executing their init method and providing them with the Grid object
1319
+ if (Array.isArray(this._registeredResources)) {
1320
+ for (const resource of this._registeredResources) {
1321
+ if (resource?.className === 'RxJsResource') {
1322
+ this.registerRxJsResource(resource as RxJsFacade);
1323
+ }
1324
+ }
1325
+ }
1326
+ }
1327
+
1328
+ protected initializeExternalResources(resources: ExternalResource[]) {
1329
+ if (Array.isArray(resources)) {
1330
+ for (const resource of resources) {
1331
+ if (this.slickGrid && typeof resource.init === 'function') {
1332
+ resource.init(this.slickGrid, this.universalContainerService);
1333
+ }
1334
+ }
1335
+ }
1336
+ }
1337
+
1338
+ protected registerResources() {
1339
+ // at this point, we consider all the registered services as external services, anything else registered afterward aren't external
1340
+ if (Array.isArray(this._registeredResources)) {
1341
+ this.sharedService.externalRegisteredResources = this._registeredResources;
1342
+ }
1343
+
1344
+ // push all other Services that we want to be registered
1345
+ this._registeredResources.push(this.gridService, this.gridStateService);
1346
+
1347
+ // when using Grouping/DraggableGrouping/Colspan register its Service
1348
+ if (this.gridOptions.createPreHeaderPanel && !this.gridOptions.enableDraggableGrouping) {
1349
+ this._registeredResources.push(this.groupingService);
1350
+ }
1351
+
1352
+ // when using Tree Data View, register its Service
1353
+ if (this.gridOptions.enableTreeData) {
1354
+ this._registeredResources.push(this.treeDataService);
1355
+ }
1356
+
1357
+ // when user enables translation, we need to translate Headers on first pass & subsequently in the bindDifferentHooks
1358
+ if (this.gridOptions.enableTranslate) {
1359
+ this.extensionService.translateColumnHeaders();
1360
+ }
1361
+
1362
+ // also initialize (render) the empty warning component
1363
+ this.slickEmptyWarning = new SlickEmptyWarningComponent();
1364
+ this._registeredResources.push(this.slickEmptyWarning);
1365
+
1366
+ // bind & initialize all Components/Services that were tagged as enabled
1367
+ // register all services by executing their init method and providing them with the Grid object
1368
+ this.initializeExternalResources(this._registeredResources);
1369
+ }
1370
+
1371
+ /** Register the RxJS Resource in all necessary services which uses */
1372
+ protected registerRxJsResource(resource: RxJsFacade) {
1373
+ this.rxjs = resource;
1374
+ this.backendUtilityService.addRxJsResource(this.rxjs);
1375
+ this.filterFactory.addRxJsResource(this.rxjs);
1376
+ this.filterService.addRxJsResource(this.rxjs);
1377
+ this.sortService.addRxJsResource(this.rxjs);
1378
+ this.paginationService.addRxJsResource(this.rxjs);
1379
+ this.universalContainerService.registerInstance('RxJsFacade', this.rxjs);
1380
+ this.universalContainerService.registerInstance('RxJsResource', this.rxjs);
1381
+ }
1382
+
1383
+ /**
1384
+ * Takes a flat dataset with parent/child relationship, sort it (via its tree structure) and return the sorted flat array
1385
+ * @returns {Array<Object>} sort flat parent/child dataset
1386
+ */
1387
+ protected sortTreeDataset<U>(flatDatasetInput: U[], forceGridRefresh = false): U[] {
1388
+ const prevDatasetLn = this._currentDatasetLength;
1389
+ let sortedDatasetResult;
1390
+ let flatDatasetOutput: any[] = [];
1391
+
1392
+ // if the hierarchical dataset was already initialized then no need to re-convert it, we can use it directly from the shared service ref
1393
+ if (this._isDatasetHierarchicalInitialized && this.datasetHierarchical) {
1394
+ sortedDatasetResult = this.treeDataService.sortHierarchicalDataset(this.datasetHierarchical);
1395
+ flatDatasetOutput = sortedDatasetResult.flat;
1396
+ } else if (Array.isArray(flatDatasetInput) && flatDatasetInput.length > 0) {
1397
+ if (this.gridOptions?.treeDataOptions?.initialSort) {
1398
+ // else we need to first convert the flat dataset to a hierarchical dataset and then sort
1399
+ sortedDatasetResult = this.treeDataService.convertFlatParentChildToTreeDatasetAndSort(flatDatasetInput, this._columnDefinitions || [], this.gridOptions);
1400
+ this.sharedService.hierarchicalDataset = sortedDatasetResult.hierarchical;
1401
+ flatDatasetOutput = sortedDatasetResult.flat;
1402
+ } else {
1403
+ // else we assume that the user provided an array that is already sorted (user's responsability)
1404
+ // and so we can simply convert the array to a tree structure and we're done, no need to sort
1405
+ this.sharedService.hierarchicalDataset = this.treeDataService.convertFlatParentChildToTreeDataset(flatDatasetInput, this.gridOptions);
1406
+ flatDatasetOutput = flatDatasetInput || [];
1407
+ }
1408
+ }
1409
+
1410
+ // if we add/remove item(s) from the dataset, we need to also refresh our tree data filters
1411
+ if (flatDatasetInput.length > 0 && (forceGridRefresh || flatDatasetInput.length !== prevDatasetLn)) {
1412
+ this.filterService.refreshTreeDataFilters(flatDatasetOutput);
1413
+ }
1414
+
1415
+ return flatDatasetOutput;
1416
+ }
1417
+
1418
+ /**
1419
+ * For convenience to the user, we provide the property "editor" as an Slickgrid-Universal editor complex object
1420
+ * however "editor" is used internally by SlickGrid for it's own Editor Factory
1421
+ * so in our lib we will swap "editor" and copy it into a new property called "internalColumnEditor"
1422
+ * then take back "editor.model" and make it the new "editor" so that SlickGrid Editor Factory still works
1423
+ */
1424
+ protected swapInternalEditorToSlickGridFactoryEditor(columnDefinitions: Column<TData>[]): Column<TData>[] {
1425
+ const columns = Array.isArray(columnDefinitions) ? columnDefinitions : [];
1426
+
1427
+ if (columns.some(col => `${col.id}`.includes('.'))) {
1428
+ console.error('[Slickgrid-Universal] Make sure that none of your Column Definition "id" property includes a dot in its name because that will cause some problems with the Editors. For example if your column definition "field" property is "user.firstName" then use "firstName" as the column "id".');
1429
+ }
1430
+
1431
+ return columns.map((column) => {
1432
+ // on every Editor that have a "collectionAsync", resolve the data and assign it to the "collection" property
1433
+ if ((column.editor as ColumnEditor)?.collectionAsync) {
1434
+ this.loadEditorCollectionAsync(column);
1435
+ }
1436
+
1437
+ // if there's already an internalColumnEditor we'll use it, else it would be inside the editor
1438
+ const columnEditor = column.internalColumnEditor || column.editor as ColumnEditor;
1439
+
1440
+ return { ...column, editor: columnEditor?.model, internalColumnEditor: { ...columnEditor } };
1441
+ });
1442
+ }
1443
+
1444
+ /** translate all columns (including hidden columns) */
1445
+ protected translateColumnHeaderTitleKeys() {
1446
+ this.extensionUtility.translateItems(this.sharedService.allColumns, 'nameKey', 'name');
1447
+ }
1448
+
1449
+ /** translate all column groups (including hidden columns) */
1450
+ protected translateColumnGroupKeys() {
1451
+ this.extensionUtility.translateItems(this.sharedService.allColumns, 'columnGroupKey', 'columnGroup');
1452
+ }
1453
+
1454
+ /**
1455
+ * Update the "internalColumnEditor.collection" property.
1456
+ * Since this is called after the async call resolves, the pointer will not be the same as the "column" argument passed.
1457
+ * Once we found the new pointer, we will reassign the "editor" and "collection" to the "internalColumnEditor" so it has newest collection
1458
+ */
1459
+ protected updateEditorCollection<U extends TData = any>(column: Column<U>, newCollection: U[]) {
1460
+ (column.editor as ColumnEditor).collection = newCollection;
1461
+ (column.editor as ColumnEditor).disabled = false;
1462
+
1463
+ if (this.slickGrid) {
1464
+ // find the new column reference pointer & re-assign the new editor to the internalColumnEditor
1465
+ if (Array.isArray(this.columnDefinitions)) {
1466
+ const columnRef = this.columnDefinitions.find((col: Column) => col.id === column.id);
1467
+ if (columnRef) {
1468
+ columnRef.internalColumnEditor = column.editor as ColumnEditor;
1469
+ }
1470
+ }
1471
+
1472
+ // get current Editor, remove it from the DOm then re-enable it and re-render it with the new collection.
1473
+ const currentEditor = this.slickGrid.getCellEditor() as AutocompleterEditor | SelectEditor;
1474
+ if (currentEditor?.disable && currentEditor?.renderDomElement) {
1475
+ if (typeof currentEditor.destroy === 'function') {
1476
+ currentEditor.destroy();
1477
+ }
1478
+ currentEditor.disable(false);
1479
+ currentEditor.renderDomElement(newCollection);
1480
+ }
1481
+ }
1482
+ }
1483
+ }