@slickgrid-universal/vanilla-bundle 5.0.0-beta.2 → 5.0.0-beta.3

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