@adaptabletools/adaptable 18.0.0-canary.0 → 18.0.0-canary.10

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