@adaptabletools/adaptable-cjs 18.0.0-canary.4 → 18.0.0-canary.5

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.
Files changed (169) hide show
  1. package/agGrid.d.ts +4 -21
  2. package/agGrid.js +5 -21
  3. package/base.css +1 -1
  4. package/base.css.map +1 -1
  5. package/index.css +74 -68
  6. package/index.css.map +1 -1
  7. package/package.json +3 -4
  8. package/src/AdaptableInterfaces/IAdaptable.d.ts +55 -109
  9. package/src/AdaptableOptions/AdaptableOptions.d.ts +6 -0
  10. package/src/AdaptableOptions/UserInterfaceOptions.d.ts +17 -0
  11. package/src/Api/AdaptableApi.d.ts +5 -0
  12. package/src/Api/ColumnFilterApi.d.ts +0 -5
  13. package/src/Api/Events/AdaptableReady.d.ts +3 -3
  14. package/src/Api/Events/GridDataChanged.d.ts +4 -4
  15. package/src/Api/GridApi.d.ts +14 -13
  16. package/src/Api/Implementation/ActionColumnApiImpl.d.ts +2 -0
  17. package/src/Api/Implementation/ActionColumnApiImpl.js +33 -0
  18. package/src/Api/Implementation/AdaptableApiImpl.d.ts +1 -0
  19. package/src/Api/Implementation/AdaptableApiImpl.js +3 -0
  20. package/src/Api/Implementation/ApiBase.d.ts +2 -1
  21. package/src/Api/Implementation/ApiBase.js +3 -0
  22. package/src/Api/Implementation/ColumnFilterApiImpl.d.ts +0 -1
  23. package/src/Api/Implementation/ColumnFilterApiImpl.js +0 -10
  24. package/src/Api/Implementation/CommentsApiImpl.js +2 -1
  25. package/src/Api/Implementation/ConfigApiImpl.js +8 -3
  26. package/src/Api/Implementation/GridApiImpl.d.ts +3 -3
  27. package/src/Api/Implementation/GridApiImpl.js +20 -14
  28. package/src/Api/Implementation/StatusBarApiImpl.d.ts +0 -1
  29. package/src/Api/Implementation/StatusBarApiImpl.js +0 -3
  30. package/src/Api/Implementation/ToolPanelApiImpl.js +6 -6
  31. package/src/Api/Internal/ActionRowInternalApi.d.ts +5 -1
  32. package/src/Api/Internal/ActionRowInternalApi.js +107 -0
  33. package/src/Api/Internal/AdaptableInternalApi.d.ts +3 -4
  34. package/src/Api/Internal/AdaptableInternalApi.js +10 -8
  35. package/src/Api/Internal/CalculatedColumnInternalApi.d.ts +2 -0
  36. package/src/Api/Internal/CalculatedColumnInternalApi.js +71 -0
  37. package/src/Api/Internal/ColumnFilterInternalApi.d.ts +1 -0
  38. package/src/Api/Internal/ColumnFilterInternalApi.js +11 -1
  39. package/src/Api/Internal/ColumnInternalApi.d.ts +4 -1
  40. package/src/Api/Internal/ColumnInternalApi.js +12 -0
  41. package/src/Api/Internal/CustomSortInternalApi.d.ts +3 -2
  42. package/src/Api/Internal/CustomSortInternalApi.js +32 -1
  43. package/src/Api/Internal/DataSetInternalApi.js +1 -1
  44. package/src/Api/Internal/FreeTextColumnInternalApi.d.ts +2 -0
  45. package/src/Api/Internal/FreeTextColumnInternalApi.js +60 -0
  46. package/src/Api/Internal/GridFilterInternalApi.js +1 -1
  47. package/src/Api/Internal/GridInternalApi.d.ts +21 -3
  48. package/src/Api/Internal/GridInternalApi.js +126 -7
  49. package/src/Api/Internal/TeamSharingInternalApi.js +1 -1
  50. package/src/EnvVars.d.ts +3 -0
  51. package/src/EnvVars.js +8 -0
  52. package/src/PredefinedConfig/Common/AggregationColumns.d.ts +1 -0
  53. package/src/PredefinedConfig/Common/AggregationColumns.js +5 -1
  54. package/src/Redux/Store/AdaptableStore.d.ts +4 -6
  55. package/src/Redux/Store/AdaptableStore.js +22 -50
  56. package/src/Redux/Store/Interface/IAdaptableStore.d.ts +7 -1
  57. package/src/Strategy/AdaptableModuleBase.d.ts +2 -3
  58. package/src/Strategy/AdaptableModuleBase.js +4 -7
  59. package/src/Strategy/AlertModule.d.ts +1 -2
  60. package/src/Strategy/AlertModule.js +2 -55
  61. package/src/Strategy/CalculatedColumnModule.d.ts +2 -3
  62. package/src/Strategy/CalculatedColumnModule.js +5 -25
  63. package/src/Strategy/ChartingModule.d.ts +0 -1
  64. package/src/Strategy/ChartingModule.js +0 -21
  65. package/src/Strategy/ColumnFilterModule.d.ts +1 -2
  66. package/src/Strategy/ColumnFilterModule.js +1 -64
  67. package/src/Strategy/CommentsModule.d.ts +1 -0
  68. package/src/Strategy/CommentsModule.js +2 -1
  69. package/src/Strategy/CustomSortModule.js +1 -1
  70. package/src/Strategy/DashboardModule.d.ts +1 -2
  71. package/src/Strategy/DashboardModule.js +1 -8
  72. package/src/Strategy/DataChangeHistoryModule.d.ts +1 -0
  73. package/src/Strategy/DataChangeHistoryModule.js +3 -1
  74. package/src/Strategy/DataSetModule.d.ts +1 -1
  75. package/src/Strategy/DataSetModule.js +1 -1
  76. package/src/Strategy/FlashingCellModule.d.ts +1 -2
  77. package/src/Strategy/FlashingCellModule.js +2 -15
  78. package/src/Strategy/FormatColumnModule.d.ts +0 -2
  79. package/src/Strategy/FormatColumnModule.js +0 -47
  80. package/src/Strategy/FreeTextColumnModule.d.ts +0 -1
  81. package/src/Strategy/FreeTextColumnModule.js +0 -30
  82. package/src/Strategy/GridFilterModule.d.ts +0 -1
  83. package/src/Strategy/GridFilterModule.js +0 -37
  84. package/src/Strategy/Interface/IModule.d.ts +0 -1
  85. package/src/Strategy/LayoutModule.d.ts +1 -3
  86. package/src/Strategy/LayoutModule.js +6 -50
  87. package/src/Strategy/NamedQueryModule.d.ts +0 -1
  88. package/src/Strategy/NamedQueryModule.js +0 -19
  89. package/src/Strategy/PlusMinusModule.d.ts +1 -1
  90. package/src/Strategy/PlusMinusModule.js +1 -1
  91. package/src/Strategy/ScheduleModule.d.ts +1 -1
  92. package/src/Strategy/ScheduleModule.js +1 -1
  93. package/src/Strategy/ShortcutModule.d.ts +1 -1
  94. package/src/Strategy/ShortcutModule.js +1 -1
  95. package/src/Strategy/StyledColumnModule.d.ts +0 -1
  96. package/src/Strategy/StyledColumnModule.js +0 -21
  97. package/src/Strategy/TeamSharingModule.d.ts +1 -0
  98. package/src/Strategy/TeamSharingModule.js +5 -5
  99. package/src/Strategy/ToolPanelModule.d.ts +0 -1
  100. package/src/Strategy/ToolPanelModule.js +0 -23
  101. package/src/Utilities/Constants/GeneralConstants.d.ts +1 -0
  102. package/src/Utilities/Constants/GeneralConstants.js +3 -2
  103. package/src/Utilities/Helpers/AdaptableHelper.d.ts +0 -3
  104. package/src/Utilities/Helpers/AdaptableHelper.js +1 -60
  105. package/src/Utilities/Services/CellPopupService.js +0 -1
  106. package/src/Utilities/Services/LicenseService/index.d.ts +3 -0
  107. package/src/Utilities/Services/LicenseService/index.js +10 -3
  108. package/src/Utilities/Services/MetamodelService.d.ts +1 -1
  109. package/src/Utilities/Services/MetamodelService.js +6 -3
  110. package/src/Utilities/Services/RowEditService.d.ts +3 -2
  111. package/src/Utilities/Services/RowEditService.js +3 -1
  112. package/src/View/AdaptableView.js +0 -2
  113. package/src/View/AdaptableWizardView/AdaptableConfigurationDialog/ConfigurationWizard.js +2 -2
  114. package/src/View/CalculatedColumn/utils.d.ts +1 -1
  115. package/src/View/CellSummary/CellSummaryPopup.js +1 -1
  116. package/src/View/Components/Popups/AdaptableLoadingScreen.d.ts +6 -5
  117. package/src/View/Components/Popups/AdaptableLoadingScreen.js +19 -9
  118. package/src/View/CustomSort/CustomSortSummary.js +1 -1
  119. package/src/View/DataChangeHistory/DataChangeHistoryGrid.js +1 -1
  120. package/src/View/GridFilter/GridFilterViewPanel.js +6 -2
  121. package/src/View/GridInfo/GridInfoPopup/GridInfoPopup.js +2 -3
  122. package/src/View/Layout/Wizard/LayoutWizard.js +1 -1
  123. package/src/agGrid/ActionColumnRenderer.js +4 -4
  124. package/src/agGrid/Adaptable.d.ts +3 -455
  125. package/src/agGrid/Adaptable.js +7 -5291
  126. package/src/agGrid/AdaptableAgGrid.d.ts +336 -0
  127. package/src/agGrid/AdaptableAgGrid.js +3785 -0
  128. package/src/agGrid/AdaptableLogger.js +78 -13
  129. package/src/agGrid/AgGridAdapter.d.ts +54 -0
  130. package/src/agGrid/AgGridAdapter.js +554 -0
  131. package/src/agGrid/AgGridColumnAdapter.d.ts +56 -0
  132. package/src/agGrid/AgGridColumnAdapter.js +818 -0
  133. package/src/agGrid/AgGridMenuAdapter.d.ts +28 -0
  134. package/src/agGrid/AgGridMenuAdapter.js +276 -0
  135. package/src/agGrid/AgGridOptionsService.d.ts +11 -0
  136. package/src/agGrid/AgGridOptionsService.js +54 -0
  137. package/src/agGrid/BadgeRenderer.js +1 -1
  138. package/src/agGrid/CheckboxRenderer.js +1 -1
  139. package/src/agGrid/FilterWrapper.d.ts +2 -2
  140. package/src/agGrid/FilterWrapper.js +1 -1
  141. package/src/agGrid/attachAddaptableColumnTypes.d.ts +12 -12
  142. package/src/agGrid/defaultAdaptableOptions.d.ts +3 -0
  143. package/src/{Utilities/Defaults/DefaultAdaptableOptions.js → agGrid/defaultAdaptableOptions.js} +72 -9
  144. package/src/agGrid/editors/AdaptableDateEditor/index.js +2 -2
  145. package/src/agGrid/editors/AdaptableNumberEditor/index.js +2 -2
  146. package/src/components/Datepicker/index.d.ts +1 -1
  147. package/src/components/InfiniteTable/index.js +2 -2
  148. package/src/components/Modal/index.d.ts +1 -0
  149. package/src/components/Modal/index.js +6 -4
  150. package/src/env.js +2 -2
  151. package/src/metamodel/adaptable.metamodel.d.ts +9 -9
  152. package/src/metamodel/adaptable.metamodel.js +7 -0
  153. package/src/migration/AdaptableUpgradeHelper.d.ts +38 -0
  154. package/src/migration/AdaptableUpgradeHelper.js +52 -0
  155. package/src/migration/VersionUpgrade.d.ts +8 -0
  156. package/src/migration/VersionUpgrade.js +15 -0
  157. package/src/migration/VersionUpgrade17.d.ts +18 -0
  158. package/src/migration/VersionUpgrade17.js +347 -0
  159. package/src/migration/VersionUpgrade18.d.ts +5 -0
  160. package/src/migration/VersionUpgrade18.js +10 -0
  161. package/src/types.d.ts +5 -4
  162. package/tsconfig.cjs.tsbuildinfo +1 -1
  163. package/src/Utilities/Defaults/DefaultAdaptableOptions.d.ts +0 -2
  164. package/src/Utilities/Services/Interface/IRowEditService.d.ts +0 -3
  165. package/src/Utilities/Services/Interface/IRowEditService.js +0 -2
  166. package/src/agGrid/agGridHelper.d.ts +0 -57
  167. package/src/agGrid/agGridHelper.js +0 -691
  168. package/src/agGrid/agGridMenuHelper.d.ts +0 -46
  169. package/src/agGrid/agGridMenuHelper.js +0 -673
@@ -0,0 +1,3785 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AdaptableAgGrid = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const throttle_1 = tslib_1.__importDefault(require("lodash/throttle"));
6
+ const debounce_1 = tslib_1.__importDefault(require("lodash/debounce"));
7
+ const core_1 = require("ag-grid-community");
8
+ const AdaptableLogger_1 = require("./AdaptableLogger");
9
+ const DocumentationLinkConstants_1 = require("../Utilities/Constants/DocumentationLinkConstants");
10
+ const StringExtensions_1 = tslib_1.__importDefault(require("../Utilities/Extensions/StringExtensions"));
11
+ const Emitter_1 = tslib_1.__importDefault(require("../Utilities/Emitter"));
12
+ const defaultAdaptableOptions_1 = require("./defaultAdaptableOptions");
13
+ const AgGridAdapter_1 = require("./AgGridAdapter");
14
+ const GeneralConstants = tslib_1.__importStar(require("../Utilities/Constants/GeneralConstants"));
15
+ const GeneralConstants_1 = require("../Utilities/Constants/GeneralConstants");
16
+ const DataService_1 = require("../Utilities/Services/DataService");
17
+ const AdaptableStore_1 = require("../Redux/Store/AdaptableStore");
18
+ const AdaptableApiImpl_1 = require("../Api/Implementation/AdaptableApiImpl");
19
+ const Fdc3Service_1 = require("../Utilities/Services/Fdc3Service");
20
+ const CellPopupService_1 = require("../Utilities/Services/CellPopupService");
21
+ const ChartingService_1 = require("../Utilities/Services/ChartingService");
22
+ const ThemeService_1 = require("../Utilities/Services/ThemeService");
23
+ const ValidationService_1 = require("../Utilities/Services/ValidationService");
24
+ const ReportService_1 = require("../Utilities/Services/ReportService");
25
+ const ModuleService_1 = require("../Utilities/Services/ModuleService");
26
+ const CalculatedColumnExpressionService_1 = require("../Utilities/Services/CalculatedColumnExpressionService");
27
+ const EntitlementService_1 = require("../Utilities/Services/EntitlementService");
28
+ const QueryLanguageService_1 = require("../Utilities/Services/QueryLanguageService");
29
+ const AlertService_1 = require("../Utilities/Services/AlertService");
30
+ const TeamSharingService_1 = require("../Utilities/Services/TeamSharingService");
31
+ const MetamodelService_1 = require("../Utilities/Services/MetamodelService");
32
+ const LicenseService_1 = require("../Utilities/Services/LicenseService");
33
+ const Types_1 = require("../PredefinedConfig/Common/Types");
34
+ const ModuleConstants = tslib_1.__importStar(require("../Utilities/Constants/ModuleConstants"));
35
+ const ModuleConstants_1 = require("../Utilities/Constants/ModuleConstants");
36
+ const DashboardModule_1 = require("../Strategy/DashboardModule");
37
+ const AlertModule_1 = require("../Strategy/AlertModule");
38
+ const FlashingCellModule_1 = require("../Strategy/FlashingCellModule");
39
+ const BulkUpdateModule_1 = require("../Strategy/BulkUpdateModule");
40
+ const CalculatedColumnModule_1 = require("../Strategy/CalculatedColumnModule");
41
+ const CellSummaryModule_1 = require("../Strategy/CellSummaryModule");
42
+ const CustomSortModule_1 = require("../Strategy/CustomSortModule");
43
+ const DataChangeHistoryModule_1 = require("../Strategy/DataChangeHistoryModule");
44
+ const DataImportModule_1 = require("../Strategy/DataImportModule");
45
+ const DataSetModule_1 = require("../Strategy/DataSetModule");
46
+ const ExportModule_1 = require("../Strategy/ExportModule");
47
+ const ColumnFilterModule_1 = require("../Strategy/ColumnFilterModule");
48
+ const FormatColumnModule_1 = require("../Strategy/FormatColumnModule");
49
+ const FreeTextColumnModule_1 = require("../Strategy/FreeTextColumnModule");
50
+ const LayoutModule_1 = require("../Strategy/LayoutModule");
51
+ const PlusMinusModule_1 = require("../Strategy/PlusMinusModule");
52
+ const QuickSearchModule_1 = require("../Strategy/QuickSearchModule");
53
+ const ScheduleModule_1 = require("../Strategy/ScheduleModule");
54
+ const SmartEditModule_1 = require("../Strategy/SmartEditModule");
55
+ const ShortcutModule_1 = require("../Strategy/ShortcutModule");
56
+ const StateManagementModule_1 = require("../Strategy/StateManagementModule");
57
+ const TeamSharingModule_1 = require("../Strategy/TeamSharingModule");
58
+ const ToolPanelModule_1 = require("../Strategy/ToolPanelModule");
59
+ const SystemStatusModule_1 = require("../Strategy/SystemStatusModule");
60
+ const ThemeModule_1 = require("../Strategy/ThemeModule");
61
+ const GridInfoModule_1 = require("../Strategy/GridInfoModule");
62
+ const ColumnInfoModule_1 = require("../Strategy/ColumnInfoModule");
63
+ const SettingsPanelModule_1 = require("../Strategy/SettingsPanelModule");
64
+ const StatusBarModule_1 = require("../Strategy/StatusBarModule");
65
+ const ChartingModule_1 = require("../Strategy/ChartingModule");
66
+ const NotesModule_1 = require("../Strategy/NotesModule");
67
+ const StyledColumnModule_1 = require("../Strategy/StyledColumnModule");
68
+ const Fdc3Module_1 = require("../Strategy/Fdc3Module");
69
+ const GridFilterModule_1 = require("../Strategy/GridFilterModule");
70
+ const NamedQueryModule_1 = require("../Strategy/NamedQueryModule");
71
+ const CommentsModule_1 = require("../Strategy/CommentsModule");
72
+ const AdaptableNumberEditor_1 = require("./editors/AdaptableNumberEditor");
73
+ const AdaptableDateEditor_1 = require("./editors/AdaptableDateEditor");
74
+ const Helper_1 = require("../Utilities/Helpers/Helper");
75
+ const uuid_1 = require("../components/utils/uuid");
76
+ const UIHelper_1 = tslib_1.__importDefault(require("../View/UIHelper"));
77
+ const AdaptableToolPanel_1 = require("../View/Components/ToolPanel/AdaptableToolPanel");
78
+ const StatusBarState_1 = require("../PredefinedConfig/StatusBarState");
79
+ const createAgStatusPanelComponent_1 = require("./createAgStatusPanelComponent");
80
+ const AdaptableStatusBar_1 = require("../View/StatusBar/AdaptableStatusBar");
81
+ const ArrayExtensions_1 = tslib_1.__importDefault(require("../Utilities/Extensions/ArrayExtensions"));
82
+ const AgGridMenuAdapter_1 = require("./AgGridMenuAdapter");
83
+ const AdaptableView_1 = require("../View/AdaptableView");
84
+ const renderReactRoot_1 = require("../renderReactRoot");
85
+ const AgGridOptionsService_1 = require("./AgGridOptionsService");
86
+ const DateHelper_1 = require("../Utilities/Helpers/DateHelper");
87
+ const AgGridColumnAdapter_1 = require("./AgGridColumnAdapter");
88
+ const uniqBy_1 = tslib_1.__importDefault(require("lodash/uniqBy"));
89
+ const getScrollbarSize_1 = tslib_1.__importDefault(require("../Utilities/getScrollbarSize"));
90
+ const AggregationColumns_1 = require("../PredefinedConfig/Common/AggregationColumns");
91
+ const isEqual_1 = tslib_1.__importDefault(require("lodash/isEqual"));
92
+ const RowEditService_1 = require("../Utilities/Services/RowEditService");
93
+ const weightedAverage_1 = require("./weightedAverage");
94
+ const sortWithOrder_1 = require("../Utilities/sortWithOrder");
95
+ const Enums_1 = require("../PredefinedConfig/Common/Enums");
96
+ const ObjectFactory_1 = tslib_1.__importDefault(require("../Utilities/ObjectFactory"));
97
+ const EnvVars_1 = require("../EnvVars");
98
+ const AdaptableUpgradeHelper_1 = require("../migration/AdaptableUpgradeHelper");
99
+ const Modal_1 = require("../components/Modal");
100
+ const AdaptableLoadingScreen_1 = require("../View/Components/Popups/AdaptableLoadingScreen");
101
+ const react_1 = require("react");
102
+ const RowNodeProto = core_1.RowNode.prototype;
103
+ const RowNode_dispatchLocalEvent = RowNodeProto.dispatchLocalEvent;
104
+ /**
105
+ * AgGrid does not expose 'cellChanged' and 'dataChanged'
106
+ * so we have to override `dispatchLocalEvent`
107
+ * and hook our own functionality into it
108
+ */
109
+ RowNodeProto.dispatchLocalEvent = function (event) {
110
+ const node = event.node;
111
+ const result = RowNode_dispatchLocalEvent.apply(this, arguments);
112
+ const extractGridApiFromRowNode = (rowNode) => {
113
+ var _a;
114
+ // starting with AG Grid 26.1.0 the gridApi is wrapped in a Beans property
115
+ const rowNodeApi = (_a = rowNode === null || rowNode === void 0 ? void 0 : rowNode.beans) === null || _a === void 0 ? void 0 : _a.gridApi;
116
+ if (!rowNodeApi) {
117
+ AdaptableLogger_1.AdaptableLogger.consoleErrorBase(`No GridAPI found in passed RowNode, this should never happen!`, rowNode);
118
+ }
119
+ return rowNodeApi;
120
+ };
121
+ // we don't know from which instance of aggrid this is coming,
122
+ // as this fn is shared by all instances
123
+ if (node) {
124
+ AdaptableAgGrid.forEachAdaptable((adaptable) => {
125
+ var _a;
126
+ if (extractGridApiFromRowNode(node) !== ((_a = adaptable.agGridAdapter) === null || _a === void 0 ? void 0 : _a.getAgGridApi(true))) {
127
+ // the event is coming from another aggrid instance
128
+ // so IGNORE IT
129
+ return;
130
+ }
131
+ // we're on the correct instance, so do this
132
+ //@ts-ignore
133
+ const fn = adaptable.rowListeners ? adaptable.rowListeners[event.type] : null;
134
+ if (fn) {
135
+ fn(event);
136
+ }
137
+ });
138
+ }
139
+ return result;
140
+ };
141
+ const adaptableInstances = {};
142
+ const publishTimestamp = Number(EnvVars_1.ADAPTABLE_PUBLISH_TIMESTAMP);
143
+ class AdaptableAgGrid {
144
+ constructor() {
145
+ this.columnMinMaxValuesCache = {};
146
+ this.renderReactRoot = (node, container) => (0, renderReactRoot_1.renderReactRoot)(node, container);
147
+ /**
148
+ * Temporary, these are MIGRATION technical debts, and should be removed as soon as possible
149
+ */
150
+ this.adaptableStatusPanelKeys = [];
151
+ // only for our private / internal events used within Adaptable
152
+ // public events are emitted through the EventApi
153
+ this._emit = (eventName, data) => {
154
+ if (this.emitter) {
155
+ return this.emitter.emit(eventName, data);
156
+ }
157
+ };
158
+ this._emitSync = (eventName, data) => {
159
+ if (this.emitter) {
160
+ return this.emitter.emitSync(eventName, data);
161
+ }
162
+ };
163
+ this._on = (eventName, callback) => {
164
+ if (!this.emitter) {
165
+ return () => { };
166
+ }
167
+ return this.emitter.on(eventName, callback);
168
+ };
169
+ this._onIncludeFired = (eventName, callback) => {
170
+ if (!this.emitter) {
171
+ return () => { };
172
+ }
173
+ return this.emitter.onIncludeFired(eventName, callback);
174
+ };
175
+ this.lifecycleState = 'initial';
176
+ this.emitter = new Emitter_1.default();
177
+ this.agGridOptionsService = new AgGridOptionsService_1.AgGridOptionsService(this);
178
+ this.agGridAdapter = new AgGridAdapter_1.AgGridAdapter(this);
179
+ this.agGridMenuAdapter = new AgGridMenuAdapter_1.AgGridMenuAdapter(this);
180
+ this.agGridColumnAdapter = new AgGridColumnAdapter_1.AgGridColumnAdapter(this);
181
+ this.DataService = new DataService_1.DataService(this);
182
+ }
183
+ static forEachAdaptable(fn) {
184
+ Object.keys(adaptableInstances).forEach((key) => {
185
+ fn(adaptableInstances[key]);
186
+ });
187
+ }
188
+ static collectInstance(adaptable, adaptableId) {
189
+ adaptable._id = adaptableId;
190
+ adaptableInstances[adaptable._id] = adaptable;
191
+ }
192
+ static dismissInstance(adaptable) {
193
+ delete adaptableInstances[adaptable._id];
194
+ }
195
+ get isReady() {
196
+ return this.lifecycleState === 'ready';
197
+ }
198
+ get isDestroyed() {
199
+ return this.lifecycleState === 'preDestroyed';
200
+ }
201
+ /**
202
+ * Internal initializer for Adaptable, directly called by the React and Angular Adaptable wrappers
203
+ * @private
204
+ */
205
+ static async _initInternal(config) {
206
+ let promise = null;
207
+ if (Array.isArray(config.adaptableOptions.plugins)) {
208
+ const agGridOptions = {
209
+ gridOptions: config.gridOptions,
210
+ modules: config.modules,
211
+ };
212
+ for (let plugin of config.adaptableOptions.plugins) {
213
+ promise =
214
+ promise && promise.then
215
+ ? promise.then(() => {
216
+ return plugin.beforeInit(config.adaptableOptions, agGridOptions);
217
+ })
218
+ : plugin.beforeInit(config.adaptableOptions, agGridOptions);
219
+ }
220
+ // if gridOptions changed, we need to update the runtimeConfig
221
+ if (agGridOptions.gridOptions !== config.gridOptions) {
222
+ // This allows plugins to modify
223
+ // FIXME AFL MIG: clarify if this is still needed (for NoCode Plugin?)
224
+ // it looks like a code smell, ideally we should get rid of it
225
+ config.gridOptions = agGridOptions.gridOptions;
226
+ }
227
+ }
228
+ const doInit = (adaptableInstance) => {
229
+ return adaptableInstance._initAdaptableAgGrid(config).then((api) => {
230
+ if (Array.isArray(config.adaptableOptions.plugins)) {
231
+ config.adaptableOptions.plugins.forEach((plugin) => {
232
+ plugin.afterInit(adaptableInstance);
233
+ });
234
+ }
235
+ return api;
236
+ });
237
+ };
238
+ if (promise && promise.then) {
239
+ return promise.then(() => {
240
+ const adaptableInstance = new AdaptableAgGrid();
241
+ return doInit(adaptableInstance);
242
+ });
243
+ }
244
+ else {
245
+ const adaptableInstance = new AdaptableAgGrid();
246
+ return doInit(adaptableInstance);
247
+ }
248
+ }
249
+ normaliseLayoutState(state, config) {
250
+ var _a, _b, _c;
251
+ if (this.shouldCreateDefaultLayout(state, this.adaptableOptions)) {
252
+ const defaultLayout = this.createDefaultLayout(state, config.gridOptions.columnDefs);
253
+ const layoutState = state.Layout || {};
254
+ const availableLayouts = layoutState.Layouts || [];
255
+ availableLayouts.push(defaultLayout);
256
+ layoutState.Layouts = availableLayouts;
257
+ layoutState.CurrentLayout = defaultLayout.Name;
258
+ state.Layout = layoutState;
259
+ }
260
+ else {
261
+ const layoutState = state.Layout;
262
+ // ensure CurrentLayout is valid
263
+ if (!layoutState.CurrentLayout ||
264
+ !layoutState.Layouts.find((l) => l.Name === layoutState.CurrentLayout)) {
265
+ layoutState.CurrentLayout = (_b = (_a = layoutState.Layouts) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.Name;
266
+ }
267
+ }
268
+ // for the initial state, we need to dynamically add the ActionRowColumn (if necessary)
269
+ // for subsequent layout changes, the `Adaptable.setLayout()` method handles this
270
+ // this is a serious code smell, hopefully we will delete `setLayout()` at some point
271
+ const actionRowColDefs = this.api.actionRowApi.internalApi.getColDefsForActionRowColumns();
272
+ actionRowColDefs.forEach((actionRowColDef) => {
273
+ const currentLayout = state.Layout.Layouts.find((l) => l.Name === state.Layout.CurrentLayout);
274
+ if (currentLayout && !currentLayout.Columns.includes(actionRowColDef.colId)) {
275
+ currentLayout.Columns.push(actionRowColDef.colId);
276
+ currentLayout.PinnedColumnsMap = currentLayout.PinnedColumnsMap || {};
277
+ currentLayout.PinnedColumnsMap[actionRowColDef.colId] = actionRowColDef.pinned;
278
+ }
279
+ });
280
+ /**
281
+ * Viewport mode does not support a few
282
+ * features instead of complicating the
283
+ * logic where layout is applied, it is easier and
284
+ * less error prone to just remove it.
285
+ */
286
+ if (config.gridOptions.rowModelType === 'viewport') {
287
+ (_c = state.Layout.Layouts) === null || _c === void 0 ? void 0 : _c.forEach((layout) => {
288
+ if (layout.RowGroupedColumns) {
289
+ delete layout.RowGroupedColumns;
290
+ }
291
+ if (layout.AggregationColumns) {
292
+ delete layout.AggregationColumns;
293
+ }
294
+ if (layout.PivotColumns) {
295
+ delete layout.PivotColumns;
296
+ delete layout.EnablePivot;
297
+ }
298
+ });
299
+ }
300
+ return state;
301
+ }
302
+ normaliseToolPanelState(state) {
303
+ var _a, _b, _c;
304
+ if ((_a = state === null || state === void 0 ? void 0 : state.ToolPanel) === null || _a === void 0 ? void 0 : _a.ToolPanels) {
305
+ return state;
306
+ }
307
+ // no predefined config provided, we will display all the panels collapsed (custom & module)
308
+ const defaultToolPanels = [];
309
+ (_c = (_b = this.adaptableOptions.toolPanelOptions) === null || _b === void 0 ? void 0 : _b.customToolPanels) === null || _c === void 0 ? void 0 : _c.forEach((customToolPanel) => defaultToolPanels.push({ Name: customToolPanel.name }));
310
+ Types_1.ALL_TOOL_PANELS.forEach((moduleToolPanel) => defaultToolPanels.push({ Name: moduleToolPanel }));
311
+ const toolPanelState = state.ToolPanel || {};
312
+ toolPanelState.ToolPanels = defaultToolPanels;
313
+ state.ToolPanel = toolPanelState;
314
+ return state;
315
+ }
316
+ async _initAdaptableAgGrid(config) {
317
+ var _a, _b;
318
+ // Phase 1: Preprocess Adaptable Options
319
+ this.lifecycleState = 'preprocessOptions';
320
+ this._rawAdaptableOptions = config.adaptableOptions;
321
+ if (StringExtensions_1.default.IsNullOrEmptyOrWhiteSpace(this._rawAdaptableOptions.adaptableId)) {
322
+ AdaptableLogger_1.AdaptableLogger.consoleErrorBase(`'AdaptableOptions.adaptableId' is a required property and cannot be empty or null`);
323
+ this._rawAdaptableOptions.adaptableId = `AdapTable_${Date.now()}`;
324
+ }
325
+ this.logger = (_a = this.logger) !== null && _a !== void 0 ? _a : new AdaptableLogger_1.AdaptableLogger(this._rawAdaptableOptions.adaptableId);
326
+ const perfInitAdaptableAgGrid = this.logger.beginPerf(`Adaptable._initAdaptableAgGrid()`);
327
+ AdaptableAgGrid.collectInstance(this, this._rawAdaptableOptions.adaptableId);
328
+ this.variant = config.variant;
329
+ this.initWithLazyData =
330
+ config.gridOptions.rowData == undefined || config.gridOptions.rowData.length === 0;
331
+ this.hasAutogeneratedPrimaryKey = !!this._rawAdaptableOptions.autogeneratePrimaryKey;
332
+ this.adaptableOptions = (0, defaultAdaptableOptions_1.applyDefaultAdaptableOptions)(this._rawAdaptableOptions);
333
+ this.adaptableOptions = this.normalizeAdaptableOptions(this.adaptableOptions);
334
+ const { showLoadingScreen, loadingScreenDelay, loadingScreenText, loadingScreenTitle } = this.adaptableOptions.userInterfaceOptions;
335
+ if (showLoadingScreen) {
336
+ const portalElement = (0, Modal_1.ensurePortalElement)();
337
+ if (portalElement) {
338
+ this.unmountLoadingScreen = this.renderReactRoot((0, react_1.createElement)(AdaptableLoadingScreen_1.AdaptableLoadingScreen, {
339
+ showLoadingScreen,
340
+ loadingScreenDelay,
341
+ loadingScreenText,
342
+ loadingScreenTitle,
343
+ }), portalElement);
344
+ }
345
+ }
346
+ this.forPlugins((plugin) => plugin.afterInitOptions(this, this.adaptableOptions));
347
+ this.api = new AdaptableApiImpl_1.AdaptableApiImpl(this);
348
+ this.forPlugins((plugin) => plugin.afterInitApi(this, this.api));
349
+ this.lifecycleState = 'initAdaptableState';
350
+ // just in case Adaptable was destroyed while loading the store (which is an async operation)
351
+ if (this.isDestroyed) {
352
+ return Promise.reject('Adaptable was destroyed while loading the store.');
353
+ // FIXME AFL MIG: is this enough?! talk with the team
354
+ }
355
+ this.initServices();
356
+ this.forPlugins((plugin) => plugin.afterInitServices(this));
357
+ this.adaptableModules = this.initModules();
358
+ this.forPlugins((plugin) => plugin.afterInitModules(this, this.adaptableModules));
359
+ const perfLoadStore = this.logger.beginPerf(`loadStore()`);
360
+ this.adaptableStore = this.initAdaptableStore();
361
+ await this.adaptableStore.loadStore({
362
+ adaptable: this,
363
+ adaptableStateKey: this.adaptableOptions.adaptableStateKey,
364
+ /**
365
+ * This method is called after the store is loaded;
366
+ * it allows to modify the state before it is used by the application
367
+ * e.g. adding default Layout, migrating deprecated state, etc.
368
+ */
369
+ postLoadHook: (state) => {
370
+ if (this.adaptableOptions.autoMigrateState) {
371
+ state = AdaptableUpgradeHelper_1.AdaptableUpgradeHelper.migrateAdaptableState(state, {
372
+ // version 16 actually includes all versions up until 16
373
+ fromVersion: 16,
374
+ logger: this.logger,
375
+ });
376
+ }
377
+ state = this.normaliseLayoutState(state, config);
378
+ state = this.normaliseToolPanelState(state);
379
+ return state;
380
+ },
381
+ });
382
+ perfLoadStore.end();
383
+ // just in case Adaptable was destroyed while loading the store (which is an async operation)
384
+ if (this.isDestroyed) {
385
+ return Promise.reject('Adaptable was destroyed while loading the store.');
386
+ // FIXME AFL MIG: is this enough?! talk with the team
387
+ }
388
+ this.forPlugins((plugin) => plugin.afterInitServices(this));
389
+ this.forPlugins((plugin) => plugin.afterInitModules(this, this.adaptableModules));
390
+ /**
391
+ * At this point it's mandatory to have the ALL the Adaptable blocks initialized:
392
+ * Store, APIs, Services, Modules
393
+ */
394
+ this.lifecycleState = 'setupAgGrid';
395
+ const gridOptions = config.gridOptions;
396
+ // Needed here because special column defs are required for deriving the adaptable column state
397
+ const columnDefs = this.getAllColumnDefinitions(gridOptions.columnDefs || []);
398
+ gridOptions.columnDefs = columnDefs;
399
+ this.setInitialGridOptions(gridOptions, config.variant);
400
+ gridOptions.initialState = this.mapAdaptableStateToAgGridState(this.adaptableStore.TheStore.getState(), gridOptions.columnDefs);
401
+ this.lifecycleState = 'initAgGrid';
402
+ this.agGridAdapter.initialGridOptions = gridOptions;
403
+ const perfInitAgGrid = this.logger.beginPerf(`initAgGrid()`);
404
+ const agGridApi = await this.initializeAgGrid(gridOptions, config.modules, config.renderAgGridFrameworkComponent);
405
+ (_b = this.unmountLoadingScreen) === null || _b === void 0 ? void 0 : _b.call(this);
406
+ perfInitAgGrid.end();
407
+ if (agGridApi === false) {
408
+ this.logger.consoleError(`Adaptable failed to initialize AG Grid!`);
409
+ return Promise.reject('Adaptable failed to initialize AG Grid!');
410
+ }
411
+ this.agGridAdapter.setAgGridApi(agGridApi);
412
+ this.logger.info(`Registered AG Grid modules: `, this.agGridAdapter.getRegisteredModuleNames().sort());
413
+ /**
414
+ * At this point AG Grid is initialized!
415
+ */
416
+ this.updateColumnModelAndRefreshGrid();
417
+ this.api.themeApi.applyCurrentTheme();
418
+ this.validatePrimaryKey();
419
+ this.embedColumnMenu = this.agGridAdapter.isModulePresent(core_1.ModuleNames.MenuModule);
420
+ this.api.internalApi.setTreeMode(this.agGridAdapter.initialGridOptions.treeData);
421
+ // TODO AFL MIG: we could just patch the defautl Layout on init? instead
422
+ this.checkShouldClearExistingFiltersOrSearches();
423
+ this.applyColumnFiltering();
424
+ this.addGridEventListeners();
425
+ this.temporaryAdaptableStateUpdates();
426
+ // do this now so it sets module entitlements
427
+ this.EntitlementService.setModulesEntitlements();
428
+ // create the module menu (for use in the dashboard and the toolpanel)
429
+ // TODO see #create-create-module-menu - make sure it's the same here and there
430
+ this.ModuleService.createModuleMenus();
431
+ // update initial mode of DataChangeHistory
432
+ this.api.internalApi.initializeDataChangeHistory();
433
+ const adaptableContainerElem = this.getAdaptableContainerElement();
434
+ if (adaptableContainerElem != null) {
435
+ adaptableContainerElem.innerHTML = '';
436
+ this.unmountReactRoot = this.renderReactRoot((0, AdaptableView_1.AdaptableApp)({ Adaptable: this }), adaptableContainerElem);
437
+ }
438
+ this.lifecycleState = 'ready';
439
+ this.forPlugins((plugin) => plugin.onAdaptableReady(this, this.adaptableOptions));
440
+ this.api.eventApi.emit('AdaptableReady', {
441
+ adaptableApi: this.api,
442
+ agGridApi: this.agGridAdapter.getAgGridApi(),
443
+ });
444
+ this.api.userInterfaceApi.hideLoadingScreen();
445
+ perfInitAdaptableAgGrid.end();
446
+ return Promise.resolve(this.api);
447
+ }
448
+ applyColumnFiltering() {
449
+ if (this.api.columnFilterApi.isQuickFilterAvailable()) {
450
+ if (this.api.columnFilterApi.isQuickFilterVisible()) {
451
+ this.showQuickFilter();
452
+ }
453
+ else {
454
+ this.hideQuickFilter();
455
+ }
456
+ }
457
+ this.applyGridFiltering();
458
+ this.agGridAdapter.updateColumnFilterActiveState();
459
+ }
460
+ applyGridFiltering() {
461
+ this.agGridAdapter.getAgGridApi().onFilterChanged();
462
+ this._emit('AdapTableFiltersApplied');
463
+ this.refreshSelectedCellsState();
464
+ this.refreshSelectedRowsState();
465
+ }
466
+ // refreshAgGridWithAdaptableState() {
467
+ // this.refreshColDefs();
468
+ // this.api.themeApi.applyCurrentTheme();
469
+ // this.api.internalApi.setTreeMode(this.agGridAdapter.initialGridOptions.treeData);
470
+ // this.checkShouldClearExistingFiltersOrSearches();
471
+ // this.applyColumnFiltering();
472
+ // }
473
+ refreshColDefs() {
474
+ const freshColDefs = this.getAllColumnDefinitions();
475
+ this.agGridAdapter.setGridOption('columnDefs', freshColDefs);
476
+ }
477
+ showQuickFilter() {
478
+ const height = this.api.optionsApi.getColumnFilterOptions().quickFilterOptions.quickFilterHeight;
479
+ this.agGridAdapter.getAgGridApi().setGridOption('floatingFiltersHeight', height);
480
+ }
481
+ hideQuickFilter() {
482
+ this.agGridAdapter.getAgGridApi().setGridOption('floatingFiltersHeight', 0);
483
+ }
484
+ normalizeAdaptableOptions(adaptableOptions) {
485
+ if (this.hasAutogeneratedPrimaryKey) {
486
+ this.logger
487
+ .warn(`Autogenerated primary key (adaptableOptions.autogeneratedPrimaryKey = TRUE) should be used only as a last resort,
488
+ when no unique column is available, as it limits some Adaptable functionalities!
489
+
490
+ For more details see: ${DocumentationLinkConstants_1.PrimaryKeyDocsLink}`);
491
+ this.adaptableOptions.primaryKey = GeneralConstants_1.AUTOGENERATED_PK_COLUMN;
492
+ return this.adaptableOptions;
493
+ }
494
+ if (StringExtensions_1.default.IsNullOrEmpty(adaptableOptions.primaryKey)) {
495
+ this.logger.consoleError(`AdaptableOptions.primaryKey is required and cannot be empty or null!
496
+ As a fallback, you can set adaptableOptions.autogeneratedPrimaryKey = TRUE
497
+
498
+ For more details see: ${DocumentationLinkConstants_1.PrimaryKeyDocsLink}`);
499
+ }
500
+ return adaptableOptions;
501
+ }
502
+ setInitialGridOptions(gridOptions, variant) {
503
+ /**
504
+ * set Adaptable instance on the AG Grid context
505
+ */
506
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'context', (original_context) => {
507
+ const userContext = original_context || {};
508
+ return Object.assign(Object.assign({}, userContext), { __adaptable: this });
509
+ });
510
+ /**
511
+ * `gridId`
512
+ */
513
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'gridId', (original_gridId) => {
514
+ return original_gridId || this.adaptableOptions.adaptableId;
515
+ });
516
+ /**
517
+ * `getRowId`
518
+ */
519
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'getRowId', (original_getRowId) => {
520
+ if (original_getRowId) {
521
+ return original_getRowId;
522
+ }
523
+ const primaryKey = this.adaptableOptions.primaryKey;
524
+ if (StringExtensions_1.default.IsNullOrEmpty(primaryKey)) {
525
+ // if no valid PK then do nothing
526
+ return original_getRowId;
527
+ }
528
+ if (this.hasAutogeneratedPrimaryKey) {
529
+ return (params) => {
530
+ // if the PK value is autogenerated, we need to make sure that the rowData has a valid PK value
531
+ // this should be taken care of in the Adaptable.[loadDataSource/setDataSource/updateRows]() methods, but the users will always make silly decisions
532
+ // so just to be safe we'll check here and add a PK value is missing
533
+ // thus adding a side-effect in a getter, but what can we do against it?! :)
534
+ if (Helper_1.Helper.objectNotExists(params.data[primaryKey])) {
535
+ params.data[primaryKey] = (0, uuid_1.createUuid)();
536
+ }
537
+ return params.data[primaryKey];
538
+ };
539
+ }
540
+ return (params) => {
541
+ var _a;
542
+ if (params.data[primaryKey]) {
543
+ return params.data[primaryKey];
544
+ }
545
+ // row does not have primary key => might be a group row
546
+ const parentKeys = (_a = params.parentKeys) !== null && _a !== void 0 ? _a : [];
547
+ const values = Object.values(params.data);
548
+ if (values.length) {
549
+ const id = [...parentKeys, values[0]].join('/');
550
+ return id;
551
+ }
552
+ };
553
+ });
554
+ /**
555
+ * `suppressAggFuncInHeader`
556
+ */
557
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'suppressAggFuncInHeader', (original_suppressAggFuncInHeader) => {
558
+ const currentLayout = this.api.layoutApi.getCurrentLayout();
559
+ if (!currentLayout) {
560
+ return original_suppressAggFuncInHeader;
561
+ }
562
+ return currentLayout.SuppressAggFuncInHeader;
563
+ });
564
+ /**
565
+ * `aggFuncs`
566
+ */
567
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'aggFuncs', (original_aggFuncs) => {
568
+ const aggregationFunctions = original_aggFuncs || {};
569
+ aggregationFunctions[AggregationColumns_1.WEIGHTED_AVERAGE_AGG_FN_NAME] = (params) => {
570
+ const columnId = params.column.getColId();
571
+ const adaptableAggFunc = this.getActiveAdaptableAggFuncForCol(columnId);
572
+ if (!adaptableAggFunc) {
573
+ return undefined;
574
+ }
575
+ if (adaptableAggFunc.type === 'weightedAverage') {
576
+ return (0, weightedAverage_1.weightedAverage)(params, params.colDef.colId, adaptableAggFunc.weightedColumnId);
577
+ }
578
+ return undefined;
579
+ };
580
+ return aggregationFunctions;
581
+ });
582
+ /**
583
+ * `allowContextMenuWithControlKey`
584
+ */
585
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'allowContextMenuWithControlKey', (original_allowContextMenuWithControlKey) => {
586
+ return original_allowContextMenuWithControlKey === undefined
587
+ ? true
588
+ : original_allowContextMenuWithControlKey;
589
+ });
590
+ /**
591
+ * `isExternalFilterPresent`
592
+ */
593
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'isExternalFilterPresent', (original_isExternalFilterPresent) => {
594
+ return (params) => {
595
+ if (this.isDestroyed) {
596
+ return true;
597
+ }
598
+ const columnFilters = this.api.columnFilterApi.getActiveColumnFilters();
599
+ const isColumnFiltersActive = ArrayExtensions_1.default.IsNotNullOrEmpty(columnFilters);
600
+ const isGridFilterActive = StringExtensions_1.default.IsNotNullOrEmpty(this.api.gridFilterApi.getCurrentGridFilterExpression());
601
+ return (isColumnFiltersActive ||
602
+ isGridFilterActive ||
603
+ // it means that userPropertyValue will be called so we re-init that collection
604
+ (original_isExternalFilterPresent ? original_isExternalFilterPresent(params) : false));
605
+ };
606
+ });
607
+ /**
608
+ * `doesExternalFilterPass`
609
+ */
610
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'doesExternalFilterPass', (original_doesExternalFilterPass) => {
611
+ return (node) => {
612
+ if (this.isDestroyed) {
613
+ return true;
614
+ }
615
+ // first we assess a Grid Filter (if its running locally)
616
+ if (!this.isGroupRowNode(node)) {
617
+ const currentGridFilter = this.api.gridFilterApi.getCurrentGridFilterExpression();
618
+ if (currentGridFilter) {
619
+ const evaluateGridFilterOnClient = this.api.expressionApi.internalApi.evaluateExpressionInAdaptableQL('GridFilter', undefined, currentGridFilter);
620
+ if (evaluateGridFilterOnClient) {
621
+ const isCurrentGridFilterValid = this.api.expressionApi.isValidBooleanExpression(currentGridFilter, ModuleConstants_1.GridFilterModuleId, `Invalid Grid Filter '${currentGridFilter}'`);
622
+ if (!isCurrentGridFilterValid ||
623
+ !this.api.internalApi
624
+ .getQueryLanguageService()
625
+ .evaluateBooleanExpression(currentGridFilter, ModuleConstants_1.GridFilterModuleId, node)) {
626
+ return false;
627
+ }
628
+ }
629
+ }
630
+ }
631
+ const columnFilters = this.api.columnFilterApi.getActiveColumnFilters();
632
+ try {
633
+ if (columnFilters.length > 0) {
634
+ for (const columnFilter of columnFilters) {
635
+ const evaluateFilterOnClient = this.api.expressionApi.internalApi.evaluatePredicatesInAdaptableQL('ColumnFilter', columnFilter, [columnFilter.Predicate]);
636
+ if (evaluateFilterOnClient) {
637
+ // we then assess filters (if running locally)
638
+ if (!this.api.columnFilterApi.internalApi.evaluateColumnFilter(columnFilter, node)) {
639
+ return false;
640
+ }
641
+ }
642
+ }
643
+ }
644
+ }
645
+ catch (ex) {
646
+ this.logger.error(ex);
647
+ return false;
648
+ }
649
+ return original_doesExternalFilterPass ? original_doesExternalFilterPass(node) : true;
650
+ };
651
+ });
652
+ /**
653
+ * `getMainMenuItems`
654
+ */
655
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'getMainMenuItems', (original_getMainMenuItems) => {
656
+ return (params) => {
657
+ // couldnt find a way to listen for menu close. There is a Menu Item Select, but you can also close menu from filter and clicking outside menu....
658
+ return this.agGridMenuAdapter.buildColumnMenu(params, original_getMainMenuItems);
659
+ };
660
+ });
661
+ /**
662
+ * `getContextMenuItems`
663
+ */
664
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'getContextMenuItems', (original_getContextMenuItems) => {
665
+ return (params) => {
666
+ return this.agGridMenuAdapter.buildContextMenu(params, original_getContextMenuItems);
667
+ };
668
+ });
669
+ /**
670
+ * `initialGroupOrderComparator
671
+ */
672
+ // Build the default group sort comparator - will get custom sort values (but not functions) in real time
673
+ // TODO: if a custom 'aggFunc' property is defined (see setupColumnAggFunc()), it won't be evaluated
674
+ if (this.adaptableOptions.groupingOptions.autoOrderGroupedColumns) {
675
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'initialGroupOrderComparator', (original_initialGroupOrderComparator) => {
676
+ if (original_initialGroupOrderComparator) {
677
+ return original_initialGroupOrderComparator;
678
+ }
679
+ return (params) => {
680
+ const { nodeA, nodeB } = params;
681
+ const firstGroupedColumnId = this.agGridAdapter.getFirstGroupedColumn();
682
+ if (firstGroupedColumnId) {
683
+ const definedColumnComparator = this.api.columnApi.internalApi.getActiveColumnComparator(firstGroupedColumnId, this.api.customSortApi.getCustomSortForColumn(firstGroupedColumnId), this.api.customSortApi.internalApi.getCustomSortComparer(firstGroupedColumnId));
684
+ if (definedColumnComparator) {
685
+ return definedColumnComparator(nodeA.key, nodeB.key);
686
+ }
687
+ const sortOder = this.api.layoutApi.getCurrentLayoutColumnSort(firstGroupedColumnId);
688
+ if (sortOder === 'Desc') {
689
+ return nodeA.key > nodeB.key ? -1 : 1;
690
+ }
691
+ }
692
+ // if no comparator available, just sort alphanumerically
693
+ if (nodeA.key == nodeB.key) {
694
+ return 0;
695
+ }
696
+ return nodeA.key < nodeB.key ? -1 : 1;
697
+ };
698
+ });
699
+ }
700
+ /**
701
+ * `components`
702
+ */
703
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'components', (original_components) => {
704
+ const AdaptableToolPanel = (0, AdaptableToolPanel_1.getAdaptableToolPanelAgGridComponent)(this);
705
+ const components = original_components || {};
706
+ const adaptableComponents = Object.assign(Object.assign({}, components), { AdaptableToolPanel });
707
+ return adaptableComponents;
708
+ });
709
+ if (variant === 'react') {
710
+ // TODO very soon we have to transition to reactiveCustomComponents in React
711
+ // but for now, if we simply set it to true, it will break our editors, etc
712
+ // this.agGridOptionsService.setGridOptionsProperty(
713
+ // gridOptions,
714
+ // 'reactiveCustomComponents',
715
+ // () => true
716
+ // );
717
+ }
718
+ /**
719
+ * `sidebar`
720
+ */
721
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'sideBar', (original_sideBar) => {
722
+ var _a, _b;
723
+ if (!original_sideBar) {
724
+ // lucky us, no sideBar is defined, so we don't have to do anything
725
+ return original_sideBar;
726
+ }
727
+ const isAdaptableToolPanelHidden = this.EntitlementService.isModuleHiddenEntitlement('ToolPanel');
728
+ const adaptableToolPanelDef = {
729
+ id: GeneralConstants.ADAPTABLE_TOOLPANEL_ID,
730
+ toolPanel: GeneralConstants.ADAPTABLE_TOOLPANEL_COMPONENT,
731
+ labelDefault: GeneralConstants.ADAPTABLE,
732
+ labelKey: 'adaptable',
733
+ iconKey: 'menu',
734
+ width: UIHelper_1.default.getAdaptableToolPanelWidth(),
735
+ minWidth: UIHelper_1.default.getAdaptableToolPanelWidth(),
736
+ // maxWidth = undefined,
737
+ };
738
+ const mapToolPanelDefs = (toolPanelDefs = []) => {
739
+ // if it's an alias for the adaptable tool panel, map it to a ToolPanelDef, otherwise return it as it is
740
+ return toolPanelDefs.map((toolPanelDef) => toolPanelDef === GeneralConstants.ADAPTABLE_TOOLPANEL_ID
741
+ ? adaptableToolPanelDef
742
+ : toolPanelDef);
743
+ };
744
+ const isSideBarDefObject = (sidebarDef) => {
745
+ return Array.isArray(sidebarDef === null || sidebarDef === void 0 ? void 0 : sidebarDef.toolPanels);
746
+ };
747
+ let result;
748
+ if (original_sideBar === true) {
749
+ // create all tool panels with default settings
750
+ const toolPanels = [];
751
+ toolPanels.push(GeneralConstants.AGGRID_TOOLPANEL_FILTERS);
752
+ toolPanels.push(GeneralConstants.AGGRID_TOOLPANEL_COLUMNS);
753
+ if (!isAdaptableToolPanelHidden) {
754
+ toolPanels.push(adaptableToolPanelDef);
755
+ }
756
+ result = {
757
+ toolPanels: toolPanels,
758
+ };
759
+ }
760
+ // if there is only one tool panel, and it's the adaptable one => we have to handle it
761
+ else if (typeof original_sideBar === 'string') {
762
+ if (gridOptions.sideBar === GeneralConstants.ADAPTABLE_TOOLPANEL_ID) {
763
+ if (!isAdaptableToolPanelHidden)
764
+ result = {
765
+ toolPanels: [adaptableToolPanelDef],
766
+ };
767
+ }
768
+ else {
769
+ result = original_sideBar;
770
+ }
771
+ }
772
+ // if it's an array, process the tool panel definitions
773
+ else if (Array.isArray(original_sideBar)) {
774
+ if (!original_sideBar.includes(GeneralConstants.ADAPTABLE_TOOLPANEL_ID) ||
775
+ isAdaptableToolPanelHidden) {
776
+ result = original_sideBar;
777
+ }
778
+ // if it's an array, process the tool panel definitions
779
+ const sidebarDef = {};
780
+ sidebarDef.toolPanels = mapToolPanelDefs(original_sideBar);
781
+ result = sidebarDef;
782
+ }
783
+ // if it's fully-fledged SideBarDef, process its tool panel definitions
784
+ else if (isSideBarDefObject(original_sideBar)) {
785
+ if ((_a = original_sideBar.toolPanels) === null || _a === void 0 ? void 0 : _a.some((toolpanelDef) => typeof toolpanelDef !== 'string' &&
786
+ toolpanelDef.id === GeneralConstants.ADAPTABLE_TOOLPANEL_ID &&
787
+ !isAdaptableToolPanelHidden)) {
788
+ // if there is an Adaptable SideBarDef, don't touch it as it may contain user-defined properties
789
+ result = original_sideBar;
790
+ }
791
+ else {
792
+ result = Object.assign(Object.assign({}, original_sideBar), { toolPanels: mapToolPanelDefs(original_sideBar.toolPanels) });
793
+ }
794
+ }
795
+ this.hasAdaptableToolPanel =
796
+ isSideBarDefObject(result) &&
797
+ ((_b = result.toolPanels) === null || _b === void 0 ? void 0 : _b.some((toolPanelDef) => typeof toolPanelDef !== 'string' &&
798
+ toolPanelDef.id === GeneralConstants.ADAPTABLE_TOOLPANEL_ID));
799
+ return result;
800
+ });
801
+ /**
802
+ * `statusBar`
803
+ */
804
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'statusBar', (original_statusBar) => {
805
+ var _a, _b;
806
+ const statusPanels = (_b = ((_a = original_statusBar === null || original_statusBar === void 0 ? void 0 : original_statusBar.statusPanels) !== null && _a !== void 0 ? _a : [])) === null || _b === void 0 ? void 0 : _b.map((statusPanel) => {
807
+ if (statusPanel.statusPanel === StatusBarState_1.ADAPTABLE_STATUS_PANEL) {
808
+ this.adaptableStatusPanelKeys.push(statusPanel.key);
809
+ const context = {
810
+ Key: statusPanel.key,
811
+ };
812
+ return Object.assign(Object.assign({}, statusPanel), { statusPanel: (0, createAgStatusPanelComponent_1.createAgStatusPanelComponent)(AdaptableStatusBar_1.AdaptableStatusBar, this, context) });
813
+ }
814
+ return statusPanel;
815
+ });
816
+ return Object.assign(Object.assign({}, original_statusBar), { statusPanels });
817
+ });
818
+ /**
819
+ * `getRowStyle`
820
+ */
821
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'getRowStyle', (original_getRowStyle) => {
822
+ return (params) => {
823
+ const result = Object.assign(Object.assign(Object.assign({}, original_getRowStyle === null || original_getRowStyle === void 0 ? void 0 : original_getRowStyle(params)), this.api.gridApi.internalApi.getRowHighlightStyle(params)), this.api.gridApi.internalApi.getAlertRowStyle(params));
824
+ return result;
825
+ };
826
+ });
827
+ /**
828
+ * `getRowClass`
829
+ */
830
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'getRowClass', (original_getRowClass) => {
831
+ return (params) => {
832
+ const alertHighlightClassName = this.api.gridApi.internalApi.getAlertRowClass(params);
833
+ const highlightClassName = this.api.gridApi.internalApi.getRowHighlightClass(params);
834
+ const returnValue = [
835
+ typeof original_getRowClass === 'function'
836
+ ? original_getRowClass(params)
837
+ : original_getRowClass,
838
+ highlightClassName,
839
+ alertHighlightClassName,
840
+ ]
841
+ // we flatten it because 'original_getRowClass' might return a string[]
842
+ .flat()
843
+ .filter((x) => !!x);
844
+ return (returnValue === null || returnValue === void 0 ? void 0 : returnValue.length) ? returnValue : undefined;
845
+ };
846
+ });
847
+ /**
848
+ * `columnTypes`
849
+ */
850
+ // this will have to go/be heavily extended with https://github.com/AdaptableTools/adaptable/issues/2230
851
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'columnTypes', (original_columnTypes) => {
852
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
853
+ const providedColumnTypes = original_columnTypes || {};
854
+ const gridOptionsColumnTypes = gridOptions.columnTypes || {};
855
+ const patchedColumnTypes = Object.assign(providedColumnTypes, {
856
+ [GeneralConstants_1.AB_SPECIAL_COLUMN]: {},
857
+ [GeneralConstants_1.AB_FDC3_COLUMN]: {},
858
+ abColDefNumber: (_a = gridOptionsColumnTypes.abColDefNumber) !== null && _a !== void 0 ? _a : {},
859
+ abColDefString: (_b = gridOptionsColumnTypes.abColDefString) !== null && _b !== void 0 ? _b : {},
860
+ abColDefBoolean: (_c = gridOptionsColumnTypes.abColDefBoolean) !== null && _c !== void 0 ? _c : {},
861
+ abColDefDate: (_d = gridOptionsColumnTypes.abColDefDate) !== null && _d !== void 0 ? _d : {},
862
+ abColDefObject: (_e = gridOptionsColumnTypes.abColDefObject) !== null && _e !== void 0 ? _e : {},
863
+ abColDefCustom: (_f = gridOptionsColumnTypes.abColDefCustom) !== null && _f !== void 0 ? _f : {},
864
+ abColDefStringArray: (_g = gridOptionsColumnTypes.abColDefStringArray) !== null && _g !== void 0 ? _g : {},
865
+ abColDefNumberArray: (_h = gridOptionsColumnTypes.abColDefNumberArray) !== null && _h !== void 0 ? _h : {},
866
+ abColDefTupleNumberArray: (_j = gridOptionsColumnTypes.abColDefTupleNumberArray) !== null && _j !== void 0 ? _j : {},
867
+ abColDefObjectNumberArray: (_k = gridOptionsColumnTypes.abColDefObjectNumberArray) !== null && _k !== void 0 ? _k : {},
868
+ });
869
+ if (patchedColumnTypes.abColDefNumber.cellEditor == undefined) {
870
+ patchedColumnTypes.abColDefNumber.cellEditor =
871
+ this.variant === 'react' ? AdaptableNumberEditor_1.ReactAdaptableNumberEditor : AdaptableNumberEditor_1.AdaptableNumberEditor;
872
+ }
873
+ if (patchedColumnTypes.abColDefDate.cellEditor == undefined) {
874
+ patchedColumnTypes.abColDefDate.cellEditor =
875
+ this.variant === 'react' ? AdaptableDateEditor_1.ReactAdaptableDateEditor : AdaptableDateEditor_1.AdaptableDateEditor;
876
+ }
877
+ return patchedColumnTypes;
878
+ });
879
+ /**
880
+ * `dataTypeDefinitions`
881
+ */
882
+ this.agGridOptionsService.setGridOptionsProperty(gridOptions, 'dataTypeDefinitions', () => {
883
+ // temporary workaround until https://github.com/AdaptableTools/adaptable/issues/2230
884
+ const revertedDateTypeDefinitions = {
885
+ date: {
886
+ baseDataType: 'date',
887
+ extendsDataType: 'date',
888
+ valueParser: null,
889
+ valueFormatter: null,
890
+ suppressDefaultProperties: true,
891
+ },
892
+ dateString: {
893
+ baseDataType: 'dateString',
894
+ extendsDataType: 'dateString',
895
+ valueParser: null,
896
+ valueFormatter: null,
897
+ suppressDefaultProperties: true,
898
+ },
899
+ };
900
+ return revertedDateTypeDefinitions;
901
+ });
902
+ }
903
+ /**
904
+ * Either initializes the AG Grid instance or delegates it to the framework wrappers (React/Anglar)
905
+ */
906
+ async initializeAgGrid(gridOptions, modules, renderAgGridFrameworkComponent) {
907
+ if (renderAgGridFrameworkComponent) {
908
+ const result = await renderAgGridFrameworkComponent(gridOptions);
909
+ if (result === false) {
910
+ return false;
911
+ }
912
+ const agGridApi = result;
913
+ // framework wrapper may pass the rowData as a prop
914
+ const rowData = agGridApi.getGridOption('rowData');
915
+ this.initWithLazyData = rowData == undefined || rowData.length === 0;
916
+ this.logger.info('initWithLazyData = TRUE');
917
+ if (!this.getAgGridContainerElement()) {
918
+ // initialize the agGridContainerElement from the AgGrid instance
919
+ // @ts-ignore
920
+ const gridRoot = agGridApi.ctrlsService.gridBodyCtrl.eGridBody;
921
+ const gridContainer = gridRoot === null || gridRoot === void 0 ? void 0 : gridRoot.closest('[class*="ag-theme"]');
922
+ if (!gridContainer) {
923
+ this.logger.consoleError('No AG Grid container element found in the DOM. Please provide a valid container element in `ContainerOptions.agGridContainer`');
924
+ }
925
+ this.DANGER_USE_GETTER_agGridContainerElement = gridContainer;
926
+ }
927
+ return agGridApi;
928
+ }
929
+ const agGridContainer = this.getAgGridContainerElement();
930
+ if (!agGridContainer) {
931
+ this.logger.consoleError('No AG Grid container element found in the DOM. Please provide a valid container element in `ContainerOptions.agGridContainer`');
932
+ return Promise.resolve(false);
933
+ }
934
+ let gridParams;
935
+ if (modules === null || modules === void 0 ? void 0 : modules.length) {
936
+ gridParams = { modules };
937
+ }
938
+ const agGridApi = (0, core_1.createGrid)(agGridContainer, gridOptions, gridParams);
939
+ return agGridApi;
940
+ }
941
+ getAllColumnDefinitions(agGridColDefs) {
942
+ const allColDefs = this.enhanceColDefsWithSpecialColumns(agGridColDefs !== null && agGridColDefs !== void 0 ? agGridColDefs : this.agGridAdapter.getAgGridApi().getColumnDefs());
943
+ this.agGridAdapter.assignColumnIdsToColDefs(allColDefs);
944
+ return allColDefs;
945
+ }
946
+ getSpecialColDefs() {
947
+ return [
948
+ ...this.api.calculatedColumnApi.internalApi.getColDefsForCalculatedColumns(),
949
+ ...this.api.actionColumnApi.getColDefsForActionColumns(),
950
+ ...this.api.freeTextColumnApi.internalApi.getColDefsForFreeTextColumns(),
951
+ ...this.api.actionRowApi.internalApi.getColDefsForActionRowColumns(),
952
+ ...this.api.fdc3Api.internalApi.getFdc3ActionColDefs(),
953
+ ];
954
+ }
955
+ enhanceColDefsWithSpecialColumns(agGridColDefs) {
956
+ const specialColDefs = this.getSpecialColDefs();
957
+ const isSpecialColDef = (colDef) => {
958
+ const { type } = colDef;
959
+ if (type === GeneralConstants_1.AB_SPECIAL_COLUMN || (Array.isArray(type) && type.includes(GeneralConstants_1.AB_SPECIAL_COLUMN))) {
960
+ return true;
961
+ }
962
+ return false;
963
+ };
964
+ const isColGroupDef = (columnDefinition) => {
965
+ // @ts-ignore
966
+ return columnDefinition['children'] != null;
967
+ };
968
+ const processedSpecialColDefIds = [];
969
+ const mapColDefs = (colDefs) => {
970
+ return colDefs.map((colDef) => {
971
+ if (isColGroupDef(colDef)) {
972
+ // if it's a group column, recursively map its children
973
+ colDef.children = mapColDefs(colDef.children);
974
+ return colDef;
975
+ }
976
+ else {
977
+ if (!isSpecialColDef(colDef)) {
978
+ // if it's not a special column, return it as is
979
+ return colDef;
980
+ }
981
+ const newlyCreatedSpecialColDef = specialColDefs.find((specialColDef) => specialColDef.colId === colDef.colId);
982
+ if (newlyCreatedSpecialColDef) {
983
+ // if it's a special column and we have a special col def for it, return the special col def
984
+ processedSpecialColDefIds.push(colDef.colId);
985
+ // merge the user defined colDef with the special col def
986
+ // this way the user may provide some custom settings for the special col def (tooltip, etc)
987
+ const mergedColDef = Object.assign(Object.assign({}, colDef), newlyCreatedSpecialColDef);
988
+ return mergedColDef;
989
+ }
990
+ else {
991
+ // otherwise, return the original col def
992
+ return colDef;
993
+ }
994
+ }
995
+ });
996
+ };
997
+ let resultColDefs = mapColDefs(agGridColDefs);
998
+ // check if there are any special colDefs that were not processed
999
+ // in that case, add them to the end of the colDefs
1000
+ specialColDefs.forEach((specialColDef) => {
1001
+ if (!processedSpecialColDefIds.includes(specialColDef.colId)) {
1002
+ resultColDefs.push(specialColDef);
1003
+ }
1004
+ });
1005
+ // remove special column that are no longer defined
1006
+ resultColDefs = resultColDefs.filter((colDef) => {
1007
+ if (isSpecialColDef(colDef)) {
1008
+ // must be in specialColDefs
1009
+ return specialColDefs.some((specialColDef) => specialColDef.colId === colDef.colId);
1010
+ }
1011
+ return true;
1012
+ });
1013
+ return resultColDefs;
1014
+ }
1015
+ useRowNodeLookUp() {
1016
+ return this.agGridAdapter.initialGridOptions.getRowId != undefined;
1017
+ }
1018
+ getAgGridContainerElement() {
1019
+ if (!this.DANGER_USE_GETTER_agGridContainerElement) {
1020
+ this.DANGER_USE_GETTER_agGridContainerElement =
1021
+ typeof this.adaptableOptions.containerOptions.agGridContainer === 'string'
1022
+ ? document.getElementById(this.adaptableOptions.containerOptions.agGridContainer)
1023
+ : this.adaptableOptions.containerOptions.agGridContainer;
1024
+ }
1025
+ return this.DANGER_USE_GETTER_agGridContainerElement;
1026
+ }
1027
+ getAdaptableContainerElement() {
1028
+ if (!this.DANGER_USE_GETTER_adaptableContainerElement) {
1029
+ this.DANGER_USE_GETTER_adaptableContainerElement =
1030
+ typeof this.adaptableOptions.containerOptions.adaptableContainer === 'string'
1031
+ ? document.getElementById(this.adaptableOptions.containerOptions.adaptableContainer)
1032
+ : this.adaptableOptions.containerOptions.adaptableContainer;
1033
+ }
1034
+ return this.DANGER_USE_GETTER_adaptableContainerElement;
1035
+ }
1036
+ // This method returns selected cells ONLY (if selection mode is cells or multiple cells).
1037
+ // If the selection mode is row it will returns nothing - use the setSelectedRows() method
1038
+ refreshSelectedCellsState() {
1039
+ var _a;
1040
+ const isRangeSelectionModuleRegistered = this.agGridAdapter.isModulePresent(core_1.ModuleNames.RangeSelectionModule);
1041
+ if (!isRangeSelectionModuleRegistered ||
1042
+ !((_a = this.agGridAdapter.getLiveGridOptions()) === null || _a === void 0 ? void 0 : _a.enableRangeSelection) === true) {
1043
+ return;
1044
+ }
1045
+ const selectedCellInfo = this.agGridAdapter.deriveSelectedCellInfoFromAgGrid();
1046
+ this.api.gridApi.internalApi.setSelectedCells(selectedCellInfo);
1047
+ this._emit('CellsSelected');
1048
+ let cellSelectionChangedInfo = Object.assign(Object.assign({}, this.api.internalApi.buildBaseContext()), { selectedCellInfo: this.api.gridApi.getGridState().SelectedCellInfo });
1049
+ this.api.eventApi.emit('CellSelectionChanged', cellSelectionChangedInfo);
1050
+ return selectedCellInfo;
1051
+ }
1052
+ refreshSelectedRowsState() {
1053
+ if (!this.isGridSelectable()) {
1054
+ return undefined;
1055
+ }
1056
+ const selectedRowInfo = this.agGridAdapter.deriveSelectedRowInfoFromAgGrid();
1057
+ this.api.gridApi.internalApi.setSelectedRows(selectedRowInfo);
1058
+ const rowSelectionChangedInfo = Object.assign(Object.assign({}, this.api.internalApi.buildBaseContext()), { selectedRowInfo: this.api.gridApi.getGridState().SelectedRowInfo });
1059
+ this.api.eventApi.emit('RowSelectionChanged', rowSelectionChangedInfo);
1060
+ return selectedRowInfo;
1061
+ }
1062
+ isGridSelectable() {
1063
+ return (this.agGridAdapter.initialGridOptions.rowSelection === 'single' ||
1064
+ this.agGridAdapter.initialGridOptions.rowSelection === 'multiple');
1065
+ }
1066
+ initAdaptableStore() {
1067
+ const perfNewAdaptableStore = this.logger.beginPerf(`initAdaptableStore()`);
1068
+ const adaptableStore = new AdaptableStore_1.AdaptableStore(this);
1069
+ adaptableStore.onAny((eventName, data) => {
1070
+ this.performAudit(data.action, data.state, data.newState);
1071
+ this.forPlugins((plugin) => plugin.onStoreEvent(eventName, data, this.adaptableStore));
1072
+ });
1073
+ perfNewAdaptableStore.end();
1074
+ return adaptableStore;
1075
+ }
1076
+ mapAdaptableStateToAgGridState(adaptableState, agGridColDefs) {
1077
+ var _a, _b, _c;
1078
+ const agGridState = {};
1079
+ const currentLayoutName = (_a = adaptableState.Layout) === null || _a === void 0 ? void 0 : _a.CurrentLayout;
1080
+ const currentLayout = currentLayoutName &&
1081
+ ((_c = (_b = adaptableState.Layout) === null || _b === void 0 ? void 0 : _b.Layouts) === null || _c === void 0 ? void 0 : _c.find((l) => l.Name === currentLayoutName));
1082
+ if (!currentLayout) {
1083
+ return agGridState;
1084
+ }
1085
+ const allAgGridColDefIds = agGridColDefs.map((colDef) => colDef.colId);
1086
+ const getColDef = (colId) => agGridColDefs.find((colDef) => colDef.colId == colId);
1087
+ agGridState.columnVisibility = {
1088
+ hiddenColIds: allAgGridColDefIds.filter((colDefId) => { var _a; return !((_a = currentLayout.Columns) === null || _a === void 0 ? void 0 : _a.includes(colDefId)); }),
1089
+ };
1090
+ agGridState.columnOrder = {
1091
+ orderedColIds: (0, sortWithOrder_1.sortWithOrderArray)(allAgGridColDefIds, currentLayout.Columns || [], {
1092
+ sortUnorderedItems: false,
1093
+ }),
1094
+ };
1095
+ if (currentLayout.ColumnWidthMap) {
1096
+ agGridState.columnSizing = {
1097
+ columnSizingModel: Object.keys(currentLayout.ColumnWidthMap).map((colId) => {
1098
+ const width = currentLayout.ColumnWidthMap[colId];
1099
+ return {
1100
+ colId,
1101
+ width,
1102
+ };
1103
+ }),
1104
+ };
1105
+ }
1106
+ if (currentLayout.ColumnSorts) {
1107
+ agGridState.sort = {
1108
+ sortModel: currentLayout.ColumnSorts.map((columnSort) => {
1109
+ return {
1110
+ colId: columnSort.ColumnId,
1111
+ sort: columnSort.SortOrder === 'Asc' ? 'asc' : 'desc',
1112
+ };
1113
+ }),
1114
+ };
1115
+ }
1116
+ if (currentLayout.RowGroupedColumns) {
1117
+ agGridState.rowGroup = {
1118
+ groupColIds: currentLayout.RowGroupedColumns,
1119
+ };
1120
+ }
1121
+ if (currentLayout.AggregationColumns) {
1122
+ agGridState.aggregation = {
1123
+ aggregationModel: Object.keys(currentLayout.AggregationColumns).map((colId) => {
1124
+ let aggFunc = currentLayout.AggregationColumns[colId];
1125
+ if (aggFunc === true) {
1126
+ const colDef = getColDef(colId);
1127
+ // fallback to SUM if no defaultAggFunc is defined
1128
+ aggFunc = (colDef === null || colDef === void 0 ? void 0 : colDef.defaultAggFunc) || 'sum';
1129
+ }
1130
+ if ((0, AggregationColumns_1.isWeightedAverageAggregation)(aggFunc)) {
1131
+ aggFunc = AggregationColumns_1.WEIGHTED_AVERAGE_AGG_FN_NAME;
1132
+ }
1133
+ return {
1134
+ colId,
1135
+ aggFunc,
1136
+ };
1137
+ }),
1138
+ };
1139
+ }
1140
+ if (currentLayout.PivotColumns || currentLayout.EnablePivot) {
1141
+ agGridState.pivot = {
1142
+ pivotMode: currentLayout.EnablePivot,
1143
+ pivotColIds: currentLayout.PivotColumns || [],
1144
+ };
1145
+ }
1146
+ if (currentLayout.PinnedColumnsMap) {
1147
+ const columnPinning = {
1148
+ leftColIds: [],
1149
+ rightColIds: [],
1150
+ };
1151
+ Object.keys(currentLayout.PinnedColumnsMap).forEach((colId) => {
1152
+ const pinned = currentLayout.PinnedColumnsMap[colId];
1153
+ if (pinned === 'left') {
1154
+ columnPinning.leftColIds.push(colId);
1155
+ }
1156
+ else if (pinned === 'right') {
1157
+ columnPinning.rightColIds.push(colId);
1158
+ }
1159
+ });
1160
+ agGridState.columnPinning = columnPinning;
1161
+ }
1162
+ return agGridState;
1163
+ }
1164
+ addGridEventListeners() {
1165
+ /**
1166
+ * Intercept DOM events and emit them as Adaptable events
1167
+ */
1168
+ const gridContainerElement = this.getAgGridContainerElement();
1169
+ if (gridContainerElement) {
1170
+ gridContainerElement.addEventListener('keydown', (this.agGridListenerKeydown = (event) => this._emit('KeyDown', event)),
1171
+ // This is needed to be able to prevent the editor to be opened
1172
+ // in bubling phase the opening is not prevented with ag-grid v30
1173
+ true);
1174
+ gridContainerElement.addEventListener('mouseenter', (this.agGridListenerMouseEnter = (event) => {
1175
+ this._emit('MouseEnter', event);
1176
+ }), true);
1177
+ gridContainerElement.addEventListener('mouseleave', (this.agGridListenerMouseLeave = (event) => this._emit('MouseLeave', event)));
1178
+ }
1179
+ this.throttleFilterOnEditDataChange = (0, throttle_1.default)(
1180
+ // the extra function is to make sure we have a reference to ag-grid-api
1181
+ () => { var _a; return (_a = this.agGridAdapter.getAgGridApi()) === null || _a === void 0 ? void 0 : _a.onFilterChanged(); }, this.adaptableOptions.columnFilterOptions.filterActionOnUserDataChange.throttleDelay, {
1182
+ trailing: true,
1183
+ leading: false,
1184
+ });
1185
+ this.throttleFilterOnTickingDataChange = (0, throttle_1.default)(() => { var _a; return (_a = this.agGridAdapter.getAgGridApi()) === null || _a === void 0 ? void 0 : _a.onFilterChanged(); }, this.adaptableOptions.columnFilterOptions.filterActionOnExternalDataChange.throttleDelay, {
1186
+ trailing: true,
1187
+ leading: false,
1188
+ });
1189
+ /**
1190
+ * Use Case: AG Grid columns have changed
1191
+ * Action: Set Columns in store and filter grid
1192
+ */
1193
+ this.debouncedSetColumnIntoStore = (0, debounce_1.default)(() => {
1194
+ if (!this.isReady) {
1195
+ return;
1196
+ }
1197
+ this.deriveAdaptableColumnStateFromAgGrid();
1198
+ }, GeneralConstants_1.HALF_SECOND);
1199
+ const columnEventsThatTriggersStateChange = [
1200
+ core_1.Events.EVENT_COLUMN_MOVED,
1201
+ core_1.Events.EVENT_GRID_COLUMNS_CHANGED,
1202
+ core_1.Events.EVENT_COLUMN_EVERYTHING_CHANGED,
1203
+ core_1.Events.EVENT_DISPLAYED_COLUMNS_CHANGED,
1204
+ core_1.Events.EVENT_COLUMN_VISIBLE,
1205
+ core_1.Events.EVENT_NEW_COLUMNS_LOADED,
1206
+ ];
1207
+ this.agGridAdapter.getAgGridApi().addGlobalListener((this.listenerGlobalColumnEventsThatTriggerStateChange = (type) => {
1208
+ if (columnEventsThatTriggersStateChange.indexOf(type) > -1) {
1209
+ this.debouncedSetColumnIntoStore();
1210
+ }
1211
+ }));
1212
+ /**
1213
+ * Use Case: User has started inline editing but its distabled in Action Row Options
1214
+ * Action: Stop editing
1215
+ */
1216
+ this.agGridAdapter.getAgGridApi().addEventListener(core_1.Events.EVENT_CELL_EDITING_STARTED, (this.listenerCellEditingStarted = () => {
1217
+ var _a;
1218
+ if ((_a = this.adaptableOptions.actionRowOptions) === null || _a === void 0 ? void 0 : _a.disableInlineEditing)
1219
+ this.agGridAdapter.getAgGridApi().stopEditing();
1220
+ }));
1221
+ /**
1222
+ * Use Case: initial data has been displayed in grid
1223
+ * Action1: Set the Layout
1224
+ * Action2: Ensure that we have set column data types
1225
+ * Note: Deals with scenario where the data is provided to AdapTable after grid has been setup
1226
+ */
1227
+ this.agGridAdapter.getAgGridApi().addEventListener(core_1.Events.EVENT_FIRST_DATA_RENDERED, (this.listenerFirstDataRendered = () => {
1228
+ if (this.initWithLazyData) {
1229
+ this.updateColumnModelAndRefreshGrid();
1230
+ this.api.calculatedColumnApi.refreshAggregatedCalculatedColumns();
1231
+ }
1232
+ }));
1233
+ /**
1234
+ * Use Case: Entered or Left Pivot Mode
1235
+ * Action 1: Autosize pivot columns when entering pivot mode (if autosize pivot in Layout is true)
1236
+ * Action 2: Set pivot mode on / off in api as necessary
1237
+ */
1238
+ this.agGridAdapter.getAgGridApi().addEventListener(core_1.Events.EVENT_COLUMN_PIVOT_MODE_CHANGED, (this.listenerPivotModeChanged = (params) => {
1239
+ if (params.type == 'columnPivotModeChanged' &&
1240
+ params.columnApi != null &&
1241
+ params.columnApi.columnController != null &&
1242
+ params.columnApi.columnController.pivotMode == true) {
1243
+ if (this.adaptableOptions.layoutOptions.autoSizeColumnsInPivotLayout == true) {
1244
+ this.agGridAdapter.getAgGridApi().autoSizeAllColumns();
1245
+ }
1246
+ this.api.internalApi.setPivotModeOn();
1247
+ }
1248
+ else {
1249
+ this.api.internalApi.setPivotModeOff();
1250
+ }
1251
+ }));
1252
+ /**
1253
+ * Use Case: A pivot column has changed
1254
+ * Action: Autosize pivot columns (if autosize pivot in Layout is true)
1255
+ */
1256
+ this.agGridAdapter.getAgGridApi().addEventListener(core_1.Events.EVENT_COLUMN_PIVOT_CHANGED, (this.listenerPivotChanged = (params) => {
1257
+ if (params.type == 'columnPivotChanged' &&
1258
+ params.columnApi != null &&
1259
+ params.columnApi.columnController != null &&
1260
+ params.columnApi.columnController.pivotMode == true) {
1261
+ if (this.adaptableOptions.layoutOptions.autoSizeColumnsInPivotLayout == true) {
1262
+ this.agGridAdapter.getAgGridApi().autoSizeAllColumns();
1263
+ }
1264
+ }
1265
+ }));
1266
+ /**
1267
+ * Use Case: Things have changed in the grid that require the Layout to be saved
1268
+ * Action: Save the Layout (on a debounce)
1269
+ */
1270
+ const columnEventsThatTriggersAutoLayoutSave = [
1271
+ core_1.Events.EVENT_COLUMN_PINNED,
1272
+ core_1.Events.EVENT_COLUMN_PIVOT_CHANGED,
1273
+ core_1.Events.EVENT_COLUMN_PIVOT_MODE_CHANGED,
1274
+ core_1.Events.EVENT_DISPLAYED_COLUMNS_CHANGED,
1275
+ core_1.Events.EVENT_SORT_CHANGED,
1276
+ core_1.Events.EVENT_COLUMN_ROW_GROUP_CHANGED,
1277
+ core_1.Events.EVENT_COLUMN_VALUE_CHANGED,
1278
+ ];
1279
+ // ADD filter event
1280
+ this.agGridAdapter.getAgGridApi().addGlobalListener((this.listenerGlobalColumnEventsThatTriggerAutoLayoutSave = (type) => {
1281
+ if (columnEventsThatTriggersAutoLayoutSave.indexOf(type) > -1) {
1282
+ this.debouncedSaveGridLayout();
1283
+ }
1284
+ }));
1285
+ /**
1286
+ * Save Layout if Display Row Groups is "dynamic
1287
+ */
1288
+ this.debouncedSaveGridLayout = (0, debounce_1.default)(() => {
1289
+ if (!this.isReady) {
1290
+ return;
1291
+ }
1292
+ this.updateLayoutFromGrid();
1293
+ }, GeneralConstants_1.HALF_SECOND);
1294
+ const rowGroupEventsThatTriggersAutoLayoutSave = [
1295
+ core_1.Events.EVENT_ROW_GROUP_OPENED,
1296
+ core_1.Events.EVENT_EXPAND_COLLAPSE_ALL,
1297
+ ];
1298
+ this.agGridAdapter.getAgGridApi().addGlobalListener((this.listenerGlobalRowGroupEventsThatTriggerAutoLayoutSave = (type) => {
1299
+ if (rowGroupEventsThatTriggersAutoLayoutSave.indexOf(type) > -1) {
1300
+ if (this.adaptableOptions.layoutOptions.displayRowGroups == 'dynamic') {
1301
+ this.debouncedSaveGridLayout();
1302
+ }
1303
+ }
1304
+ }));
1305
+ /**
1306
+ * Use Case: Column Row Grouping changes and 'restoreUngroupedColumns' is true
1307
+ * Action: Make the column invisiblel
1308
+ */
1309
+ this.agGridAdapter.getAgGridApi().addEventListener(core_1.Events.EVENT_COLUMN_ROW_GROUP_CHANGED, (this.listenerColumnRowGroupChanged = (params) => {
1310
+ var _a, _b;
1311
+ if (this.api.internalApi.isGridInPivotMode()) {
1312
+ return;
1313
+ }
1314
+ if ((_b = (_a = this.adaptableOptions) === null || _a === void 0 ? void 0 : _a.groupingOptions) === null || _b === void 0 ? void 0 : _b.restoreUngroupedColumns) {
1315
+ this.persistColumnIndexBeforeGrouping(params);
1316
+ }
1317
+ }));
1318
+ /**
1319
+ * Use Case: A Column has finished being resized
1320
+ * Action 1: Save the Layout (on a debounce)
1321
+ * Action 2: Emit the internal ColumnResized event - used by Sparkline Column (in Charts)
1322
+ */
1323
+ this.agGridAdapter.getAgGridApi().addEventListener(core_1.Events.EVENT_COLUMN_RESIZED, (this.listenerColumnResized = (params) => {
1324
+ if (params.finished == true && params.type == 'columnResized' && params.column) {
1325
+ this.debouncedSaveGridLayout();
1326
+ }
1327
+ }));
1328
+ /**
1329
+ * Use Case: Row Selection has changed
1330
+ * Action: Set Selected Rows (on a debeounce)
1331
+ */
1332
+ this.debouncedSetSelectedRows = (0, debounce_1.default)(() => {
1333
+ if (!this.isReady) {
1334
+ return;
1335
+ }
1336
+ this.refreshSelectedRowsState();
1337
+ }, GeneralConstants_1.HALF_SECOND);
1338
+ const columnEventsThatTriggerSetRowSelection = [
1339
+ core_1.Events.EVENT_ROW_GROUP_OPENED,
1340
+ core_1.Events.EVENT_SELECTION_CHANGED,
1341
+ core_1.Events.EVENT_ROW_SELECTED,
1342
+ ];
1343
+ this.agGridAdapter.getAgGridApi().addGlobalListener((this.listenerGlobalSetRowSelection = (type) => {
1344
+ if (ArrayExtensions_1.default.ContainsItem(columnEventsThatTriggerSetRowSelection, type)) {
1345
+ this.debouncedSetSelectedRows();
1346
+ }
1347
+ }));
1348
+ /**
1349
+ * Use Case: User has selected a range of cells
1350
+ * Action: Set Selected Cells (on a debounce)
1351
+ */
1352
+ this.debouncedSetSelectedCells = (0, debounce_1.default)(() => {
1353
+ if (!this.isReady) {
1354
+ return;
1355
+ }
1356
+ this.refreshSelectedCellsState();
1357
+ }, 250);
1358
+ this.agGridAdapter.getAgGridApi().addEventListener(core_1.Events.EVENT_RANGE_SELECTION_CHANGED, (this.listenerRangeSelectionChanged = (params) => {
1359
+ if (params.finished == true) {
1360
+ this.debouncedSetSelectedCells();
1361
+ }
1362
+ }));
1363
+ /**
1364
+ * Use Case: Sort has changed in the Grid
1365
+ * Action1: Update AdapTable Sort Info
1366
+ * Action2: Set Selected Cells (on a debounce)
1367
+ */
1368
+ this.agGridAdapter.getAgGridApi().addEventListener(core_1.Events.EVENT_SORT_CHANGED, (this.listenerSortChanged = () => {
1369
+ this.onSortChanged();
1370
+ this.debouncedSetSelectedCells();
1371
+ }));
1372
+ const showGroupingTotalsAsHeader = this.adaptableOptions.groupingOptions.showGroupingTotalsAsHeader;
1373
+ /**
1374
+ * Use Case: Model has updated
1375
+ * Action: If user has set to see grouping totals as header create a pinned row (bit of a hack)
1376
+ */
1377
+ this.agGridAdapter.getAgGridApi().addEventListener(core_1.Events.EVENT_MODEL_UPDATED, (this.listenerModelUpdated = (params) => {
1378
+ if (showGroupingTotalsAsHeader) {
1379
+ if (params && params.api) {
1380
+ const pinnedData = params.api.getPinnedTopRow(0);
1381
+ const model = params.api.getModel();
1382
+ const rootNode = model.getRootNode();
1383
+ if (!pinnedData) {
1384
+ params.api.setPinnedTopRowData([rootNode.aggData]);
1385
+ }
1386
+ else {
1387
+ pinnedData.updateData(rootNode.aggData);
1388
+ }
1389
+ }
1390
+ }
1391
+ }));
1392
+ const eventsThatTriggerChartingChanges = [
1393
+ core_1.Events.EVENT_CHART_CREATED,
1394
+ /** Chart Range selection has changed */
1395
+ core_1.Events.EVENT_CHART_RANGE_SELECTION_CHANGED,
1396
+ /** Chart Options have changed */
1397
+ core_1.Events.EVENT_CHART_OPTIONS_CHANGED,
1398
+ /** Chart was destroyed */
1399
+ core_1.Events.EVENT_CHART_DESTROYED,
1400
+ ];
1401
+ const chartingModule = this.ModuleService.getModuleById('Charting');
1402
+ if (chartingModule.isModuleAvailable()) {
1403
+ this.agGridAdapter.getAgGridApi().addGlobalListener((type, params) => {
1404
+ if (ArrayExtensions_1.default.ContainsItem(eventsThatTriggerChartingChanges, type)) {
1405
+ this.ChartingService.onChartModelChange(this.getChartModels(), type, params);
1406
+ }
1407
+ });
1408
+ }
1409
+ /**
1410
+ * Row and Cell listeners created in 2020
1411
+ * These have supplanted many of the events we previously had and simplified things
1412
+ */
1413
+ this.rowListeners = {
1414
+ dataChanged: (event) => {
1415
+ this.onRowDataChanged({
1416
+ rowNode: event.node,
1417
+ oldData: event.oldData,
1418
+ newData: event.newData,
1419
+ });
1420
+ },
1421
+ cellChanged: (event) => {
1422
+ if (event.column) {
1423
+ this.onCellDataChanged({
1424
+ rowNode: event.node,
1425
+ oldValue: event.oldValue,
1426
+ newValue: event.newValue,
1427
+ colId: event.column.colId,
1428
+ });
1429
+ }
1430
+ },
1431
+ };
1432
+ }
1433
+ performAudit(action, oldState, newState) {
1434
+ if (this.isReady) {
1435
+ const adaptableStateChangedInfo = {
1436
+ adaptableApi: this.api,
1437
+ actionName: action.type,
1438
+ clientTimestamp: new Date(),
1439
+ userName: this.adaptableOptions.userName,
1440
+ adaptableId: this.adaptableOptions.adaptableId,
1441
+ adaptableStateKey: this.adaptableOptions.adaptableStateKey,
1442
+ action: action,
1443
+ oldState: oldState,
1444
+ newState: newState,
1445
+ };
1446
+ this.api.eventApi.emit('AdaptableStateChanged', adaptableStateChangedInfo);
1447
+ }
1448
+ }
1449
+ forPlugins(callback) {
1450
+ if (Array.isArray(this.adaptableOptions.plugins)) {
1451
+ this.adaptableOptions.plugins.forEach((plugin) => {
1452
+ callback(plugin);
1453
+ });
1454
+ }
1455
+ }
1456
+ getPluginProperty(pluginId, propertyName, ...args) {
1457
+ const plugins = this.adaptableOptions.plugins || [];
1458
+ const thePlugin = plugins.filter((p) => p.pluginId === pluginId)[0];
1459
+ if (!thePlugin) {
1460
+ throw `Cannot find plugin "${pluginId}". Make sure you spelled it right!`;
1461
+ }
1462
+ if (thePlugin && thePlugin.hasProperty(propertyName)) {
1463
+ return thePlugin.getProperty(propertyName)(...args);
1464
+ }
1465
+ }
1466
+ getPlugin(pluginId) {
1467
+ const plugins = this.adaptableOptions.plugins || [];
1468
+ const thePlugin = plugins.filter((p) => p.pluginId === pluginId)[0];
1469
+ if (!thePlugin) {
1470
+ throw `Cannot find plugin "${pluginId}". Make sure you spelled it right!`;
1471
+ }
1472
+ return thePlugin;
1473
+ }
1474
+ initServices() {
1475
+ // create the services
1476
+ this.LicenseService = this.initLicenseService();
1477
+ this.ChartingService = new ChartingService_1.ChartingService(this.api);
1478
+ this.ThemeService = new ThemeService_1.ThemeService(this.api);
1479
+ this.ValidationService = new ValidationService_1.ValidationService(this.api);
1480
+ this.ReportService = new ReportService_1.ReportService(this.api);
1481
+ this.ModuleService = new ModuleService_1.ModuleService(this.api);
1482
+ this.CalculatedColumnExpressionService = new CalculatedColumnExpressionService_1.CalculatedColumnExpressionService(this.api);
1483
+ this.EntitlementService = new EntitlementService_1.EntitlementService(this.api);
1484
+ this.QueryLanguageService = new QueryLanguageService_1.QueryLanguageService(this.api);
1485
+ this.AlertService = new AlertService_1.AlertService(this.api);
1486
+ this.TeamSharingService = new TeamSharingService_1.TeamSharingService(this.api);
1487
+ this.Fdc3Service = new Fdc3Service_1.Fdc3Service(this.api);
1488
+ this.CellPopupService = new CellPopupService_1.CellPopupService(this.api);
1489
+ this.RowEditService = new RowEditService_1.RowEditService(this.api);
1490
+ this.MetamodelService = new MetamodelService_1.MetamodelService(() => this.api.optionsApi.getAdaptableOptions(), true);
1491
+ }
1492
+ initLicenseService() {
1493
+ const globalObject = typeof globalThis !== 'undefined' ? globalThis : window;
1494
+ const licenseKey = globalObject.ADAPTABLE_LICENSE_KEY || this.api.optionsApi.getLicenseKey();
1495
+ return new LicenseService_1.LicenseService(this, licenseKey, {
1496
+ publishedAt: publishTimestamp,
1497
+ });
1498
+ }
1499
+ initModules() {
1500
+ const modules = new Map();
1501
+ modules.set(ModuleConstants.AlertModuleId, new AlertModule_1.AlertModule(this.api));
1502
+ modules.set(ModuleConstants.BulkUpdateModuleId, new BulkUpdateModule_1.BulkUpdateModule(this.api));
1503
+ modules.set(ModuleConstants.CalculatedColumnModuleId, new CalculatedColumnModule_1.CalculatedColumnModule(this.api));
1504
+ modules.set(ModuleConstants.CellSummaryModuleId, new CellSummaryModule_1.CellSummaryModule(this.api));
1505
+ modules.set(ModuleConstants.ChartingModuleId, new ChartingModule_1.ChartingModule(this.api));
1506
+ modules.set(ModuleConstants.ColumnFilterModuleId, new ColumnFilterModule_1.ColumnFilterModule(this.api));
1507
+ modules.set(ModuleConstants.ColumnInfoModuleId, new ColumnInfoModule_1.ColumnInfoModule(this.api));
1508
+ modules.set(ModuleConstants.CommentsModuleId, new CommentsModule_1.CommentsModule(this.api));
1509
+ modules.set(ModuleConstants.CustomSortModuleId, new CustomSortModule_1.CustomSortModule(this.api));
1510
+ modules.set(ModuleConstants.DashboardModuleId, new DashboardModule_1.DashboardModule(this.api));
1511
+ modules.set(ModuleConstants.DataChangeHistoryModuleId, new DataChangeHistoryModule_1.DataChangeHistoryModule(this.api));
1512
+ modules.set(ModuleConstants.DataImportModuleId, new DataImportModule_1.DataImportModule(this.api));
1513
+ modules.set(ModuleConstants.DataSetModuleId, new DataSetModule_1.DataSetModule(this.api));
1514
+ modules.set(ModuleConstants.ExportModuleId, new ExportModule_1.ExportModule(this.api));
1515
+ modules.set(ModuleConstants.Fdc3ModuleId, new Fdc3Module_1.Fdc3Module(this.api));
1516
+ modules.set(ModuleConstants.FlashingCellModuleId, new FlashingCellModule_1.FlashingCellModule(this.api));
1517
+ modules.set(ModuleConstants.FormatColumnModuleId, new FormatColumnModule_1.FormatColumnModule(this.api));
1518
+ modules.set(ModuleConstants.FreeTextColumnModuleId, new FreeTextColumnModule_1.FreeTextColumnModule(this.api));
1519
+ modules.set(ModuleConstants.GridFilterModuleId, new GridFilterModule_1.GridFilterModule(this.api));
1520
+ modules.set(ModuleConstants.GridInfoModuleId, new GridInfoModule_1.GridInfoModule(this.api));
1521
+ modules.set(ModuleConstants.LayoutModuleId, new LayoutModule_1.LayoutModule(this.api));
1522
+ modules.set(ModuleConstants.NamedQueryModuleId, new NamedQueryModule_1.NamedQueryModule(this.api));
1523
+ modules.set(ModuleConstants.NotesModuleId, new NotesModule_1.NotesModule(this.api));
1524
+ modules.set(ModuleConstants.PlusMinusModuleId, new PlusMinusModule_1.PlusMinusModule(this.api));
1525
+ modules.set(ModuleConstants.QuickSearchModuleId, new QuickSearchModule_1.QuickSearchModule(this.api));
1526
+ modules.set(ModuleConstants.ScheduleModuleId, new ScheduleModule_1.ScheduleModule(this.api));
1527
+ modules.set(ModuleConstants.SettingsPanelModuleId, new SettingsPanelModule_1.SettingsPanelModule(this.api));
1528
+ modules.set(ModuleConstants.ShortcutModuleId, new ShortcutModule_1.ShortcutModule(this.api));
1529
+ modules.set(ModuleConstants.SmartEditModuleId, new SmartEditModule_1.SmartEditModule(this.api));
1530
+ modules.set(ModuleConstants.StateManagementModuleId, new StateManagementModule_1.StateManagementModule(this.api));
1531
+ modules.set(ModuleConstants.StatusBarModuleId, new StatusBarModule_1.StatusBarModule(this.api));
1532
+ modules.set(ModuleConstants.StyledColumnModuleId, new StyledColumnModule_1.StyledColumnModule(this.api));
1533
+ modules.set(ModuleConstants.SystemStatusModuleId, new SystemStatusModule_1.SystemStatusModule(this.api));
1534
+ modules.set(ModuleConstants.TeamSharingModuleId, new TeamSharingModule_1.TeamSharingModule(this.api));
1535
+ modules.set(ModuleConstants.ThemeModuleId, new ThemeModule_1.ThemeModule(this.api));
1536
+ modules.set(ModuleConstants.ToolPanelModuleId, new ToolPanelModule_1.ToolPanelModule(this.api));
1537
+ return modules;
1538
+ }
1539
+ /**
1540
+ * This method contains all the updates on the AdaptableState which were made AFTER Adaptbale was ready
1541
+ * This was contidioned because we required AG Grid to be ready before we could make these updates
1542
+ * We should be able to refactor the code, no that we no fore sure that Adaptable State is ready BEFORE AG Grid init
1543
+ */
1544
+ temporaryAdaptableStateUpdates() {
1545
+ this.api.eventApi.on('AdaptableReady', () => {
1546
+ var _a, _b;
1547
+ // update status bar state
1548
+ const adaptableStatusPanels = (_b = (_a = this.agGridAdapter.initialGridOptions.statusBar) === null || _a === void 0 ? void 0 : _a.statusPanels) === null || _b === void 0 ? void 0 : _b.filter((statusPanel) => this.adaptableStatusPanelKeys.includes(statusPanel.key));
1549
+ const statusBarModule = this.ModuleService.getModuleById(ModuleConstants.StatusBarModuleId);
1550
+ // need to add only the adaptable panels
1551
+ statusBarModule.syncStateWithOptions(adaptableStatusPanels);
1552
+ });
1553
+ }
1554
+ validatePrimaryKey() {
1555
+ if (this.hasAutogeneratedPrimaryKey) {
1556
+ return;
1557
+ }
1558
+ const primaryKey = this.adaptableOptions.primaryKey;
1559
+ const primaryKeyColDef = this.agGridAdapter.getAgGridApi().getColumnDef(primaryKey);
1560
+ if (!primaryKeyColDef) {
1561
+ const errorMessage = `The Primary Key Column '${this.adaptableOptions.primaryKey}' does not exist. This will affect many functions in Adaptable.`;
1562
+ if (this.adaptableOptions.alertOptions.showMissingPrimaryKeyAlert) {
1563
+ // show an alert if that is the option
1564
+ this.api.alertApi.showAlertError('No Primary Key', errorMessage);
1565
+ }
1566
+ else {
1567
+ if (this.adaptableOptions.columnOptions.showMissingColumnsWarning) {
1568
+ this.logger.consoleError(errorMessage);
1569
+ }
1570
+ }
1571
+ }
1572
+ }
1573
+ deriveAdaptableColumnStateFromAgGrid() {
1574
+ const allColumns = [];
1575
+ const agGridCols = this.agGridAdapter.getAgGridApi().getColumns();
1576
+ const columnGroupChildren = this.agGridAdapter
1577
+ .getAgGridApi()
1578
+ // TODO AFL MIG: check why this assertion is here
1579
+ .getAllDisplayedColumnGroups();
1580
+ const groupsCount = {};
1581
+ const colsToGroups = columnGroupChildren.reduce((acc, columnGroup) => {
1582
+ var _a, _b, _c;
1583
+ if (!((_b = (_a = columnGroup.getProvidedColumnGroup) === null || _a === void 0 ? void 0 : _a.call(columnGroup)) === null || _b === void 0 ? void 0 : _b.getColGroupDef())) {
1584
+ return acc;
1585
+ }
1586
+ const ColumnGroupId = columnGroup.getGroupId();
1587
+ const AllowGroupSplit = !columnGroup.getProvidedColumnGroup().getColGroupDef().marryChildren;
1588
+ const FriendlyName = (_c = columnGroup.getProvidedColumnGroup().getColGroupDef().headerName) !== null && _c !== void 0 ? _c : ColumnGroupId;
1589
+ const columnsInGroup = columnGroup.getLeafColumns();
1590
+ columnsInGroup.forEach((col) => {
1591
+ const group = {
1592
+ columnGroupId: ColumnGroupId,
1593
+ friendlyName: FriendlyName,
1594
+ allowGroupSplit: AllowGroupSplit,
1595
+ groupCount: 0,
1596
+ };
1597
+ groupsCount[group.columnGroupId] = groupsCount[group.columnGroupId] || 0;
1598
+ groupsCount[group.columnGroupId] += columnsInGroup.length;
1599
+ acc[col.getColId()] = group;
1600
+ });
1601
+ return acc;
1602
+ }, {});
1603
+ Object.keys(colsToGroups).forEach((colId) => {
1604
+ colsToGroups[colId].groupCount = groupsCount[colsToGroups[colId].columnGroupId];
1605
+ });
1606
+ // TODO sort the visible columns by layout order
1607
+ agGridCols.forEach((agGridColumn) => {
1608
+ const colId = agGridColumn.getColId();
1609
+ if (!this.api.columnApi.isAutoRowGroupColumn(colId)) {
1610
+ allColumns.push(this.agGridAdapter.createAdaptableColumnFromAgGridColumn(agGridColumn, colsToGroups));
1611
+ }
1612
+ });
1613
+ this.api.gridApi.internalApi.setColumns(allColumns);
1614
+ }
1615
+ checkShouldClearExistingFiltersOrSearches() {
1616
+ // if they have selected to clear column filters on startup then do it
1617
+ if (this.adaptableOptions.columnFilterOptions.clearColumnFiltersOnStartUp) {
1618
+ if (ArrayExtensions_1.default.IsNotNullOrEmpty(this.api.columnFilterApi.getColumnFilters())) {
1619
+ this.logger.warn('Clearing existing Column Filters as "clearColumnFiltersOnStartUp" is true');
1620
+ this.api.columnFilterApi.clearColumnFilters();
1621
+ }
1622
+ }
1623
+ // if they have selected to clear the Grid filter on startup then do it
1624
+ if (this.adaptableOptions.gridFilterOptions.clearGridFilterOnStartUp) {
1625
+ if (StringExtensions_1.default.IsNotNullOrEmpty(this.api.gridFilterApi.getCurrentGridFilterExpression())) {
1626
+ this.logger.warn('Clearing existing Grid Filter as "clearGridFilterOnStartUp" is true');
1627
+ this.api.gridFilterApi.setGridFilterExpression('');
1628
+ }
1629
+ }
1630
+ // if they have selected to clear searches on startup then do it
1631
+ if (this.adaptableOptions.quickSearchOptions.clearQuickSearchOnStartUp) {
1632
+ if (StringExtensions_1.default.IsNotNullOrEmpty(this.api.quickSearchApi.getQuickSearchState().QuickSearchText)) {
1633
+ this.logger.warn('Clearing existing Searches as "clearQuickSearchOnStartUp" is true');
1634
+ this.api.quickSearchApi.clearQuickSearch();
1635
+ }
1636
+ }
1637
+ }
1638
+ getGridCellFromRowNode(rowNode, columnId) {
1639
+ if (rowNode == null) {
1640
+ return undefined;
1641
+ }
1642
+ const abColumn = this.api.columnApi.getColumnWithColumnId(columnId);
1643
+ const pkValue = this.getPrimaryKeyValueFromRowNode(rowNode);
1644
+ const rawValue = this.getRawValueFromRowNode(rowNode, columnId);
1645
+ const displayValue = this.getDisplayValueFromRawValue(rowNode, columnId, rawValue);
1646
+ const normalisedValue = this.getNormalisedValueFromRawValue(rawValue, abColumn);
1647
+ const isPivotCell = this.api.columnApi.isAutoPivotColumn(columnId);
1648
+ const isRowGroupCell = rowNode.group;
1649
+ return {
1650
+ rawValue: rawValue,
1651
+ displayValue: displayValue,
1652
+ normalisedValue: normalisedValue,
1653
+ column: abColumn,
1654
+ primaryKeyValue: pkValue,
1655
+ rowNode: rowNode,
1656
+ isPivotCell,
1657
+ isRowGroupCell,
1658
+ };
1659
+ }
1660
+ getPrimaryKeyValueFromRowNode(rowNode, gridApi) {
1661
+ if (!rowNode) {
1662
+ return null;
1663
+ }
1664
+ const agGridApi = gridApi || this.agGridAdapter.getAgGridApi();
1665
+ let result;
1666
+ if (!this.hasAutogeneratedPrimaryKey) {
1667
+ result = agGridApi.getValue(this.adaptableOptions.primaryKey, rowNode);
1668
+ }
1669
+ if (result == undefined && rowNode.data) {
1670
+ result = rowNode.data[this.adaptableOptions.primaryKey];
1671
+ }
1672
+ return result;
1673
+ }
1674
+ getRawValueFromRowNode(rowNode, columnId) {
1675
+ if (rowNode == null) {
1676
+ return undefined;
1677
+ }
1678
+ return this.agGridAdapter.getAgGridApi().getValue(columnId, rowNode);
1679
+ }
1680
+ getDisplayValueFromRowNode(rowNode, columnId) {
1681
+ if (rowNode == null) {
1682
+ return undefined;
1683
+ }
1684
+ const rawValue = this.getRawValueFromRowNode(rowNode, columnId);
1685
+ return this.getDisplayValueFromRawValue(rowNode, columnId, rawValue);
1686
+ }
1687
+ getDisplayValueFromRawValue(rowNode, columnId, rawValue) {
1688
+ var _a;
1689
+ const isActionColumn = this.api.columnApi.isActionColumn(columnId);
1690
+ if (isActionColumn) {
1691
+ return this.getCleanValue(rawValue);
1692
+ }
1693
+ const colDef = this.agGridAdapter.getAgGridApi().getColumnDef(columnId);
1694
+ if (colDef) {
1695
+ if (typeof colDef.valueFormatter == 'function') {
1696
+ const column = this.agGridAdapter.getAgGridApi().getColumn(columnId);
1697
+ const params = {
1698
+ value: rawValue,
1699
+ node: rowNode,
1700
+ data: rowNode.data,
1701
+ colDef,
1702
+ column,
1703
+ api: this.agGridAdapter.getAgGridApi(),
1704
+ columnApi: (_a = this.agGridAdapter.getLiveGridOptions()) === null || _a === void 0 ? void 0 : _a.columnApi,
1705
+ context: this.agGridAdapter.getLiveGridOptions().context,
1706
+ };
1707
+ const formattedValue = colDef.valueFormatter(params);
1708
+ return formattedValue || '';
1709
+ }
1710
+ }
1711
+ return this.getCleanValue(rawValue);
1712
+ }
1713
+ getCleanValue(value) {
1714
+ if (typeof value === 'string') {
1715
+ return value;
1716
+ }
1717
+ if (value == null || value == 'null' || value == undefined || value == 'undefined') {
1718
+ return undefined;
1719
+ }
1720
+ return String(value) || '';
1721
+ }
1722
+ getNormalisedValueFromRawValue(rawValue, column) {
1723
+ if (!column) {
1724
+ return rawValue;
1725
+ }
1726
+ // prevents from null
1727
+ if (rawValue === undefined || rawValue === null) {
1728
+ return rawValue;
1729
+ }
1730
+ const dataType = column.dataType;
1731
+ if (dataType === 'String') {
1732
+ return typeof rawValue !== 'string' ? String(rawValue) : rawValue;
1733
+ }
1734
+ if (dataType === 'Number') {
1735
+ // empty string or space should not be converted to 0
1736
+ return typeof rawValue !== 'number' && StringExtensions_1.default.IsNumeric(rawValue)
1737
+ ? Number(rawValue)
1738
+ : rawValue;
1739
+ }
1740
+ if (dataType === 'Boolean') {
1741
+ return typeof rawValue !== 'boolean' ? Boolean(rawValue) : rawValue;
1742
+ }
1743
+ if (dataType === 'Date') {
1744
+ return rawValue instanceof Date ? rawValue : (0, DateHelper_1.parseDateValue)(rawValue);
1745
+ }
1746
+ return rawValue;
1747
+ }
1748
+ updateColumnModelAndRefreshGrid() {
1749
+ this.deriveAdaptableColumnStateFromAgGrid();
1750
+ this.agGridColumnAdapter.setupColumns();
1751
+ this.redrawBody();
1752
+ this.refreshHeader();
1753
+ }
1754
+ redrawBody() {
1755
+ this.redrawRows();
1756
+ this._emit('GridRefreshed');
1757
+ }
1758
+ refreshHeader() {
1759
+ this.agGridAdapter.getAgGridApi().refreshHeader();
1760
+ }
1761
+ // TODO AFL: this method seems to be used A LOT
1762
+ // we should check if we couldn't use the `refresh` method instead for some cases
1763
+ // see https://www.ag-grid.com/react-data-grid/view-refresh/#redraw-rows
1764
+ redrawRows(rowNodes) {
1765
+ const redrawRowsParams = rowNodes
1766
+ ? {
1767
+ rowNodes,
1768
+ }
1769
+ : undefined;
1770
+ try {
1771
+ this.agGridAdapter.getAgGridApi().redrawRows(redrawRowsParams);
1772
+ }
1773
+ catch (ex) {
1774
+ this.logger.consoleError('AG Grid redrawRows was unable to find some row nodes. Tried to redraw row nodes: ', rowNodes, ex);
1775
+ }
1776
+ }
1777
+ redrawRow(rowNode) {
1778
+ this.redrawRows([rowNode]);
1779
+ }
1780
+ refreshCells(rowNodes, columns, forceUpdate, suppressFlash = false) {
1781
+ const refreshCellParams = {
1782
+ rowNodes,
1783
+ columns: columns,
1784
+ force: forceUpdate,
1785
+ suppressFlash,
1786
+ };
1787
+ this.agGridAdapter.getAgGridApi().refreshCells(refreshCellParams);
1788
+ }
1789
+ refreshColumns(columns, forceUpdate, suppressFlash) {
1790
+ this.refreshCells(null, columns, forceUpdate, suppressFlash);
1791
+ }
1792
+ jumpToRow(rowNode) {
1793
+ this.agGridAdapter.getAgGridApi().ensureNodeVisible(rowNode, 'middle');
1794
+ }
1795
+ jumpToColumn(columnId) {
1796
+ this.agGridAdapter.getAgGridApi().ensureColumnVisible(columnId);
1797
+ }
1798
+ jumpToCell(columnId, rowNode) {
1799
+ this.jumpToRow(rowNode);
1800
+ this.jumpToColumn(columnId);
1801
+ }
1802
+ selectColumn(columnId, config) {
1803
+ if (!(config === null || config === void 0 ? void 0 : config.keepExistingSelection)) {
1804
+ this.agGridAdapter.getAgGridApi().clearRangeSelection();
1805
+ }
1806
+ const cellRangeParams = {
1807
+ rowStartIndex: 0,
1808
+ rowEndIndex: this.agGridAdapter.getAgGridApi().getDisplayedRowCount() - 1,
1809
+ columnStart: columnId,
1810
+ columnEnd: columnId,
1811
+ };
1812
+ this.agGridAdapter.getAgGridApi().addCellRange(cellRangeParams);
1813
+ }
1814
+ selectColumns(columnIds, config) {
1815
+ if (!(config === null || config === void 0 ? void 0 : config.keepExistingSelection)) {
1816
+ this.agGridAdapter.getAgGridApi().clearRangeSelection();
1817
+ }
1818
+ const rowCount = this.agGridAdapter.getAgGridApi().getDisplayedRowCount();
1819
+ columnIds.forEach((colId) => {
1820
+ const cellRangeParams = {
1821
+ rowStartIndex: 0,
1822
+ rowEndIndex: rowCount - 1,
1823
+ columnStart: colId,
1824
+ columnEnd: colId,
1825
+ };
1826
+ this.agGridAdapter.getAgGridApi().addCellRange(cellRangeParams);
1827
+ });
1828
+ }
1829
+ selectAll() {
1830
+ this.agGridAdapter.getAgGridApi().selectAll();
1831
+ }
1832
+ deselectAll() {
1833
+ // need to do both as first just clears selected rows and second clears ranges
1834
+ this.agGridAdapter.getAgGridApi().deselectAll();
1835
+ this.agGridAdapter.getAgGridApi().clearRangeSelection();
1836
+ }
1837
+ setGridData(dataSource) {
1838
+ if (!this.isReady) {
1839
+ return;
1840
+ }
1841
+ if (this.hasAutogeneratedPrimaryKey) {
1842
+ this.addSyntheticPrimaryKey(dataSource);
1843
+ }
1844
+ this.agGridAdapter.setGridOption('rowData', dataSource);
1845
+ this.updateRowGroupsExpandedState();
1846
+ this.updateColumnModelAndRefreshGrid();
1847
+ }
1848
+ getGridData() {
1849
+ const data = [];
1850
+ this.agGridAdapter.getAgGridApi().forEachNode((rowNode) => {
1851
+ if (!this.isGroupRowNode(rowNode)) {
1852
+ data.push(rowNode.data);
1853
+ }
1854
+ });
1855
+ return data;
1856
+ }
1857
+ addSyntheticPrimaryKey(rowData = []) {
1858
+ for (let i = 0; i < rowData.length; i++) {
1859
+ rowData[i][GeneralConstants_1.AUTOGENERATED_PK_COLUMN] = (0, uuid_1.createUuid)();
1860
+ }
1861
+ }
1862
+ // add a synthetic PK only if missing (useful in case of updating row data)
1863
+ addSyntheticPrimaryKeyIfMissing(rowData = []) {
1864
+ this.adaptableOptions.primaryKey = GeneralConstants_1.AUTOGENERATED_PK_COLUMN;
1865
+ for (let i = 0; i < rowData.length; i++) {
1866
+ if (!rowData[i][GeneralConstants_1.AUTOGENERATED_PK_COLUMN]) {
1867
+ rowData[i][GeneralConstants_1.AUTOGENERATED_PK_COLUMN] = (0, uuid_1.createUuid)();
1868
+ }
1869
+ }
1870
+ }
1871
+ getFirstDisplayedRowNode() {
1872
+ const firstDisplayedRowIndex = this.agGridAdapter
1873
+ .getAgGridApi()
1874
+ .getFirstDisplayedRowIndex();
1875
+ return this.agGridAdapter.getAgGridApi().getDisplayedRowAtIndex(firstDisplayedRowIndex);
1876
+ }
1877
+ getFirstRowNode() {
1878
+ let firstRowNode = this.getFirstDisplayedRowNode();
1879
+ if (firstRowNode === null || firstRowNode === void 0 ? void 0 : firstRowNode.group) {
1880
+ // all groups may be closed so it is safer to get first leaf node
1881
+ // all groups must have at least one leafe node
1882
+ firstRowNode = firstRowNode.allLeafChildren[0];
1883
+ }
1884
+ return firstRowNode;
1885
+ }
1886
+ updateRowGroupsExpandedState(layout) {
1887
+ if (!layout) {
1888
+ layout = this.api.layoutApi.getCurrentLayout();
1889
+ }
1890
+ if (this.api.layoutApi.internalApi.areExpandedRowGroupsSavedInLayouts() &&
1891
+ ArrayExtensions_1.default.IsNotNullOrEmpty(layout.ExpandedRowGroupValues)) {
1892
+ this.expandRowGroupsForValues(layout.ExpandedRowGroupValues);
1893
+ }
1894
+ if (this.adaptableOptions.layoutOptions.displayRowGroups === 'expanded') {
1895
+ this.expandAllRowGroups();
1896
+ }
1897
+ }
1898
+ isGroupRowNode(rowNode) {
1899
+ if (!rowNode) {
1900
+ return false;
1901
+ }
1902
+ if (rowNode.isEmptyRowGroupNode()) {
1903
+ return true;
1904
+ }
1905
+ if (rowNode.group && rowNode.group === true) {
1906
+ return true;
1907
+ }
1908
+ if (rowNode.leafGroup && rowNode.leafGroup === true) {
1909
+ return true;
1910
+ }
1911
+ return false;
1912
+ }
1913
+ getFilteredData() {
1914
+ const data = [];
1915
+ this.agGridAdapter.getAgGridApi().forEachNodeAfterFilter((rowNode) => {
1916
+ if (!this.isGroupRowNode(rowNode)) {
1917
+ data.push(rowNode.data);
1918
+ }
1919
+ });
1920
+ return data;
1921
+ }
1922
+ updateRows(dataRows, dataUpdateConfig) {
1923
+ if (this.hasAutogeneratedPrimaryKey) {
1924
+ this.addSyntheticPrimaryKeyIfMissing(dataRows);
1925
+ }
1926
+ dataUpdateConfig = dataUpdateConfig || {};
1927
+ if (dataUpdateConfig.runAsync) {
1928
+ return new Promise((resolve) => {
1929
+ this.agGridAdapter
1930
+ .getAgGridApi()
1931
+ .applyTransactionAsync({ update: dataRows }, (transaction) => {
1932
+ if (typeof dataUpdateConfig.callback === 'function') {
1933
+ dataUpdateConfig.callback(transaction);
1934
+ }
1935
+ resolve(transaction === null || transaction === void 0 ? void 0 : transaction.update);
1936
+ });
1937
+ });
1938
+ }
1939
+ else {
1940
+ const transaction = this.agGridAdapter.getAgGridApi().applyTransaction({
1941
+ update: dataRows,
1942
+ });
1943
+ return Promise.resolve(transaction === null || transaction === void 0 ? void 0 : transaction.update);
1944
+ }
1945
+ }
1946
+ addRows(dataRows, dataUpdateConfig) {
1947
+ if (this.hasAutogeneratedPrimaryKey) {
1948
+ this.addSyntheticPrimaryKey(dataRows);
1949
+ }
1950
+ dataUpdateConfig = dataUpdateConfig || {};
1951
+ const newData = { add: dataRows };
1952
+ if (dataUpdateConfig.addIndex !== undefined) {
1953
+ newData.addIndex = dataUpdateConfig.addIndex;
1954
+ }
1955
+ if (dataUpdateConfig.runAsync) {
1956
+ return new Promise((resolve) => {
1957
+ this.agGridAdapter.getAgGridApi().applyTransactionAsync(newData, (transaction) => {
1958
+ if (typeof dataUpdateConfig.callback === 'function') {
1959
+ dataUpdateConfig.callback(transaction);
1960
+ }
1961
+ resolve(transaction === null || transaction === void 0 ? void 0 : transaction.add);
1962
+ this.updateRowGroupsExpandedState();
1963
+ });
1964
+ });
1965
+ }
1966
+ else {
1967
+ const transaction = this.agGridAdapter.getAgGridApi().applyTransaction(newData);
1968
+ this.updateRowGroupsExpandedState();
1969
+ return Promise.resolve(transaction === null || transaction === void 0 ? void 0 : transaction.add);
1970
+ }
1971
+ }
1972
+ addOrUpdateRows(dataRows, dataUpdateConfig) {
1973
+ const addDataRows = [];
1974
+ const updateDataRows = [];
1975
+ const primaryKey = this.adaptableOptions.primaryKey;
1976
+ dataRows.forEach((dataRow) => {
1977
+ const node = this.getRowNodeForPrimaryKey(dataRow[primaryKey]);
1978
+ if (node) {
1979
+ updateDataRows.push(dataRow);
1980
+ }
1981
+ else {
1982
+ addDataRows.push(dataRow);
1983
+ }
1984
+ });
1985
+ if (this.hasAutogeneratedPrimaryKey) {
1986
+ this.addSyntheticPrimaryKeyIfMissing(addDataRows);
1987
+ }
1988
+ dataUpdateConfig = dataUpdateConfig || {};
1989
+ if (dataUpdateConfig.runAsync) {
1990
+ return new Promise((resolve) => {
1991
+ this.agGridAdapter
1992
+ .getAgGridApi()
1993
+ .applyTransactionAsync({ update: updateDataRows, add: addDataRows, addIndex: dataUpdateConfig.addIndex }, (transaction) => {
1994
+ if (typeof dataUpdateConfig.callback === 'function') {
1995
+ dataUpdateConfig.callback(transaction);
1996
+ }
1997
+ resolve({
1998
+ added: transaction === null || transaction === void 0 ? void 0 : transaction.add,
1999
+ updated: transaction === null || transaction === void 0 ? void 0 : transaction.update,
2000
+ });
2001
+ });
2002
+ });
2003
+ }
2004
+ else {
2005
+ const transaction = this.agGridAdapter.getAgGridApi().applyTransaction({
2006
+ update: updateDataRows,
2007
+ add: addDataRows,
2008
+ addIndex: dataUpdateConfig.addIndex,
2009
+ });
2010
+ return Promise.resolve({
2011
+ added: transaction === null || transaction === void 0 ? void 0 : transaction.add,
2012
+ updated: transaction === null || transaction === void 0 ? void 0 : transaction.update,
2013
+ });
2014
+ }
2015
+ }
2016
+ deleteRows(dataRows, dataUpdateConfig) {
2017
+ dataUpdateConfig = dataUpdateConfig || {};
2018
+ if (dataUpdateConfig.runAsync) {
2019
+ return new Promise((resolve) => {
2020
+ this.agGridAdapter
2021
+ .getAgGridApi()
2022
+ .applyTransactionAsync({ remove: dataRows }, (transaction) => {
2023
+ if (typeof dataUpdateConfig.callback === 'function') {
2024
+ dataUpdateConfig.callback(transaction);
2025
+ }
2026
+ resolve(transaction === null || transaction === void 0 ? void 0 : transaction.remove);
2027
+ });
2028
+ });
2029
+ }
2030
+ else {
2031
+ const transaction = this.agGridAdapter.getAgGridApi().applyTransaction({
2032
+ remove: dataRows,
2033
+ });
2034
+ return Promise.resolve(transaction.remove);
2035
+ }
2036
+ }
2037
+ getRowNodeForPrimaryKey(primaryKeyValue) {
2038
+ if (this.useRowNodeLookUp) {
2039
+ return this.agGridAdapter.getAgGridApi().getRowNode(primaryKeyValue);
2040
+ }
2041
+ else {
2042
+ this.agGridAdapter.getAgGridApi().forEachNode((rowNode) => {
2043
+ if (primaryKeyValue == this.getPrimaryKeyValueFromRowNode(rowNode)) {
2044
+ return rowNode;
2045
+ }
2046
+ });
2047
+ }
2048
+ }
2049
+ hideColumn(columnId) {
2050
+ let agGridColumn = this.agGridAdapter.getAgGridApi().getColumn(columnId);
2051
+ if (agGridColumn) {
2052
+ this.agGridAdapter.getAgGridApi().setColumnsVisible([columnId], false);
2053
+ this.deriveAdaptableColumnStateFromAgGrid();
2054
+ }
2055
+ }
2056
+ showColumn(columnId) {
2057
+ let agGridColumn = this.agGridAdapter.getAgGridApi().getColumn(columnId);
2058
+ if (agGridColumn) {
2059
+ this.agGridAdapter.getAgGridApi().setColumnsVisible([columnId], true);
2060
+ this.deriveAdaptableColumnStateFromAgGrid();
2061
+ }
2062
+ }
2063
+ autoSizeColumn(columnId) {
2064
+ this.autoSizeColumns([columnId]);
2065
+ }
2066
+ autoSizeColumns(columnIds) {
2067
+ this.agGridAdapter.getAgGridApi().autoSizeColumns(columnIds);
2068
+ }
2069
+ autoSizeAllColumns() {
2070
+ this.agGridAdapter.getAgGridApi().autoSizeAllColumns();
2071
+ }
2072
+ setColumnOrder(VisibleColumnList) {
2073
+ const newColumnState = this.getSortedColumnStateForVisibleColumns(VisibleColumnList);
2074
+ this.agGridAdapter.getAgGridApi().applyColumnState({
2075
+ state: newColumnState,
2076
+ applyOrder: true,
2077
+ });
2078
+ this.deriveAdaptableColumnStateFromAgGrid();
2079
+ }
2080
+ getSortedColumnStateForVisibleColumns(visibleColumnList, columnState) {
2081
+ columnState = columnState || this.agGridAdapter.getAgGridApi().getColumnState();
2082
+ const NewVisibleColumnIdsMap = visibleColumnList.reduce((acc, colId, index) => {
2083
+ acc[colId] = index;
2084
+ return acc;
2085
+ }, {});
2086
+ const columnsStateIndexes = columnState.reduce((acc, colState, index) => {
2087
+ acc[colState.colId] = index;
2088
+ return acc;
2089
+ }, {});
2090
+ const newVisibleColumnsMap = visibleColumnList.reduce((acc, colId, index) => {
2091
+ acc[colId] = index;
2092
+ return acc;
2093
+ }, {});
2094
+ const result = [...columnState]
2095
+ .sort((colState1, colState2) => {
2096
+ const colId1 = colState1.colId;
2097
+ const colId2 = colState2.colId;
2098
+ const originalIndex1 = columnsStateIndexes[colId1];
2099
+ const originalIndex2 = columnsStateIndexes[colId2];
2100
+ const isRowGroup1 = this.api.columnApi.isAutoRowGroupColumn(colId1);
2101
+ const isRowGroup2 = this.api.columnApi.isAutoRowGroupColumn(colId2);
2102
+ if (isRowGroup1 && isRowGroup2) {
2103
+ return 1;
2104
+ }
2105
+ if (isRowGroup1) {
2106
+ return -1;
2107
+ }
2108
+ if (isRowGroup2) {
2109
+ return 1;
2110
+ }
2111
+ if (newVisibleColumnsMap[colId1] != null && newVisibleColumnsMap[colId2] == null) {
2112
+ return -1;
2113
+ }
2114
+ if (newVisibleColumnsMap[colId1] == null && newVisibleColumnsMap[colId2] != null) {
2115
+ return 1;
2116
+ }
2117
+ if (newVisibleColumnsMap[colId1] == null && newVisibleColumnsMap[colId2] == null) {
2118
+ return originalIndex1 - originalIndex2;
2119
+ }
2120
+ return newVisibleColumnsMap[colState1.colId] - newVisibleColumnsMap[colState2.colId];
2121
+ })
2122
+ .map((colState) => (Object.assign(Object.assign({}, colState), { hide: NewVisibleColumnIdsMap[colState.colId] == null })));
2123
+ return result;
2124
+ }
2125
+ getDistinctValuesForColumn(column, distinctValuesParams) {
2126
+ let gridCells = this.getGridCellsForPermittedValues(column, distinctValuesParams);
2127
+ if (ArrayExtensions_1.default.IsNullOrEmpty(gridCells)) {
2128
+ gridCells = this.getDistinctGridCellsForColumn(column, distinctValuesParams);
2129
+ }
2130
+ return this.getUniqueGridCells(column, gridCells);
2131
+ }
2132
+ getGridCellsForPermittedValues(column, distinctValuesParams) {
2133
+ var _a;
2134
+ let gridCells = [];
2135
+ const permittedValues = (_a = distinctValuesParams.permittedValues) !== null && _a !== void 0 ? _a : this.api.userInterfaceApi.getPermittedValuesForColumn(column);
2136
+ if (ArrayExtensions_1.default.IsNotNullOrEmpty(permittedValues)) {
2137
+ gridCells = permittedValues.map((pv) => {
2138
+ return {
2139
+ rawValue: pv,
2140
+ displayValue: pv,
2141
+ normalisedValue: pv,
2142
+ columnId: column.columnId,
2143
+ column: column,
2144
+ rowNode: undefined,
2145
+ isPivotCell: false,
2146
+ isRowGroupCell: false,
2147
+ };
2148
+ });
2149
+ return gridCells;
2150
+ }
2151
+ }
2152
+ getDistinctGridCellsForColumn(column, distinctValuesParams) {
2153
+ let gridCells = [];
2154
+ if (distinctValuesParams.visibleRowsOnly) {
2155
+ this.agGridAdapter.getAgGridApi().forEachNodeAfterFilter((rowNode) => {
2156
+ const gridCell = this.addDistinctColumnValue(rowNode, column.columnId);
2157
+ if (gridCell &&
2158
+ gridCell.rawValue != undefined &&
2159
+ gridCell.rowNode !== distinctValuesParams.skipRowNode) {
2160
+ gridCells.push(gridCell);
2161
+ }
2162
+ });
2163
+ }
2164
+ else {
2165
+ this.agGridAdapter.getAgGridApi().forEachNode((rowNode) => {
2166
+ const gridCell = this.addDistinctColumnValue(rowNode, column.columnId);
2167
+ if (gridCell && gridCell.rowNode !== distinctValuesParams.skipRowNode) {
2168
+ if (gridCell.rawValue == undefined &&
2169
+ this.adaptableOptions.columnFilterOptions.valuesFilterOptions.includeBlankFilterValues) {
2170
+ gridCell.rawValue = GeneralConstants_1.BLANK_DISTINCT_COLUMN_VALUE;
2171
+ gridCell.displayValue = GeneralConstants_1.BLANK_DISTINCT_COLUMN_VALUE;
2172
+ gridCell.normalisedValue = GeneralConstants_1.BLANK_DISTINCT_COLUMN_VALUE;
2173
+ }
2174
+ gridCells.push(gridCell);
2175
+ }
2176
+ });
2177
+ }
2178
+ return gridCells;
2179
+ }
2180
+ addDistinctColumnValue(rowNode, columnId) {
2181
+ // we do not return the values of the aggregates when in grouping mode
2182
+ // otherwise they would appear in the filter dropdown etc....
2183
+ if (rowNode && !this.isGroupRowNode(rowNode)) {
2184
+ const returnValue = this.getGridCellFromRowNode(rowNode, columnId);
2185
+ if (Helper_1.Helper.objectExists(returnValue)) {
2186
+ return returnValue;
2187
+ }
2188
+ }
2189
+ else {
2190
+ return undefined;
2191
+ }
2192
+ }
2193
+ getUniqueGridCells(column, gridCells) {
2194
+ let uniqueVals = (0, uniqBy_1.default)(gridCells, (dataItem) => {
2195
+ const value = dataItem.rawValue;
2196
+ if (value instanceof Date) {
2197
+ return value.toISOString();
2198
+ }
2199
+ return value;
2200
+ });
2201
+ if (column.dataType == 'String' && this.api.predicateApi.useCaseSensitivity()) {
2202
+ uniqueVals = (0, uniqBy_1.default)(uniqueVals, (d) => d.displayValue.toLowerCase());
2203
+ }
2204
+ return uniqueVals.slice(0, this.api.columnFilterApi.internalApi.getFilterValuesMaxNumberOfItems(column));
2205
+ }
2206
+ getGridCellsForColumn(columnId) {
2207
+ let returnValues = [];
2208
+ this.agGridAdapter.getAgGridApi().forEachNode((rowNode) => {
2209
+ const gridCell = this.getGridCellFromRowNode(rowNode, columnId);
2210
+ if (gridCell && gridCell.rawValue != undefined) {
2211
+ returnValues.push(gridCell);
2212
+ }
2213
+ });
2214
+ return returnValues;
2215
+ }
2216
+ getRowNodesForPrimaryKeys(primaryKeyValues) {
2217
+ let rowNodes = [];
2218
+ if (this.useRowNodeLookUp) {
2219
+ primaryKeyValues.forEach((pkValue) => {
2220
+ const rowNode = this.agGridAdapter.getAgGridApi().getRowNode(pkValue);
2221
+ if (rowNode) {
2222
+ rowNodes.push(rowNode);
2223
+ }
2224
+ });
2225
+ }
2226
+ else {
2227
+ primaryKeyValues.forEach((pkValue) => {
2228
+ let foundRow = false;
2229
+ this.agGridAdapter.getAgGridApi().forEachNode((rowNode) => {
2230
+ if (!foundRow && pkValue == this.getPrimaryKeyValueFromRowNode(rowNode)) {
2231
+ rowNodes.push(rowNode);
2232
+ foundRow = true;
2233
+ }
2234
+ });
2235
+ });
2236
+ }
2237
+ return rowNodes;
2238
+ }
2239
+ getRowNodeByIndex(index) {
2240
+ return this.agGridAdapter.getAgGridApi().getDisplayedRowAtIndex(index);
2241
+ }
2242
+ getAgGridStatusPanels() {
2243
+ var _a, _b, _c;
2244
+ return (_c = (_b = (_a = this.agGridAdapter.getLiveGridOptions()) === null || _a === void 0 ? void 0 : _a.statusBar) === null || _b === void 0 ? void 0 : _b.statusPanels) !== null && _c !== void 0 ? _c : [];
2245
+ }
2246
+ setDataValue(value, column, primaryKeyValue, rowNode) {
2247
+ // note: because we use RowNode.setDataValue() this will cause Validation to fire
2248
+ // see https://www.ag-grid.com/javascript-data-grid/change-detection/#triggering-value-change-detection
2249
+ let newValue;
2250
+ let dataType = column.dataType;
2251
+ newValue = dataType == 'Number' ? Number(value) : value;
2252
+ if (dataType == undefined) {
2253
+ return; // no point continuing as probably a wrong column
2254
+ }
2255
+ if (rowNode) {
2256
+ rowNode.setDataValue(column.columnId, newValue);
2257
+ }
2258
+ else {
2259
+ if (this.useRowNodeLookUp) {
2260
+ const rowNode = this.agGridAdapter.getAgGridApi().getRowNode(primaryKeyValue);
2261
+ if (rowNode != null) {
2262
+ rowNode.setDataValue(column.columnId, newValue);
2263
+ }
2264
+ }
2265
+ else {
2266
+ let isUpdated = false;
2267
+ // prefer not to use this method but if we do then at least we can prevent further lookups once we find
2268
+ this.agGridAdapter.getAgGridApi().forEachNode((rowNode) => {
2269
+ if (!isUpdated) {
2270
+ if (primaryKeyValue == this.getPrimaryKeyValueFromRowNode(rowNode)) {
2271
+ rowNode.setDataValue(column.columnId, newValue);
2272
+ isUpdated = true;
2273
+ }
2274
+ }
2275
+ });
2276
+ }
2277
+ }
2278
+ }
2279
+ isCellEditable(rowNode, column) {
2280
+ // it's safe to rely on the AG Grid implementation because we override the colDef.editable property, which is in this case the single source of truth
2281
+ return column === null || column === void 0 ? void 0 : column.isCellEditable(rowNode);
2282
+ }
2283
+ forAllRowNodesDo(func, config) {
2284
+ this.agGridAdapter.getAgGridApi().forEachNode((rowNode, rowIndex) => {
2285
+ const includeGroupRows = (config === null || config === void 0 ? void 0 : config.includeGroupRows) || !this.isGroupRowNode(rowNode);
2286
+ const filterFnFulfilled = !(config === null || config === void 0 ? void 0 : config.filterFn) || (config === null || config === void 0 ? void 0 : config.filterFn(rowNode));
2287
+ if (includeGroupRows && filterFnFulfilled) {
2288
+ func(rowNode, rowIndex);
2289
+ }
2290
+ });
2291
+ }
2292
+ forAllVisibleRowNodesDo(func, config) {
2293
+ if (this.getAgGridRowModelType() !== 'clientSide') {
2294
+ // only in client-side row model can we loop through filtered&sorted rows
2295
+ // see https://www.ag-grid.com/javascript-data-grid/accessing-data/#iterating-rows
2296
+ this.logger.warn('`forAllVisibleRowNodesDo()` is only supported in client-side row model. `forAllRowNodesDo` will be used instead.');
2297
+ return this.forAllRowNodesDo(func, config);
2298
+ }
2299
+ this.agGridAdapter.getAgGridApi().forEachNodeAfterFilterAndSort((rowNode, rowIndex) => {
2300
+ const includeGroupRows = (config === null || config === void 0 ? void 0 : config.includeGroupRows) || !this.isGroupRowNode(rowNode);
2301
+ const filterFnFulfilled = !(config === null || config === void 0 ? void 0 : config.filterFn) || (config === null || config === void 0 ? void 0 : config.filterFn(rowNode));
2302
+ if (includeGroupRows && filterFnFulfilled) {
2303
+ func(rowNode, rowIndex);
2304
+ }
2305
+ });
2306
+ }
2307
+ getAgGridRowModelType() {
2308
+ var _a, _b;
2309
+ // it seems that this can be null so we need explicitly to return "clientSide" in this case
2310
+ // need to check that for ServerSideRowModel it is ALWAYS returned...
2311
+ return (_b = (_a = this.agGridAdapter.initialGridOptions) === null || _a === void 0 ? void 0 : _a.rowModelType) !== null && _b !== void 0 ? _b : 'clientSide';
2312
+ }
2313
+ getAllRowNodes(config) {
2314
+ let rowNodes = [];
2315
+ this.forAllRowNodesDo((rowNode) => rowNodes.push(rowNode), config);
2316
+ return rowNodes;
2317
+ }
2318
+ getGroupRowNodes() {
2319
+ return this.getAllRowNodes({
2320
+ includeGroupRows: true,
2321
+ filterFn: (rowNode) => this.isGroupRowNode(rowNode),
2322
+ });
2323
+ }
2324
+ getRowsInViewport() {
2325
+ return this.agGridAdapter.getAgGridApi().getRenderedNodes();
2326
+ }
2327
+ isRowNodeVisible(rowNode) {
2328
+ const foundNode = this.agGridAdapter
2329
+ .getAgGridApi()
2330
+ .getRenderedNodes()
2331
+ .find((n) => n.id == rowNode.id);
2332
+ return foundNode != null;
2333
+ }
2334
+ selectNodes(rowNodes, clearSelection) {
2335
+ if (ArrayExtensions_1.default.IsNotNullOrEmpty(rowNodes)) {
2336
+ rowNodes.forEach((node) => this.selectNode(node, clearSelection));
2337
+ }
2338
+ }
2339
+ deSelectNodes(rowNodes, clearSelection) {
2340
+ if (ArrayExtensions_1.default.IsNotNullOrEmpty(rowNodes)) {
2341
+ rowNodes.forEach((node) => this.deSelectNode(node, clearSelection));
2342
+ }
2343
+ }
2344
+ selectNode(rowNode, clearSelection) {
2345
+ if (!rowNode) {
2346
+ this.logger.error('No node to select');
2347
+ return;
2348
+ }
2349
+ rowNode.setSelected(true, clearSelection);
2350
+ }
2351
+ deSelectNode(rowNode, clearSelection) {
2352
+ if (!rowNode) {
2353
+ this.logger.error('No node to deselect');
2354
+ return;
2355
+ }
2356
+ rowNode.setSelected(false, clearSelection);
2357
+ }
2358
+ selectCells(columnIds, startNode, endNode, clearSelection) {
2359
+ if (clearSelection) {
2360
+ this.agGridAdapter.getAgGridApi().clearRangeSelection();
2361
+ }
2362
+ const cellRangeParams = {
2363
+ rowStartIndex: startNode.rowIndex,
2364
+ rowEndIndex: endNode.rowIndex,
2365
+ columns: columnIds,
2366
+ };
2367
+ this.agGridAdapter.getAgGridApi().addCellRange(cellRangeParams);
2368
+ }
2369
+ getAgGridColumnType(columnId) {
2370
+ var _a;
2371
+ const { type } = (_a = this.agGridAdapter.getAgGridApi().getColumnDef(columnId)) !== null && _a !== void 0 ? _a : {};
2372
+ return type || '';
2373
+ }
2374
+ setColumnSort(columnSorts) {
2375
+ if (!this.isReady) {
2376
+ return;
2377
+ }
2378
+ const columnSortsMap = columnSorts === null || columnSorts === void 0 ? void 0 : columnSorts.reduce((acc, columnSort, index) => {
2379
+ acc[columnSort.ColumnId] = Object.assign(Object.assign({}, columnSort), { SortIndex: index });
2380
+ return acc;
2381
+ }, {});
2382
+ const newColumnState = this.agGridAdapter
2383
+ .getAgGridApi()
2384
+ .getColumnState()
2385
+ .map((colState) => {
2386
+ const { colId } = colState;
2387
+ const state = Object.assign({}, colState);
2388
+ const colSort = columnSortsMap ? columnSortsMap[colId] : undefined;
2389
+ if (colSort) {
2390
+ state.sort = colSort.SortOrder === 'Asc' ? 'asc' : 'desc';
2391
+ state.sortIndex = colSort.SortIndex;
2392
+ }
2393
+ else {
2394
+ state.sort = null;
2395
+ state.sortIndex = null;
2396
+ }
2397
+ return state;
2398
+ });
2399
+ this.agGridAdapter.getAgGridApi().applyColumnState({
2400
+ state: newColumnState,
2401
+ applyOrder: true,
2402
+ });
2403
+ this.agGridAdapter.getAgGridApi().onSortChanged();
2404
+ }
2405
+ clearColumnSort() {
2406
+ this.setColumnSort(null);
2407
+ }
2408
+ hideColumnFilterForm() {
2409
+ if (this.hideFilterFormPopup) {
2410
+ this.hideFilterFormPopup();
2411
+ }
2412
+ }
2413
+ clearColumnFiltering() {
2414
+ this.agGridAdapter
2415
+ .getAgGridApi()
2416
+ .getColumns()
2417
+ .forEach((c) => {
2418
+ this.agGridAdapter.getAgGridApi().destroyFilter(c);
2419
+ });
2420
+ }
2421
+ clearColumnFilteringForColumns(columnIds) {
2422
+ columnIds.forEach((c) => {
2423
+ const column = this.agGridAdapter
2424
+ .getAgGridApi()
2425
+ .getColumns()
2426
+ .find((col) => col.getColId() === c);
2427
+ if (column) {
2428
+ this.agGridAdapter.getAgGridApi().destroyFilter(column);
2429
+ }
2430
+ });
2431
+ }
2432
+ canGenerateCharts() {
2433
+ return (this.agGridAdapter.isModulePresent(core_1.ModuleNames.GridChartsModule) &&
2434
+ this.agGridAdapter.initialGridOptions.enableCharts);
2435
+ }
2436
+ canDisplaySparklines() {
2437
+ return this.agGridAdapter.isModulePresent(core_1.ModuleNames.SparklinesModule);
2438
+ }
2439
+ showCharts(chartsDefinitions, chartContainer) {
2440
+ return chartsDefinitions.map((chartDefinition) => this.showChart(chartDefinition, chartContainer));
2441
+ }
2442
+ showChart(chartDefinition, container) {
2443
+ if (!this.isReady) {
2444
+ this.logger.consoleError('Adaptable must be instantiated before calling showChart');
2445
+ return null;
2446
+ }
2447
+ /**
2448
+ * Ag-grid always creates new charts behind the sences.
2449
+ * So we need to update the model inside adaptable state.
2450
+ * This is important to be done as soon as possible so it is not considered new.
2451
+ */
2452
+ const chartRef = this.agGridAdapter
2453
+ .getAgGridApi()
2454
+ .restoreChart(chartDefinition.Model, container);
2455
+ const chartModel = this.getChartModels().find((chartModel) => chartModel.chartId === chartRef.chartId);
2456
+ // Update the definition in state so it is not considered new
2457
+ this.api.chartingApi.editChartDefinition(Object.assign(Object.assign({}, chartDefinition), { Model: chartModel }));
2458
+ return chartRef;
2459
+ }
2460
+ updateChart(chart) {
2461
+ const upgradableProperties = {
2462
+ // Only Range charts are supported to be created at run time
2463
+ // the other two are pivot & cross-filter
2464
+ type: 'rangeChartUpdate',
2465
+ chartId: chart.Model.chartId,
2466
+ unlinkChart: Boolean(chart.Model.unlinkChart),
2467
+ suppressChartRanges: Boolean(chart.Model.suppressChartRanges),
2468
+ aggFunc: chart.Model.aggFunc,
2469
+ };
2470
+ this.agGridAdapter.getAgGridApi().updateChart(upgradableProperties);
2471
+ }
2472
+ getChartModels() {
2473
+ if (!this.isReady) {
2474
+ this.logger.consoleError('Adaptable must be instantiated before calling getChartModels');
2475
+ return [];
2476
+ }
2477
+ return this.agGridAdapter.getAgGridApi().getChartModels();
2478
+ }
2479
+ getRowCount() {
2480
+ return this.agGridAdapter.getAgGridApi().getDisplayedRowCount();
2481
+ }
2482
+ getColumnCount() {
2483
+ var _a, _b;
2484
+ return (_b = (_a = this.agGridAdapter.getAgGridApi().getColumns()) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
2485
+ }
2486
+ getVisibleColumnCount() {
2487
+ var _a, _b;
2488
+ return ((_b = (_a = this.agGridAdapter
2489
+ .getAgGridApi()
2490
+ .getColumns()) === null || _a === void 0 ? void 0 : _a.filter((c) => c.isVisible()).length) !== null && _b !== void 0 ? _b : 0);
2491
+ }
2492
+ isGridGroupable() {
2493
+ return !this.api.internalApi.isGridInTreeMode();
2494
+ }
2495
+ isGridGroupingActive() {
2496
+ let isGroupedActive = false;
2497
+ this.agGridAdapter.getAgGridApi().forEachNode((node) => {
2498
+ if (!isGroupedActive) {
2499
+ if (node.group) {
2500
+ isGroupedActive = true;
2501
+ }
2502
+ }
2503
+ });
2504
+ return isGroupedActive;
2505
+ }
2506
+ setAgGridQuickSearch(searchText) {
2507
+ this.agGridAdapter.setGridOption('quickFilterText', searchText);
2508
+ }
2509
+ getAgGridCurrentThemeName() {
2510
+ const container = this.getAgGridContainerElement();
2511
+ if (container && container.classList) {
2512
+ // we detect the ag theme class
2513
+ const classList = container.classList;
2514
+ for (let i = 0, len = classList.length; i < len; i++) {
2515
+ const cls = classList[i];
2516
+ if (cls.indexOf('ag-theme-') === 0) {
2517
+ return cls;
2518
+ }
2519
+ }
2520
+ }
2521
+ return this.getAgGridLightThemeName();
2522
+ }
2523
+ getAgGridLightThemeName() {
2524
+ const container = this.getAgGridContainerElement();
2525
+ if (container && container.classList) {
2526
+ // we detect the ag theme class
2527
+ const classList = container.classList;
2528
+ for (let i = 0, len = classList.length; i < len; i++) {
2529
+ const cls = classList[i];
2530
+ if (cls.indexOf('ag-theme-') === 0) {
2531
+ // even if dark theme is included, we compute the light theme name out of it
2532
+ return cls.replace('-dark', '');
2533
+ }
2534
+ }
2535
+ }
2536
+ else {
2537
+ this.logger.warn('No AgGrid container found, defaulting to ag-theme-balham for the light theme');
2538
+ }
2539
+ this.logger.warn('No ag-theme- class found on the grid container, defaulting to ag-theme-balham');
2540
+ // fallback to the default light theme
2541
+ return 'ag-theme-balham';
2542
+ }
2543
+ applyAdaptableTheme(theme) {
2544
+ theme = this.ThemeService.mapOsTheme(theme);
2545
+ const themeName = typeof theme === 'string' ? theme : theme.Name;
2546
+ const isSystemTheme = this.api.themeApi.internalApi.isSystemTheme(themeName);
2547
+ const themeClassNamesToRemove = [];
2548
+ const themesToRemove = [];
2549
+ const allThemes = this.api.themeApi.getThemes().map((t) => {
2550
+ // we mutate the theme later,
2551
+ // and since we don't want the mutation to end up in state
2552
+ // we better clone it here
2553
+ return Object.assign({}, t);
2554
+ });
2555
+ const allThemesMap = allThemes.reduce((acc, theme) => {
2556
+ acc[theme.Name] = theme;
2557
+ return acc;
2558
+ }, {});
2559
+ const themeObject = allThemesMap[themeName];
2560
+ // REMOVE PREVIOUS THEME
2561
+ // const themePrefix = 'ab--theme-'
2562
+ const el = document.documentElement;
2563
+ el.classList.forEach((cssClassName) => {
2564
+ const index = cssClassName.indexOf(GeneralConstants.THEME_STYLE);
2565
+ if (index === 0) {
2566
+ themeClassNamesToRemove.push(cssClassName);
2567
+ const themeName = cssClassName.substring(GeneralConstants.THEME_STYLE.length);
2568
+ if (allThemesMap[themeName]) {
2569
+ themesToRemove.push(allThemesMap[themeName]);
2570
+ }
2571
+ }
2572
+ });
2573
+ themeClassNamesToRemove.forEach((cssClassName) => el.classList.remove(cssClassName));
2574
+ // remove infinite table classnames
2575
+ themesToRemove.forEach((theme) => {
2576
+ el.classList.remove(`infinite-${theme.Name}`);
2577
+ });
2578
+ // VARIANT
2579
+ let variantTheme = '';
2580
+ if (!isSystemTheme && themeObject.Variant) {
2581
+ variantTheme = themeObject.Variant;
2582
+ }
2583
+ // APPLY NEW THEME
2584
+ const newTheme = allThemesMap[themeName];
2585
+ const getClassName = (theme) => GeneralConstants.THEME_STYLE + theme;
2586
+ el.classList.add(getClassName(themeName));
2587
+ if (variantTheme) {
2588
+ el.classList.add(getClassName(variantTheme));
2589
+ }
2590
+ if (isSystemTheme) {
2591
+ // add infinite table classname for theme
2592
+ el.classList.add(`infinite-${themeName}`);
2593
+ }
2594
+ else if (variantTheme) {
2595
+ el.classList.add(`infinite-${variantTheme}`);
2596
+ }
2597
+ // AG THEME CLASS NAME
2598
+ const container = this.getAgGridContainerElement();
2599
+ const getAgGridLightThemeName = () => this.getAgGridLightThemeName();
2600
+ const getAgGridDarkThemeName = () => getAgGridLightThemeName() + '-dark';
2601
+ if (newTheme && (isSystemTheme || variantTheme)) {
2602
+ if ((variantTheme || themeName) === GeneralConstants_1.LIGHT_THEME) {
2603
+ newTheme.AgGridClassName = newTheme.AgGridClassName || getAgGridLightThemeName();
2604
+ }
2605
+ if ((variantTheme || themeName) === GeneralConstants_1.DARK_THEME) {
2606
+ newTheme.AgGridClassName = newTheme.AgGridClassName || getAgGridDarkThemeName();
2607
+ }
2608
+ }
2609
+ if (!newTheme.AgGridClassName) {
2610
+ // default AG Grid to its light theme
2611
+ newTheme.AgGridClassName = getAgGridLightThemeName();
2612
+ }
2613
+ if (container != null) {
2614
+ if (themesToRemove.length) {
2615
+ themesToRemove.forEach((theme) => {
2616
+ if (theme.AgGridClassName) {
2617
+ container.classList.remove(theme.AgGridClassName);
2618
+ }
2619
+ });
2620
+ }
2621
+ // also remove all AG Grid theme class names
2622
+ const agGridClassNamesToRemove = [];
2623
+ container.classList.forEach((x) => {
2624
+ if (x && x.indexOf('ag-theme-') === 0) {
2625
+ agGridClassNamesToRemove.push(x);
2626
+ }
2627
+ });
2628
+ agGridClassNamesToRemove.forEach((x) => container.classList.remove(x));
2629
+ if (newTheme && newTheme.AgGridClassName) {
2630
+ container.classList.add(newTheme.AgGridClassName);
2631
+ }
2632
+ container.classList.add('ab-Grid');
2633
+ if (this.adaptableOptions.columnFilterOptions.indicateFilteredColumns) {
2634
+ container.classList.add('ab-Grid--indicate-filtered-columns');
2635
+ }
2636
+ }
2637
+ // MAC LIKE SCROLLBARS
2638
+ if (this.adaptableOptions.userInterfaceOptions &&
2639
+ this.adaptableOptions.userInterfaceOptions.useCustomMacLikeScrollbars &&
2640
+ (0, getScrollbarSize_1.default)() > 0) {
2641
+ el.classList.add('ab--custom-mac-like-scrollbars');
2642
+ }
2643
+ else {
2644
+ el.classList.remove('ab--custom-mac-like-scrollbars');
2645
+ }
2646
+ }
2647
+ setRowGroupColumns(columnIds) {
2648
+ this.agGridAdapter.getAgGridApi().setRowGroupColumns(columnIds);
2649
+ }
2650
+ getAgGridAllGridColumns() {
2651
+ return this.agGridAdapter.getAgGridApi().getAllGridColumns();
2652
+ }
2653
+ clearRowGroupColumns() {
2654
+ this.agGridAdapter
2655
+ .getAgGridApi()
2656
+ .removeRowGroupColumns(this.agGridAdapter.getAgGridApi().getRowGroupColumns());
2657
+ }
2658
+ expandAllRowGroups() {
2659
+ this.agGridAdapter.getAgGridApi().forEachNode((node) => {
2660
+ if (node.group) {
2661
+ node.expanded = true;
2662
+ }
2663
+ });
2664
+ this.agGridAdapter.getAgGridApi().onGroupExpandedOrCollapsed();
2665
+ }
2666
+ closeAllRowGroups() {
2667
+ this.agGridAdapter.getAgGridApi().forEachNode((node) => {
2668
+ if (node.group) {
2669
+ node.expanded = false;
2670
+ }
2671
+ });
2672
+ this.agGridAdapter.getAgGridApi().onGroupExpandedOrCollapsed();
2673
+ }
2674
+ expandRowGroupsForValues(columnValues) {
2675
+ if (ArrayExtensions_1.default.IsNotNullOrEmpty(columnValues)) {
2676
+ const expandedKeys = columnValues.reduce((acc, key) => {
2677
+ acc[key] = true;
2678
+ return acc;
2679
+ }, {});
2680
+ this.agGridAdapter.getAgGridApi().forEachNode((node) => {
2681
+ if (node.group && !node.expanded) {
2682
+ const nodePath = [];
2683
+ let current = node;
2684
+ while (current) {
2685
+ nodePath.push(current.key);
2686
+ current = current.parent;
2687
+ }
2688
+ const nodeKey = nodePath
2689
+ .filter((x) => !!x)
2690
+ .reverse()
2691
+ .join(GeneralConstants_1.GROUP_PATH_SEPARATOR);
2692
+ if (expandedKeys[nodeKey]) {
2693
+ node.setExpanded(true);
2694
+ }
2695
+ }
2696
+ });
2697
+ this.agGridAdapter.getAgGridApi().onGroupExpandedOrCollapsed();
2698
+ }
2699
+ }
2700
+ getExpandRowGroupsKeys() {
2701
+ let returnValues = [];
2702
+ if (this.api.layoutApi.internalApi.areExpandedRowGroupsSavedInLayouts()) {
2703
+ this.agGridAdapter.getAgGridApi().forEachNode((node) => {
2704
+ if (node.group && node.expanded) {
2705
+ let current = node;
2706
+ const path = [];
2707
+ while (current) {
2708
+ path.push(current.key);
2709
+ current = current.parent;
2710
+ }
2711
+ returnValues.push(path
2712
+ .filter((x) => !!x)
2713
+ .reverse()
2714
+ .join(GeneralConstants_1.GROUP_PATH_SEPARATOR));
2715
+ }
2716
+ });
2717
+ }
2718
+ return returnValues;
2719
+ }
2720
+ getAgGridColumnForColumnId(columnId) {
2721
+ return this.agGridAdapter.getAgGridApi().getColumn(columnId);
2722
+ }
2723
+ getMinMaxCachedValueForColumn(column, minMax) {
2724
+ var _a;
2725
+ const { columnId, dataType } = column;
2726
+ if (dataType !== 'Number') {
2727
+ return undefined;
2728
+ }
2729
+ let value = (_a = this.columnMinMaxValuesCache[columnId]) === null || _a === void 0 ? void 0 : _a[minMax];
2730
+ if (value !== undefined) {
2731
+ return value;
2732
+ }
2733
+ const distinctRawValues = this.api.gridApi.internalApi
2734
+ .getUnsortedDistinctRawValuesForColumn(columnId)
2735
+ .map((item) => item.rawValue);
2736
+ value = minMax === 'min' ? Math.min(...distinctRawValues) : Math.max(...distinctRawValues);
2737
+ this.columnMinMaxValuesCache[columnId] = Object.assign(Object.assign({}, this.columnMinMaxValuesCache[columnId]), { [minMax]: value });
2738
+ return value;
2739
+ }
2740
+ getAgGridRegisteredModules() {
2741
+ return this.agGridAdapter.getRegisteredModules();
2742
+ }
2743
+ destroy(config) {
2744
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10;
2745
+ if ((_a = this.agGridAdapter) === null || _a === void 0 ? void 0 : _a.getAgGridApi()) {
2746
+ this.agGridAdapter
2747
+ .getAgGridApi()
2748
+ .removeEventListener(core_1.Events.EVENT_FIRST_DATA_RENDERED, this.listenerFirstDataRendered);
2749
+ this.agGridAdapter
2750
+ .getAgGridApi()
2751
+ .removeEventListener(core_1.Events.EVENT_COLUMN_PIVOT_MODE_CHANGED, this.listenerPivotModeChanged);
2752
+ this.agGridAdapter
2753
+ .getAgGridApi()
2754
+ .removeEventListener(core_1.Events.EVENT_COLUMN_PIVOT_CHANGED, this.listenerPivotChanged);
2755
+ this.agGridAdapter
2756
+ .getAgGridApi()
2757
+ .removeEventListener(core_1.Events.EVENT_CELL_EDITING_STARTED, this.listenerCellEditingStarted);
2758
+ this.agGridAdapter
2759
+ .getAgGridApi()
2760
+ .removeEventListener(core_1.Events.EVENT_COLUMN_ROW_GROUP_CHANGED, this.listenerColumnRowGroupChanged);
2761
+ this.agGridAdapter
2762
+ .getAgGridApi()
2763
+ .removeEventListener(core_1.Events.EVENT_RANGE_SELECTION_CHANGED, this.listenerRangeSelectionChanged);
2764
+ this.agGridAdapter
2765
+ .getAgGridApi()
2766
+ .removeEventListener(core_1.Events.EVENT_COLUMN_RESIZED, this.listenerColumnResized);
2767
+ this.agGridAdapter
2768
+ .getAgGridApi()
2769
+ .removeEventListener(core_1.Events.EVENT_SORT_CHANGED, this.listenerSortChanged);
2770
+ this.agGridAdapter
2771
+ .getAgGridApi()
2772
+ .removeEventListener(core_1.Events.EVENT_MODEL_UPDATED, this.listenerModelUpdated);
2773
+ this.agGridAdapter.getAgGridApi().removeGlobalListener(this.listenerGlobalSetRowSelection);
2774
+ this.agGridAdapter
2775
+ .getAgGridApi()
2776
+ .removeGlobalListener(this.listenerGlobalColumnEventsThatTriggerStateChange);
2777
+ this.agGridAdapter
2778
+ .getAgGridApi()
2779
+ .removeGlobalListener(this.listenerGlobalColumnEventsThatTriggerAutoLayoutSave);
2780
+ this.agGridAdapter
2781
+ .getAgGridApi()
2782
+ .removeGlobalListener(this.listenerGlobalRowGroupEventsThatTriggerAutoLayoutSave);
2783
+ this.listenerFirstDataRendered = null;
2784
+ this.listenerPivotModeChanged = null;
2785
+ this.listenerPivotChanged = null;
2786
+ this.listenerCellEditingStarted = null;
2787
+ this.listenerColumnRowGroupChanged = null;
2788
+ this.listenerRangeSelectionChanged = null;
2789
+ this.listenerColumnResized = null;
2790
+ this.listenerGlobalSetRowSelection = null;
2791
+ this.listenerSortChanged = null;
2792
+ this.listenerModelUpdated = null;
2793
+ this.listenerGlobalColumnEventsThatTriggerStateChange = null;
2794
+ this.listenerGlobalColumnEventsThatTriggerAutoLayoutSave = null;
2795
+ this.listenerGlobalRowGroupEventsThatTriggerAutoLayoutSave = null;
2796
+ this.throttleFilterOnEditDataChange = null;
2797
+ this.throttleFilterOnTickingDataChange = null;
2798
+ const liveGridOptions = this.agGridAdapter.getLiveGridOptions();
2799
+ if (liveGridOptions) {
2800
+ this.agGridOptionsService.revertGridOptionsPropertiesToUserValue(liveGridOptions, [
2801
+ 'aggFuncs',
2802
+ 'allowContextMenuWithControlKey',
2803
+ 'columnTypes',
2804
+ 'components',
2805
+ 'context',
2806
+ 'dataTypeDefinitions',
2807
+ 'doesExternalFilterPass',
2808
+ 'excelStyles',
2809
+ 'getContextMenuItems',
2810
+ 'getMainMenuItems',
2811
+ 'getRowClass',
2812
+ 'getRowId',
2813
+ 'getRowStyle',
2814
+ 'gridId',
2815
+ 'initialGroupOrderComparator',
2816
+ 'isExternalFilterPresent',
2817
+ 'sideBar',
2818
+ 'statusBar',
2819
+ 'suppressAggFuncInHeader',
2820
+ ]);
2821
+ if (liveGridOptions.components) {
2822
+ liveGridOptions.components.AdaptableToolPanel = null;
2823
+ }
2824
+ }
2825
+ }
2826
+ if (config && config.destroyApi === false) {
2827
+ }
2828
+ else {
2829
+ (_b = this.agGridAdapter.getAgGridApi()) === null || _b === void 0 ? void 0 : _b.destroy();
2830
+ }
2831
+ const gridContainerElement = this.getAgGridContainerElement();
2832
+ if (gridContainerElement) {
2833
+ gridContainerElement.removeEventListener('keydown', this.agGridListenerKeydown);
2834
+ gridContainerElement.removeEventListener('mouseenter', this.agGridListenerMouseEnter);
2835
+ gridContainerElement.removeEventListener('mouseleave', this.agGridListenerMouseLeave);
2836
+ this.agGridListenerKeydown = null;
2837
+ this.agGridListenerMouseEnter = null;
2838
+ this.agGridListenerMouseLeave = null;
2839
+ }
2840
+ this.api.internalDestroySelf();
2841
+ (_c = this.agGridOptionsService) === null || _c === void 0 ? void 0 : _c.destroy();
2842
+ this.agGridOptionsService = null;
2843
+ (_d = this.agGridAdapter) === null || _d === void 0 ? void 0 : _d.destroy();
2844
+ this.agGridAdapter = null;
2845
+ (_e = this.agGridMenuAdapter) === null || _e === void 0 ? void 0 : _e.destroy();
2846
+ this.agGridMenuAdapter = null;
2847
+ (_f = this.agGridColumnAdapter) === null || _f === void 0 ? void 0 : _f.destroy();
2848
+ this.agGridColumnAdapter = null;
2849
+ this.rowListeners = null;
2850
+ this.emitter.destroy();
2851
+ this.emitter = null;
2852
+ this.adaptableOptions = null;
2853
+ this.columnMinMaxValuesCache = null;
2854
+ this.lifecycleState = 'preDestroyed';
2855
+ AdaptableAgGrid.dismissInstance(this);
2856
+ (_g = this.unmountLoadingScreen) === null || _g === void 0 ? void 0 : _g.call(this);
2857
+ this.unmountLoadingScreen = null;
2858
+ const abContainerElement = this.getAdaptableContainerElement();
2859
+ if (config && !config.unmount) {
2860
+ return;
2861
+ }
2862
+ if (abContainerElement != null) {
2863
+ (_h = this.unmountReactRoot) === null || _h === void 0 ? void 0 : _h.call(this);
2864
+ }
2865
+ this.unmountReactRoot = null;
2866
+ this.DANGER_USE_GETTER_adaptableContainerElement = null;
2867
+ this.DANGER_USE_GETTER_agGridContainerElement = null;
2868
+ (_j = this.adaptableStore) === null || _j === void 0 ? void 0 : _j.destroy();
2869
+ this.adaptableStore = null;
2870
+ this.adaptableOptions = null;
2871
+ this.adaptableStatusPanelKeys = null;
2872
+ (_l = (_k = this.CalculatedColumnExpressionService) === null || _k === void 0 ? void 0 : _k.destroy) === null || _l === void 0 ? void 0 : _l.call(_k);
2873
+ this.CalculatedColumnExpressionService = null;
2874
+ (_o = (_m = this.DataService) === null || _m === void 0 ? void 0 : _m.destroy) === null || _o === void 0 ? void 0 : _o.call(_m);
2875
+ this.DataService = null;
2876
+ (_q = (_p = this.EntitlementService) === null || _p === void 0 ? void 0 : _p.destroy) === null || _q === void 0 ? void 0 : _q.call(_p);
2877
+ this.EntitlementService = null;
2878
+ (_s = (_r = this.Fdc3Service) === null || _r === void 0 ? void 0 : _r.destroy) === null || _s === void 0 ? void 0 : _s.call(_r);
2879
+ this.Fdc3Service = null;
2880
+ (_u = (_t = this.ReportService) === null || _t === void 0 ? void 0 : _t.destroy) === null || _u === void 0 ? void 0 : _u.call(_t);
2881
+ this.ReportService = null;
2882
+ (_w = (_v = this.ModuleService) === null || _v === void 0 ? void 0 : _v.destroy) === null || _w === void 0 ? void 0 : _w.call(_v);
2883
+ this.ModuleService = null;
2884
+ (_y = (_x = this.ValidationService) === null || _x === void 0 ? void 0 : _x.destroy) === null || _y === void 0 ? void 0 : _y.call(_x);
2885
+ this.ValidationService = null;
2886
+ (_0 = (_z = this.QueryLanguageService) === null || _z === void 0 ? void 0 : _z.destroy) === null || _0 === void 0 ? void 0 : _0.call(_z);
2887
+ this.QueryLanguageService = null;
2888
+ (_2 = (_1 = this.AlertService) === null || _1 === void 0 ? void 0 : _1.destroy) === null || _2 === void 0 ? void 0 : _2.call(_1);
2889
+ this.AlertService = null;
2890
+ (_4 = (_3 = this.TeamSharingService) === null || _3 === void 0 ? void 0 : _3.destroy) === null || _4 === void 0 ? void 0 : _4.call(_3);
2891
+ this.TeamSharingService = null;
2892
+ (_6 = (_5 = this.RowEditService) === null || _5 === void 0 ? void 0 : _5.destroy) === null || _6 === void 0 ? void 0 : _6.call(_5);
2893
+ this.RowEditService = null;
2894
+ (_8 = (_7 = this.MetamodelService) === null || _7 === void 0 ? void 0 : _7.destroy) === null || _8 === void 0 ? void 0 : _8.call(_7);
2895
+ this.MetamodelService = null;
2896
+ (_10 = (_9 = this.LicenseService) === null || _9 === void 0 ? void 0 : _9.destroy) === null || _10 === void 0 ? void 0 : _10.call(_9);
2897
+ this.LicenseService = null;
2898
+ }
2899
+ canExportToExcel() {
2900
+ return this.agGridAdapter.isModulePresent(core_1.ModuleNames.ExcelExportModule);
2901
+ }
2902
+ exportToExcel(reportData, fileName) {
2903
+ const columnDefs = reportData.columns.map((column) => ({
2904
+ field: column.columnId,
2905
+ headerName: column.friendlyName,
2906
+ }));
2907
+ const NESTED_COL_SEPARATOR = '.';
2908
+ const nestedColumns = reportData.columns.filter((column) => column.columnId.includes(NESTED_COL_SEPARATOR));
2909
+ if (nestedColumns.length) {
2910
+ // the rowData of nested fields (containing dots) was flattened during the report data extraction and we need to un-flatten it back
2911
+ // ex.
2912
+ // current state: { field: 'outerKey.innerKey', value: 2}
2913
+ // original (desired) state: { field: 'outerKey.innerKey', value: {outerKey: {innerKey: 2}}}
2914
+ reportData.rows.forEach((rowDataEntry) => nestedColumns.forEach((nestedColumn) => {
2915
+ const cellExportValue = rowDataEntry[nestedColumn.columnId];
2916
+ let intermediaryValue = rowDataEntry;
2917
+ // augment the rowDataEntry with the new object
2918
+ nestedColumn.columnId
2919
+ .split(NESTED_COL_SEPARATOR)
2920
+ .forEach((nestedKey, index, nestedCols) => {
2921
+ // we reached the leaf node, so we set the cell value and break
2922
+ if (index === nestedCols.length - 1) {
2923
+ intermediaryValue[nestedKey] = cellExportValue;
2924
+ return;
2925
+ }
2926
+ if (intermediaryValue[nestedKey] == undefined) {
2927
+ intermediaryValue[nestedKey] = {};
2928
+ } // else means that the object already has a property with this key
2929
+ intermediaryValue = intermediaryValue[nestedKey];
2930
+ });
2931
+ // delete the obsolete flattened property
2932
+ delete rowDataEntry[nestedColumn.columnId];
2933
+ }));
2934
+ }
2935
+ const gridOptions = {
2936
+ columnDefs,
2937
+ rowData: reportData.rows,
2938
+ };
2939
+ let gridParams = { modules: this.getAgGridRegisteredModules() };
2940
+ const ephemeralGridApi = (0, core_1.createGrid)(document.createElement('div'), gridOptions, gridParams);
2941
+ ephemeralGridApi.exportDataAsExcel({
2942
+ sheetName: 'Sheet 1',
2943
+ fileName: fileName,
2944
+ });
2945
+ ephemeralGridApi.destroy();
2946
+ }
2947
+ exportVisualDataToExcel() {
2948
+ // // add adaptable style props to user defined props
2949
+ // this.setExcelStylesForExport();
2950
+ //
2951
+ // this.gridOptions.api.exportDataAsExcel({
2952
+ // sheetName: 'Sheet 1',
2953
+ // fileName: this.ReportService.getReportFileName(this.adaptableOptions.adaptableId, 'Excel'),
2954
+ // // delegate the cell value processing to Adaptable
2955
+ // processCellCallback: ({ node, column, value }: ProcessCellForExportParams): string => {
2956
+ // const columnId = column.getColId();
2957
+ // if (
2958
+ // node?.group &&
2959
+ // (this.api.columnApi.isAutoRowGroupColumn(columnId) ||
2960
+ // // we would still need to process the cell if this is a group row with an aggregated value
2961
+ // node?.aggData?.[columnId] == undefined)
2962
+ // ) {
2963
+ // // skip processing of row groups, this was already handled in processRowGroupCallback()
2964
+ // return value;
2965
+ // }
2966
+ // return this.processCellForExcelExport(node, columnId);
2967
+ // },
2968
+ // processRowGroupCallback: (params: ProcessRowGroupForExportParams): string => {
2969
+ // // recreating the standard AG Grid styling for row groups: 'Parent -> Child'
2970
+ // // additionally the values are formatted
2971
+ // let rowGroupNode = params.node;
2972
+ // const isFooterRow = rowGroupNode.footer;
2973
+ // const rowGroupSummary = [this.processRowGroupForExcelExport(rowGroupNode) ?? ''];
2974
+ // while (rowGroupNode.parent) {
2975
+ // rowGroupNode = rowGroupNode.parent;
2976
+ // const formattedParentNode = this.processRowGroupForExcelExport(rowGroupNode);
2977
+ // if (formattedParentNode) {
2978
+ // rowGroupSummary.push(formattedParentNode);
2979
+ // }
2980
+ // }
2981
+ //
2982
+ // let summary = rowGroupSummary.reverse().join(' -> ');
2983
+ // if (isFooterRow) {
2984
+ // summary = `Total: ${summary}`;
2985
+ // }
2986
+ // return summary;
2987
+ // },
2988
+ // });
2989
+ //
2990
+ // // keep only the user defined props
2991
+ // this.setGridOptionsProperty('excelStyles', (userExcelStyles) => {
2992
+ // return userExcelStyles;
2993
+ // });
2994
+ }
2995
+ isQuickFilterAvailable() {
2996
+ return this.hasFloatingFilterOnAtLeastOneColumn(this.agGridAdapter.getAgGridApi().getColumnDefs());
2997
+ }
2998
+ hasFloatingFilterOnAtLeastOneColumn(columnDefs) {
2999
+ let col;
3000
+ for (col of columnDefs) {
3001
+ if (col.floatingFilter) {
3002
+ return true;
3003
+ }
3004
+ if (col.children) {
3005
+ if (this.hasFloatingFilterOnAtLeastOneColumn(col.children)) {
3006
+ return true;
3007
+ }
3008
+ }
3009
+ }
3010
+ return false;
3011
+ }
3012
+ getChartRef(chartId) {
3013
+ return this.agGridAdapter.getAgGridApi().getChartRef(chartId);
3014
+ }
3015
+ setLayout(layout) {
3016
+ var _a, _b, _c, _d, _e, _f;
3017
+ if (!layout) {
3018
+ layout = this.api.layoutApi.getCurrentLayout();
3019
+ }
3020
+ const perfSetLayout = this.logger.beginPerf(`setLayout(${layout.Name})`);
3021
+ layout.Columns = layout.Columns || [];
3022
+ const actionRowColumn = this.api.actionRowApi.internalApi.getColDefsForActionRowColumns()[0];
3023
+ if (actionRowColumn) {
3024
+ layout.Columns.push(actionRowColumn.colId);
3025
+ layout.PinnedColumnsMap = layout.PinnedColumnsMap || {};
3026
+ layout.PinnedColumnsMap[actionRowColumn.colId] = actionRowColumn.pinned;
3027
+ }
3028
+ const layoutColumnsMap = layout.Columns.reduce((acc, colId) => {
3029
+ acc[colId] = true;
3030
+ return acc;
3031
+ }, {});
3032
+ const columnsState = this.agGridAdapter.getAgGridApi().getColumnState();
3033
+ const columnsStateIndexes = {};
3034
+ const columnsStateMap = columnsState.reduce((acc, colState, index) => {
3035
+ columnsStateIndexes[colState.colId] = index;
3036
+ acc[colState.colId] = colState;
3037
+ return acc;
3038
+ }, {});
3039
+ let sortIndex = 0;
3040
+ const sortModelMap = ((_a = layout.ColumnSorts) !== null && _a !== void 0 ? _a : []).reduce((acc, customSort) => {
3041
+ const colId = customSort.ColumnId;
3042
+ acc[colId] = {
3043
+ colId,
3044
+ sort: customSort.SortOrder === 'Asc' ? 'asc' : 'desc',
3045
+ sortIndex,
3046
+ };
3047
+ sortIndex++;
3048
+ return acc;
3049
+ }, {});
3050
+ const groupedColumnsIndexesMap = (layout.RowGroupedColumns || []).reduce((acc, colId, index) => {
3051
+ acc[colId] = index;
3052
+ return acc;
3053
+ }, {});
3054
+ let pivotedColumnsIndexesMap = {};
3055
+ const aggregationFunctionsColumnsMap = layout.AggregationColumns || {};
3056
+ const columnsToShow = !layout.EnablePivot
3057
+ ? layout.Columns
3058
+ : ((_b = this.agGridAdapter
3059
+ .getAgGridApi()
3060
+ .getPivotResultColumns()) === null || _b === void 0 ? void 0 : _b.map((column) => column.getColId())) || [];
3061
+ let isChanged = false;
3062
+ const colsToAutoSize = {};
3063
+ let newColumnsState = this.getSortedColumnStateForVisibleColumns(columnsToShow, columnsState);
3064
+ newColumnsState = newColumnsState
3065
+ .map((colState) => {
3066
+ var _a, _b, _c;
3067
+ const { colId } = colState;
3068
+ const oldColState = columnsStateMap[colId];
3069
+ const hide = this.api.columnApi.isAutoPivotColumn(colId)
3070
+ ? colState.hide
3071
+ : !layoutColumnsMap[colId];
3072
+ const newColState = Object.assign(Object.assign({}, oldColState), { hide });
3073
+ if (layout.ColumnWidthMap && layout.ColumnWidthMap[colId] != null) {
3074
+ newColState.width = layout.ColumnWidthMap[colId];
3075
+ }
3076
+ else if (!hide) {
3077
+ // autosize only the columns which are part of the selected layout
3078
+ colsToAutoSize[colId] = true;
3079
+ }
3080
+ if (actionRowColumn && actionRowColumn.colId === colId) {
3081
+ newColState.width = actionRowColumn.width;
3082
+ }
3083
+ newColState.rowGroupIndex =
3084
+ groupedColumnsIndexesMap[colId] != null ? groupedColumnsIndexesMap[colId] : null;
3085
+ const previousRowGroup = newColState.rowGroup;
3086
+ newColState.rowGroup = newColState.rowGroupIndex != null;
3087
+ if (!previousRowGroup && newColState.rowGroup) {
3088
+ this.agGridColumnAdapter.triggerSetupColumnKeyCreator(colId);
3089
+ }
3090
+ const normalizePinned = (pinnedValue) => {
3091
+ if (typeof pinnedValue === 'string') {
3092
+ return pinnedValue;
3093
+ }
3094
+ return pinnedValue == true ? 'left' : !!pinnedValue;
3095
+ };
3096
+ const newValuePinned = normalizePinned(layout.PinnedColumnsMap ? layout.PinnedColumnsMap[colId] : false);
3097
+ const stateValuePinned = normalizePinned(newColState.pinned);
3098
+ if (newValuePinned !== stateValuePinned) {
3099
+ newColState.pinned = newValuePinned;
3100
+ }
3101
+ newColState.pivotIndex = null;
3102
+ if (pivotedColumnsIndexesMap[colId] != null) {
3103
+ newColState.pivotIndex = pivotedColumnsIndexesMap[colId];
3104
+ }
3105
+ newColState.aggFunc = null;
3106
+ if (aggregationFunctionsColumnsMap[colId] != null) {
3107
+ const colDef = this.agGridAdapter.getAgGridApi().getColumnDef(colId);
3108
+ let aggFunc = null;
3109
+ const aggFuncFromLayout = aggregationFunctionsColumnsMap[colId];
3110
+ const adaptableAggFunc = this.getActiveAdaptableAggFuncForCol(colId);
3111
+ if (aggFuncFromLayout === true) {
3112
+ // if we have true, it means - take the default aggFunc from colDef
3113
+ // NOTE: colState gives us the current aggFunc, which can be null,
3114
+ // while the colDef gives us the initially configured aggFunc for that column
3115
+ aggFunc =
3116
+ (_c = (_b = (_a = colState.aggFunc) !== null && _a !== void 0 ? _a : colDef === null || colDef === void 0 ? void 0 : colDef.aggFunc) !== null && _b !== void 0 ? _b :
3117
+ // @ts-ignore available only wth ag-Grid v27.3.x
3118
+ colDef === null || colDef === void 0 ? void 0 : colDef.defaultAggFunc) !== null && _c !== void 0 ? _c : 'sum';
3119
+ }
3120
+ else if (adaptableAggFunc && adaptableAggFunc.type === 'weightedAverage') {
3121
+ aggFunc = AggregationColumns_1.WEIGHTED_AVERAGE_AGG_FN_NAME;
3122
+ }
3123
+ else if (typeof aggFuncFromLayout === 'string') {
3124
+ aggFunc = aggFuncFromLayout;
3125
+ }
3126
+ newColState.aggFunc = aggFunc;
3127
+ }
3128
+ if (sortModelMap[colId]) {
3129
+ newColState.sort = sortModelMap[colId].sort;
3130
+ newColState.sortIndex = sortModelMap[colId].sortIndex;
3131
+ }
3132
+ else {
3133
+ newColState.sort = null;
3134
+ newColState.sortIndex = null;
3135
+ }
3136
+ isChanged = isChanged || !(0, isEqual_1.default)(newColState, oldColState);
3137
+ return newColState;
3138
+ })
3139
+ .filter((x) => !!x);
3140
+ if (!isChanged) {
3141
+ // order changed
3142
+ const toString = (c) => `${c.colId}-${c.rowGroupIndex}-${c.pivotIndex}-${c.aggFunc}-${c.pinned}-${c.width}-${c.hide}`;
3143
+ const oldColStateString = columnsState.map(toString).join(',');
3144
+ const newColStateString = newColumnsState.map(toString).join(',');
3145
+ isChanged = newColStateString != oldColStateString;
3146
+ }
3147
+ const pivoted = !!layout.EnablePivot;
3148
+ const shouldUpdatePivoted = this.agGridAdapter.getAgGridApi().isPivotMode() !== pivoted;
3149
+ /**
3150
+ * Pivot columns are secondary columns that are created on the fly and base
3151
+ * their configuration on the main columns by copying that configuration.
3152
+ * Because they copy the colDefs they might have an old copy of the colldefs.
3153
+ * This is why when the layout is pivoted we need to set columns before pivoting is applied.
3154
+ * e.g. {
3155
+ * field: 'pivot-1',
3156
+ * pivotValueColumn: {
3157
+ * colDef: {
3158
+ * field: 'price',
3159
+ * // this is a copy of the original column
3160
+ * }
3161
+ * }
3162
+ *
3163
+ */
3164
+ if (shouldUpdatePivoted) {
3165
+ this.updateColumnModelAndRefreshGrid();
3166
+ }
3167
+ isChanged = isChanged || shouldUpdatePivoted;
3168
+ let shouldUpdateHeaders = false;
3169
+ // update the header name for all columns
3170
+ // there should be a simpler solution for this, once the Layout Management is refactored
3171
+ this.agGridAdapter
3172
+ .getAgGridApi()
3173
+ .getColumns()
3174
+ .forEach((col) => {
3175
+ const colDef = col.getColDef();
3176
+ const colId = col.getColId();
3177
+ const abColumn = this.api.columnApi.getColumnWithColumnId(colId);
3178
+ const colSetupInfo = {
3179
+ col,
3180
+ colDef,
3181
+ colId,
3182
+ abColumn,
3183
+ };
3184
+ shouldUpdateHeaders =
3185
+ this.agGridColumnAdapter.setupColumnHeader(colSetupInfo) || shouldUpdateHeaders;
3186
+ });
3187
+ isChanged = isChanged || shouldUpdateHeaders;
3188
+ if (isChanged) {
3189
+ // it's important we set pivot mode
3190
+ // before we set column state
3191
+ // as otherwise column order is not preserved properly when
3192
+ // going from pivoted to unpivoted layout
3193
+ if (shouldUpdatePivoted) {
3194
+ this.agGridAdapter.getAgGridApi().setPivotMode(pivoted);
3195
+ }
3196
+ const perfApplyColumnState = this.logger.beginPerf('applyColumnState (layout.isChanged)');
3197
+ this.agGridAdapter.getAgGridApi().applyColumnState({
3198
+ state: newColumnsState,
3199
+ applyOrder: true,
3200
+ });
3201
+ this.applyGroupColumnWidth(layout);
3202
+ perfApplyColumnState.end();
3203
+ this.api.gridApi.setColumnSorts(layout.ColumnSorts);
3204
+ this.agGridAdapter.getAgGridApi().setPivotColumns(layout.PivotColumns || []);
3205
+ // aggrid 25.1.0 introduced a bug such that a layout that has a grouped column, if the column has enableRowGroup: true but not rowGroup: true
3206
+ // the group column is not possitioned correctly at the start of the layout
3207
+ // see the test in layout/layout-switch/"should be able to switch from grouped to non-grouped and back"
3208
+ // so we figured out the following line fixes the issue
3209
+ // this.gridOptions.api.setColumnDefs(this.gridOptions.api.getColumnDefs()); //TODO find a solution for weighted averages - column floating filters are not showing
3210
+ // these updates need to be at the end, the methods are based on the grid state/col defs
3211
+ // the layout needs to be applied for them to work
3212
+ this.updateRowGroupsExpandedState(layout);
3213
+ }
3214
+ const colsToAutoSizeArray = Object.keys(colsToAutoSize);
3215
+ if (pivoted && ((_d = (_c = this.adaptableOptions) === null || _c === void 0 ? void 0 : _c.layoutOptions) === null || _d === void 0 ? void 0 : _d.autoSizeColumnsInPivotLayout)) {
3216
+ // when a pivoted layout loads, autosize all cols
3217
+ requestAnimationFrame(() => {
3218
+ this.agGridAdapter.getAgGridApi().autoSizeAllColumns();
3219
+ });
3220
+ //but if it's also the first time the grid is loading
3221
+ //it's not timely enough the above call, so we keep trying... I know it's ugly, we need to find a better way
3222
+ setTimeout(() => {
3223
+ this.agGridAdapter.getAgGridApi().autoSizeAllColumns();
3224
+ setTimeout(() => {
3225
+ this.agGridAdapter.getAgGridApi().autoSizeAllColumns();
3226
+ }, 200);
3227
+ }, 100);
3228
+ }
3229
+ else if (((_f = (_e = this.adaptableOptions) === null || _e === void 0 ? void 0 : _e.layoutOptions) === null || _f === void 0 ? void 0 : _f.autoSizeColumnsInLayout) &&
3230
+ colsToAutoSizeArray.length) {
3231
+ this.agGridAdapter.getAgGridApi().autoSizeColumns(colsToAutoSizeArray);
3232
+ }
3233
+ this.forPlugins((plugin) => {
3234
+ if (plugin.afterSetLayout) {
3235
+ plugin.afterSetLayout(this, layout);
3236
+ }
3237
+ });
3238
+ perfSetLayout.end();
3239
+ }
3240
+ getActiveAdaptableAggFuncForCol(columnId) {
3241
+ if (!columnId) {
3242
+ return null;
3243
+ }
3244
+ const currentLayout = this.api.layoutApi.getCurrentLayout();
3245
+ const aggregationFunctionsColumnsMap = currentLayout.AggregationColumns || {};
3246
+ const adaptableAggFunc = aggregationFunctionsColumnsMap[columnId];
3247
+ if (typeof adaptableAggFunc === 'object' &&
3248
+ 'type' in adaptableAggFunc &&
3249
+ adaptableAggFunc.type === 'weightedAverage') {
3250
+ return adaptableAggFunc;
3251
+ }
3252
+ return null;
3253
+ }
3254
+ /**
3255
+ * Setting layout works by modifing the column state.
3256
+ * The column state is based on the current existing columns.
3257
+ * At this point the column groups do not exist, and the widths from layout are not applied.
3258
+ *
3259
+ * After the col sate is applied and the column groups are created we need
3260
+ * to apply the state again to update the widths of the group columns.
3261
+ */
3262
+ applyGroupColumnWidth(layout) {
3263
+ if (!layout.RowGroupedColumns || !layout.RowGroupedColumns.length) {
3264
+ return;
3265
+ }
3266
+ const groupColumnWithDifferentWidths = this.agGridAdapter
3267
+ .getAgGridApi()
3268
+ .getColumnState()
3269
+ .reduce((acc, col) => {
3270
+ var _a;
3271
+ if (this.api.columnApi.isAutoRowGroupColumn(col.colId)) {
3272
+ const widthInLayout = (_a = layout.ColumnWidthMap) === null || _a === void 0 ? void 0 : _a[col.colId];
3273
+ if (widthInLayout && widthInLayout !== col.width) {
3274
+ acc.push(Object.assign(Object.assign({}, col), { width: widthInLayout }));
3275
+ }
3276
+ }
3277
+ return acc;
3278
+ }, []);
3279
+ if (groupColumnWithDifferentWidths.length === 0) {
3280
+ return;
3281
+ }
3282
+ this.agGridAdapter.getAgGridApi().applyColumnState({
3283
+ state: groupColumnWithDifferentWidths,
3284
+ });
3285
+ }
3286
+ onRowDataChanged({ rowNode, oldData, newData, }) {
3287
+ if (oldData == null || oldData == undefined) {
3288
+ return;
3289
+ }
3290
+ if (oldData == newData) {
3291
+ return;
3292
+ }
3293
+ const primaryKeyValue = this.getPrimaryKeyValueFromRowNode(rowNode);
3294
+ if (!primaryKeyValue) {
3295
+ return;
3296
+ }
3297
+ // rowNode = this.getRowNodeForPrimaryKey(primaryKeyValue);
3298
+ let cellDataChangedInfos = [];
3299
+ Object.keys(oldData).forEach((key) => {
3300
+ if (this.api.columnApi.isColumnInGrid(key)) {
3301
+ const oldValue = oldData[key];
3302
+ const newValue = newData[key];
3303
+ if (oldValue != newValue) {
3304
+ const cellDataChangedInfo = this.api.internalApi.buildDataChangedInfo({
3305
+ oldValue: oldValue,
3306
+ newValue: newValue,
3307
+ column: this.api.columnApi.getColumnWithColumnId(key),
3308
+ primaryKeyValue: primaryKeyValue,
3309
+ rowNode: rowNode,
3310
+ trigger: 'tick',
3311
+ });
3312
+ if (this.isUndoChange(cellDataChangedInfo)) {
3313
+ cellDataChangedInfo.trigger = 'undo';
3314
+ }
3315
+ cellDataChangedInfos.push(cellDataChangedInfo);
3316
+ }
3317
+ }
3318
+ });
3319
+ this.performPostEditChecks(cellDataChangedInfos);
3320
+ }
3321
+ onCellDataChanged({ rowNode, oldValue, newValue, colId, }) {
3322
+ if (oldValue == newValue) {
3323
+ return;
3324
+ }
3325
+ const abColumn = this.api.columnApi.getColumnWithColumnId(colId);
3326
+ if (!abColumn) {
3327
+ return;
3328
+ }
3329
+ if (this.isGroupRowNode(rowNode)) {
3330
+ const cellDataChangedInfo = this.api.internalApi.buildDataChangedInfo({
3331
+ oldValue: oldValue,
3332
+ newValue: newValue,
3333
+ column: abColumn,
3334
+ /**
3335
+ * A grouped row does not have an underling data item.
3336
+ * Because of this we use the rowNode.id as an identifier.
3337
+ */
3338
+ primaryKeyValue: rowNode.id,
3339
+ rowNode: rowNode,
3340
+ trigger: 'aggChange',
3341
+ });
3342
+ this.DataService.CreateDataChangedEvent(cellDataChangedInfo);
3343
+ return;
3344
+ }
3345
+ const primaryKeyValue = this.getPrimaryKeyValueFromRowNode(rowNode);
3346
+ if (!primaryKeyValue) {
3347
+ return;
3348
+ }
3349
+ const cellDataChangedInfo = this.api.internalApi.buildDataChangedInfo({
3350
+ oldValue: oldValue,
3351
+ newValue: newValue,
3352
+ column: abColumn,
3353
+ primaryKeyValue: primaryKeyValue,
3354
+ rowNode: rowNode,
3355
+ trigger: 'edit',
3356
+ });
3357
+ if (this.isUndoChange(cellDataChangedInfo)) {
3358
+ cellDataChangedInfo.trigger = 'undo';
3359
+ }
3360
+ this.performPostEditChecks([cellDataChangedInfo]);
3361
+ }
3362
+ isUndoChange(dataChange) {
3363
+ // check if this is not a reverted change
3364
+ const undoChange = this.api.internalApi.getDataService().extractUndoChange(dataChange);
3365
+ return !!undoChange;
3366
+ }
3367
+ /**
3368
+ * There are a few things that we need to do AFTER we edit a cell and it makes sense to put them in one place
3369
+ */
3370
+ performPostEditChecks(cellDataChangedInfos) {
3371
+ const firstInfo = cellDataChangedInfos[0];
3372
+ if (!firstInfo || !firstInfo.rowNode) {
3373
+ return;
3374
+ }
3375
+ cellDataChangedInfos.forEach((cellDataChangedInfo) => {
3376
+ if (cellDataChangedInfo.trigger === 'undo') {
3377
+ this.logger.info(`Undo data change: PK(${cellDataChangedInfo.primaryKeyValue}) Col(${cellDataChangedInfo.column}) RevertedValue(${cellDataChangedInfo.oldValue}) OriginalValue(${cellDataChangedInfo.newValue})`);
3378
+ }
3379
+ if (cellDataChangedInfo.trigger === 'edit' || cellDataChangedInfo.trigger === 'undo') {
3380
+ this.checkChangedCellCurrentlySelected(cellDataChangedInfo);
3381
+ this.api.freeTextColumnApi.internalApi.handleFreeTextColumnDataChange(cellDataChangedInfo);
3382
+ }
3383
+ this.DataService.CreateDataChangedEvent(cellDataChangedInfo);
3384
+ this.resetMinMaxCachedValueForColumn(cellDataChangedInfo.column);
3385
+ });
3386
+ this.refreshCellsBasedOnCellDataChange(cellDataChangedInfos);
3387
+ firstInfo.trigger == 'tick' ? this.filterOnTickingDataChange() : this.filterOnEditDataChange();
3388
+ }
3389
+ refreshCellsBasedOnCellDataChange(cellDataChangedInfos) {
3390
+ const [firstInfo] = cellDataChangedInfos;
3391
+ // if node is visible then check if need to refresh other columns / whole row if the updating column is:
3392
+ // 1. referenced in Format Column Styles that have Expressions (refreshing whole row if Scope is All)
3393
+ // 2. referenced in Format Column styles that use Column Comparisons (which might also be calculated columns)
3394
+ if (this.agGridAdapter.isVisibleNode(firstInfo.rowNode)) {
3395
+ let dataChangedScope = {
3396
+ wholeRow: false,
3397
+ columnIds: new Set(),
3398
+ };
3399
+ this.getFormatColumnExpressionStylesChanges(dataChangedScope, cellDataChangedInfos);
3400
+ if (dataChangedScope.wholeRow === false) {
3401
+ this.getFormatColumnPredicateStyleChanges(dataChangedScope, cellDataChangedInfos);
3402
+ }
3403
+ if (dataChangedScope.wholeRow) {
3404
+ this.redrawRow(firstInfo.rowNode);
3405
+ }
3406
+ else {
3407
+ this.getStyledColumnComparisonChanges(dataChangedScope, cellDataChangedInfos);
3408
+ if (dataChangedScope.columnIds.size > 0) {
3409
+ this.refreshCells([firstInfo.rowNode], Array.from(dataChangedScope.columnIds.values()), true);
3410
+ }
3411
+ }
3412
+ }
3413
+ this.refreshColumnForRelativeRangeStyledColumns(cellDataChangedInfos);
3414
+ }
3415
+ refreshColumnForRelativeRangeStyledColumns(cellDataChangedInfos) {
3416
+ const columnIdMap = new Set();
3417
+ cellDataChangedInfos.forEach((cellDataChangeInfo) => {
3418
+ const styledColumn = this.api.styledColumnApi.getActiveStyledColumnForColumn(cellDataChangeInfo.column);
3419
+ if (styledColumn &&
3420
+ this.api.styledColumnApi.internalApi.hasStyledColumnRelativeCellRange(styledColumn)) {
3421
+ columnIdMap.add(styledColumn.ColumnId);
3422
+ }
3423
+ });
3424
+ const columnIdsToUpdate = [...columnIdMap];
3425
+ if (columnIdsToUpdate.length) {
3426
+ this.refreshColumns(columnIdsToUpdate, true);
3427
+ }
3428
+ }
3429
+ getStyledColumnComparisonChanges(dataChangedScope, cellDataChangedInfos) {
3430
+ this.api.styledColumnApi.getStyledColumns().forEach((sc) => {
3431
+ let columnComparison = this.api.styledColumnApi.internalApi.getColumnComparisonForStyledColumn(sc);
3432
+ if (columnComparison) {
3433
+ let affectedColumnIds = this.api.styledColumnApi.internalApi.getColumnIdsFromColumnComparison(columnComparison);
3434
+ if (ArrayExtensions_1.default.IsNotNullOrEmpty(affectedColumnIds)) {
3435
+ cellDataChangedInfos.forEach((cellDataChangedInfo) => {
3436
+ if (affectedColumnIds.includes(cellDataChangedInfo.column.columnId)) {
3437
+ dataChangedScope.columnIds.add(sc.ColumnId);
3438
+ }
3439
+ });
3440
+ }
3441
+ }
3442
+ });
3443
+ }
3444
+ getFormatColumnPredicateStyleChanges(dataChangedScope, cellDataChangedInfos) {
3445
+ cellDataChangedInfos.forEach((cellDataChangeInfo) => {
3446
+ const dependentColumns = this.api.formatColumnApi.internalApi.getFormatColumnColumnsDependentOnColumnChange(cellDataChangeInfo.column);
3447
+ for (let colId of dependentColumns) {
3448
+ dataChangedScope.columnIds.add(colId);
3449
+ }
3450
+ });
3451
+ }
3452
+ getFormatColumnExpressionStylesChanges(dataChangedScope, cellDataChangedInfos) {
3453
+ const formatColumnsWithExpression = [];
3454
+ formatColumnsWithExpression.push(...this.api.formatColumnApi.internalApi.getFormatColumnsWithExpression());
3455
+ if (ArrayExtensions_1.default.IsNullOrEmpty(formatColumnsWithExpression)) {
3456
+ return;
3457
+ }
3458
+ cellDataChangedInfos.forEach((cellDataChangedInfo) => {
3459
+ if (!dataChangedScope.wholeRow) {
3460
+ formatColumnsWithExpression.forEach((styleModule) => {
3461
+ if (!dataChangedScope.wholeRow) {
3462
+ const columnIds = this.api.expressionApi.getColumnsFromExpression(styleModule.Rule.BooleanExpression);
3463
+ if (columnIds.includes(cellDataChangedInfo.column.columnId)) {
3464
+ if (this.api.scopeApi.scopeIsAll(styleModule.Scope)) {
3465
+ dataChangedScope.wholeRow = true;
3466
+ return;
3467
+ }
3468
+ else {
3469
+ this.api.scopeApi
3470
+ .getColumnsForScope(styleModule.Scope)
3471
+ .map((c) => c.columnId)
3472
+ .forEach((colId) => {
3473
+ dataChangedScope.columnIds.add(colId);
3474
+ });
3475
+ }
3476
+ }
3477
+ }
3478
+ });
3479
+ }
3480
+ });
3481
+ }
3482
+ checkChangedCellCurrentlySelected(cellDataChangedInfo) {
3483
+ let selectedCellInfo = this.api.gridApi.getSelectedCellInfo();
3484
+ if (selectedCellInfo && ArrayExtensions_1.default.IsNotNullOrEmpty(selectedCellInfo.gridCells)) {
3485
+ let matchingCell = selectedCellInfo.gridCells.find((gc) => gc.primaryKeyValue == cellDataChangedInfo.primaryKeyValue &&
3486
+ gc.column == cellDataChangedInfo.column);
3487
+ if (matchingCell) {
3488
+ this.refreshSelectedCellsState();
3489
+ }
3490
+ }
3491
+ let selectedRowInfo = this.api.gridApi.getSelectedRowInfo();
3492
+ if (selectedRowInfo && ArrayExtensions_1.default.IsNotNullOrEmpty(selectedRowInfo.gridRows)) {
3493
+ let matchingRow = selectedRowInfo.gridRows.find((gr) => gr.primaryKeyValue == cellDataChangedInfo.primaryKeyValue);
3494
+ if (matchingRow) {
3495
+ this.refreshSelectedRowsState();
3496
+ }
3497
+ }
3498
+ }
3499
+ resetMinMaxCachedValueForColumn(column) {
3500
+ if (!column) {
3501
+ this.columnMinMaxValuesCache[column.columnId] = {};
3502
+ }
3503
+ if (this.columnMinMaxValuesCache[column.columnId]) {
3504
+ this.columnMinMaxValuesCache[column.columnId] = undefined;
3505
+ }
3506
+ }
3507
+ filterOnTickingDataChange() {
3508
+ var _a;
3509
+ if (this.adaptableOptions.columnFilterOptions.filterActionOnExternalDataChange.applyFilter ==
3510
+ Enums_1.FilterOnDataChangeOptions.Always) {
3511
+ (_a = this.agGridAdapter.getAgGridApi()) === null || _a === void 0 ? void 0 : _a.onFilterChanged();
3512
+ }
3513
+ else if (this.adaptableOptions.columnFilterOptions.filterActionOnExternalDataChange.applyFilter ==
3514
+ Enums_1.FilterOnDataChangeOptions.Throttle) {
3515
+ this.throttleFilterOnTickingDataChange();
3516
+ }
3517
+ }
3518
+ filterOnEditDataChange() {
3519
+ var _a;
3520
+ if (this.adaptableOptions.columnFilterOptions.filterActionOnUserDataChange.applyFilter ==
3521
+ Enums_1.FilterOnDataChangeOptions.Always) {
3522
+ (_a = this.agGridAdapter.getAgGridApi()) === null || _a === void 0 ? void 0 : _a.onFilterChanged();
3523
+ }
3524
+ else if (this.adaptableOptions.columnFilterOptions.filterActionOnUserDataChange.applyFilter ==
3525
+ Enums_1.FilterOnDataChangeOptions.Throttle) {
3526
+ this.throttleFilterOnEditDataChange();
3527
+ }
3528
+ }
3529
+ shouldCreateDefaultLayout(adaptableState, adaptableOptions) {
3530
+ var _a, _b, _c;
3531
+ const layoutState = adaptableState.Layout || {};
3532
+ if (((_a = adaptableOptions.layoutOptions) === null || _a === void 0 ? void 0 : _a.createDefaultLayout) &&
3533
+ !((_b = layoutState.Layouts) === null || _b === void 0 ? void 0 : _b.find((layout) => layout.Name === GeneralConstants_1.DEFAULT_LAYOUT))) {
3534
+ return true;
3535
+ }
3536
+ return !((_c = layoutState.Layouts) === null || _c === void 0 ? void 0 : _c.length);
3537
+ }
3538
+ createDefaultLayout(state, gridOptionsColDefs) {
3539
+ var _a, _b;
3540
+ const allColumnDefs = this.agGridAdapter.getFlattenedColDefs(gridOptionsColDefs);
3541
+ const defaultLayout = ObjectFactory_1.default.CreateEmptyLayout({
3542
+ Name: GeneralConstants_1.DEFAULT_LAYOUT,
3543
+ Columns: allColumnDefs.map((c) => c.colId),
3544
+ AggregationColumns: allColumnDefs.reduce((acc, col) => {
3545
+ if (typeof col.aggFunc === 'string') {
3546
+ acc[col.colId] = col.aggFunc;
3547
+ }
3548
+ return acc;
3549
+ }, {}),
3550
+ PinnedColumnsMap: allColumnDefs.reduce((acc, col) => {
3551
+ const pinned = col.pinned;
3552
+ if (pinned) {
3553
+ acc[col.colId] = pinned === true ? 'left' : pinned;
3554
+ }
3555
+ return acc;
3556
+ }, {}),
3557
+ RowGroupedColumns: allColumnDefs.reduce((acc, col) => {
3558
+ if (col.rowGroup) {
3559
+ acc.push(col.colId);
3560
+ }
3561
+ return acc;
3562
+ }, []),
3563
+ });
3564
+ // ADD special columns
3565
+ const calculatedColumns = ((_a = state.CalculatedColumn) === null || _a === void 0 ? void 0 : _a.CalculatedColumns) || [];
3566
+ if (calculatedColumns.length) {
3567
+ defaultLayout.Columns.push(...calculatedColumns.map((c) => c.ColumnId));
3568
+ }
3569
+ const freeTextColumns = ((_b = state.FreeTextColumn) === null || _b === void 0 ? void 0 : _b.FreeTextColumns) || [];
3570
+ if (freeTextColumns.length) {
3571
+ defaultLayout.Columns.push(...freeTextColumns.map((c) => c.ColumnId));
3572
+ }
3573
+ return defaultLayout;
3574
+ }
3575
+ /*
3576
+ * This is the opposite of setLayout
3577
+ */
3578
+ updateLayoutFromGrid() {
3579
+ var _a, _b;
3580
+ const currentLayout = this.api.layoutApi.getCurrentLayout();
3581
+ if (currentLayout.IsReadOnly) {
3582
+ // reaply the layout so the grid is reverted
3583
+ this.setLayout();
3584
+ return;
3585
+ }
3586
+ const layout = Object.assign({}, currentLayout);
3587
+ let columnOrder = [];
3588
+ const columnFlexes = {};
3589
+ const pinnedColumns = {};
3590
+ const columnSorts = [];
3591
+ const columnState = this.agGridAdapter.getAgGridApi().getColumnState();
3592
+ let groupedColumns = [...new Array(columnState.length)];
3593
+ let pivotedColumns = [...new Array(columnState.length)];
3594
+ const pivotColumns = [];
3595
+ const aggregatedColumns = {};
3596
+ const columnWidths = columnState.reduce((acc, colState) => {
3597
+ const { colId } = colState;
3598
+ if (colState.sort && colState.sortIndex != null) {
3599
+ columnSorts.push({
3600
+ ColumnId: colId,
3601
+ SortOrder: colState.sort === 'asc' ? 'Asc' : 'Desc',
3602
+ SortIndex: colState.sortIndex,
3603
+ });
3604
+ }
3605
+ if (colState.width != null) {
3606
+ acc[colId] = colState.width;
3607
+ }
3608
+ if (colState.flex != null) {
3609
+ columnFlexes[colId] = colState.flex;
3610
+ }
3611
+ if (colState.pinned === 'left') {
3612
+ pinnedColumns[colId] = 'left';
3613
+ }
3614
+ if (colState.pinned === 'right') {
3615
+ pinnedColumns[colId] = 'right';
3616
+ }
3617
+ if (!colState.hide) {
3618
+ columnOrder.push(colId);
3619
+ }
3620
+ if (colState.rowGroupIndex != null) {
3621
+ groupedColumns[colState.rowGroupIndex] = colId;
3622
+ }
3623
+ if (colState.pivotIndex != null) {
3624
+ pivotedColumns[colState.pivotIndex] = colId;
3625
+ }
3626
+ if (colState.aggFunc && typeof colState.aggFunc === 'string') {
3627
+ aggregatedColumns[colId] = colState.aggFunc;
3628
+ }
3629
+ return acc;
3630
+ }, {});
3631
+ columnSorts.sort((a, b) => a.SortIndex - b.SortIndex);
3632
+ this.agGridAdapter
3633
+ .getAgGridApi()
3634
+ .getPivotColumns()
3635
+ .forEach((col) => {
3636
+ pivotColumns.push(col.getColId());
3637
+ });
3638
+ groupedColumns = groupedColumns.filter((x) => !!x);
3639
+ pivotedColumns = pivotedColumns.filter((x) => !!x);
3640
+ if ((_b = (_a = this.adaptableOptions) === null || _a === void 0 ? void 0 : _a.groupingOptions) === null || _b === void 0 ? void 0 : _b.restoreUngroupedColumns) {
3641
+ columnOrder = this.restoreUnGroupColumnOrder({
3642
+ columnOrder,
3643
+ newGroupColumns: groupedColumns,
3644
+ });
3645
+ }
3646
+ layout.ColumnWidthMap = columnWidths;
3647
+ // layout.ColumnFlexMap = columnFlexes;
3648
+ layout.PinnedColumnsMap = pinnedColumns;
3649
+ layout.Columns = columnOrder;
3650
+ layout.ColumnSorts = columnSorts;
3651
+ layout.RowGroupedColumns = groupedColumns;
3652
+ if (Object.keys(aggregatedColumns).length) {
3653
+ // AG Grid aggregations are not 1-1 with adaptable column-aggregations
3654
+ layout.AggregationColumns = this.mapAggregationColumnsFromGrid(aggregatedColumns, currentLayout);
3655
+ }
3656
+ else {
3657
+ layout.AggregationColumns = {};
3658
+ }
3659
+ layout.EnablePivot = this.agGridAdapter.getAgGridApi().isPivotMode();
3660
+ layout.PivotColumns = pivotColumns;
3661
+ if (
3662
+ // check first row node for presence of data without iterating over whole grid
3663
+ this.api.layoutApi.internalApi.areExpandedRowGroupsSavedInLayouts() &&
3664
+ this.api.gridApi.getFirstDisplayedRowNode()) {
3665
+ layout.ExpandedRowGroupValues = this.getExpandRowGroupsKeys();
3666
+ }
3667
+ const previousVisibleColumns = currentLayout.Columns;
3668
+ const newVisibleColumns = layout.Columns;
3669
+ // check if all new columns were previously visible
3670
+ const someColumnsAreNew = newVisibleColumns.some((colId) => !previousVisibleColumns.includes(colId));
3671
+ if (someColumnsAreNew) {
3672
+ this.updateColumnModelAndRefreshGrid();
3673
+ }
3674
+ this.persistLayout(layout);
3675
+ }
3676
+ persistLayout(layout) {
3677
+ if (this.api.layoutApi.shouldAutoSaveLayouts()) {
3678
+ this.api.layoutApi.createOrUpdateLayout(layout);
3679
+ }
3680
+ else {
3681
+ this.api.layoutApi.internalApi.updateCurrentDraftLayout(layout);
3682
+ }
3683
+ }
3684
+ /**
3685
+ * When reading the state from the grid, we have to make sure 'avg' is not overriden with the 'avg' string.
3686
+ */
3687
+ mapAggregationColumnsFromGrid(aggFuncFromGrid, currentLayout) {
3688
+ return Object.entries(aggFuncFromGrid).reduce((acc, [colId, agg]) => {
3689
+ const adaptableAggFunc = this.getActiveAdaptableAggFuncForCol(colId);
3690
+ if ((adaptableAggFunc === null || adaptableAggFunc === void 0 ? void 0 : adaptableAggFunc.type) === 'weightedAverage' && agg === AggregationColumns_1.WEIGHTED_AVERAGE_AGG_FN_NAME) {
3691
+ // do not override the agg func
3692
+ acc[colId] = currentLayout.AggregationColumns[colId];
3693
+ }
3694
+ else {
3695
+ acc[colId] = agg;
3696
+ }
3697
+ return acc;
3698
+ }, {});
3699
+ }
3700
+ persistColumnIndexBeforeGrouping(params) {
3701
+ const layout = this.api.layoutApi.getCurrentLayout();
3702
+ const columnGroupsInLayout = layout.RowGroupedColumns;
3703
+ const columnGroupsInGrid = params.columns.map((col) => col.getColId());
3704
+ // what is new
3705
+ const newGroups = columnGroupsInGrid.filter((colId) => !columnGroupsInLayout.includes(colId));
3706
+ newGroups.forEach((colId) => {
3707
+ const columnIndex = layout.Columns.filter((colId) => !(this.api.columnApi.isAutoRowGroupColumn(colId) ||
3708
+ this.api.columnApi.isAutoPivotColumn(colId))).findIndex((columnIdInLayout) => columnIdInLayout === colId);
3709
+ // user may group after a column not in layout
3710
+ if (columnIndex !== -1) {
3711
+ this.api.internalApi.persistPreviousGroupedColumnsIndex(layout.Uuid, colId, columnIndex);
3712
+ }
3713
+ });
3714
+ }
3715
+ /**
3716
+ * Restores the order previous grouping order.
3717
+ */
3718
+ restoreUnGroupColumnOrder({ newGroupColumns, columnOrder, }) {
3719
+ var _a;
3720
+ const newColumnOrder = [...columnOrder];
3721
+ const currentLayout = this.api.layoutApi.getCurrentLayout();
3722
+ const previousGroupedColumnsIndex = this.api.internalApi.getPreviousGroupedColumnsIndex(currentLayout.Uuid);
3723
+ const isUnGroup = newGroupColumns.length < ((_a = currentLayout === null || currentLayout === void 0 ? void 0 : currentLayout.RowGroupedColumns) === null || _a === void 0 ? void 0 : _a.length);
3724
+ if (!isUnGroup) {
3725
+ return columnOrder;
3726
+ }
3727
+ if (!previousGroupedColumnsIndex) {
3728
+ return columnOrder;
3729
+ }
3730
+ for (let [colId, previousIndex] of Object.entries(previousGroupedColumnsIndex)) {
3731
+ const isStillGrouped = newGroupColumns.includes(colId);
3732
+ const isAlreadyInGrid = currentLayout.Columns.includes(colId); // was not just added by ungrouping
3733
+ if (isStillGrouped) {
3734
+ continue;
3735
+ }
3736
+ if (isAlreadyInGrid) {
3737
+ // no longer grouped, but already in grid, this means it was already in grid before ungrouping
3738
+ // in this case the state can be cleared
3739
+ this.api.internalApi.persistPreviousGroupedColumnsIndex(currentLayout.Uuid, colId, null);
3740
+ continue;
3741
+ }
3742
+ // need to ajust index based if grouped
3743
+ const numberOfGroupedColumns = newColumnOrder.filter((colId) => this.api.columnApi.isAutoRowGroupColumn(colId)).length;
3744
+ const adjustedPreviousIndex = previousIndex + numberOfGroupedColumns;
3745
+ const indexInGrid = newColumnOrder.indexOf(colId);
3746
+ const hasDifferentPositionAsPreviousLayout = adjustedPreviousIndex !== null && // if null, the reorder was already applied
3747
+ indexInGrid > 0 && // needs to be in grid
3748
+ adjustedPreviousIndex !== indexInGrid;
3749
+ const isPreviousPositionInRange = adjustedPreviousIndex < newColumnOrder.length;
3750
+ if (hasDifferentPositionAsPreviousLayout && isPreviousPositionInRange) {
3751
+ newColumnOrder.splice(indexInGrid, 1);
3752
+ newColumnOrder.splice(adjustedPreviousIndex, 0, colId);
3753
+ }
3754
+ this.api.internalApi.persistPreviousGroupedColumnsIndex(currentLayout.Uuid, colId, null);
3755
+ }
3756
+ return newColumnOrder;
3757
+ }
3758
+ onSortChanged() {
3759
+ const columnSorts = this.getColumnSorts();
3760
+ this.api.gridApi.setColumnSorts(columnSorts);
3761
+ this._emit('SortChanged', columnSorts);
3762
+ }
3763
+ getColumnSorts() {
3764
+ const columnSorts = [];
3765
+ const columnState = this.agGridAdapter.getAgGridApi().getColumnState();
3766
+ columnState.forEach((colState) => {
3767
+ const { colId } = colState;
3768
+ if (colState.sort && colState.sortIndex != null) {
3769
+ columnSorts.push({
3770
+ ColumnId: colId,
3771
+ SortOrder: colState.sort === 'asc' ? 'Asc' : 'Desc',
3772
+ SortIndex: colState.sortIndex,
3773
+ });
3774
+ }
3775
+ });
3776
+ columnSorts.sort((a, b) => a.SortIndex - b.SortIndex);
3777
+ return columnSorts.map((c) => {
3778
+ return {
3779
+ ColumnId: c.ColumnId,
3780
+ SortOrder: c.SortOrder,
3781
+ };
3782
+ });
3783
+ }
3784
+ }
3785
+ exports.AdaptableAgGrid = AdaptableAgGrid;