@bino-bi/bn-template-engine 1.0.0-alpha.6 → 1.0.0-alpha.8

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 (108) hide show
  1. package/dist/bn-template-engine/bn-template-engine.esm.js +1 -1
  2. package/dist/bn-template-engine/p-0d41c5d8.entry.js +1 -0
  3. package/dist/bn-template-engine/p-67538176.entry.js +1 -0
  4. package/dist/bn-template-engine/p-825a07a8.entry.js +1 -0
  5. package/dist/bn-template-engine/p-916296a5.entry.js +1 -0
  6. package/dist/bn-template-engine/{p-1164c0b0.entry.js → p-96006b06.entry.js} +1 -1
  7. package/dist/bn-template-engine/p-B4JfKvVT.js +1 -0
  8. package/dist/bn-template-engine/{p-JNHhIe7t.js → p-B_d-jp99.js} +1 -1
  9. package/dist/bn-template-engine/p-Ck-NYtot.js +1 -0
  10. package/dist/bn-template-engine/p-CnDq0oVa.js +1 -0
  11. package/dist/bn-template-engine/p-DSXNgKLa.js +1 -0
  12. package/dist/bn-template-engine/p-bc711fb0.entry.js +1 -0
  13. package/dist/bn-template-engine/p-e6f646b1.entry.js +1 -0
  14. package/dist/bn-template-engine/p-f41d9242.entry.js +1 -0
  15. package/dist/bn-template-engine/{p-B0lsgVuN.js → p-gFbbuhtl.js} +1 -1
  16. package/dist/cjs/{SVGVariancesStyleGroup-BqAdPYtL.js → bn-asset_20.cjs.entry.js} +21948 -6938
  17. package/dist/cjs/bn-grid.cjs.entry.js +6 -9
  18. package/dist/cjs/bn-image.cjs.entry.js +6 -9
  19. package/dist/cjs/bn-internationalization.cjs.entry.js +5 -6
  20. package/dist/cjs/bn-template-engine.cjs.js +2 -2
  21. package/dist/cjs/bn-template.cjs.entry.js +3 -4
  22. package/dist/cjs/bn-text.cjs.entry.js +7 -10
  23. package/dist/cjs/bn-tree.cjs.entry.js +6 -9
  24. package/dist/cjs/{context-protocol-DRQWrwsA.js → context-protocol-ohYzcb5F.js} +1 -1
  25. package/dist/cjs/editor-companion.cjs.entry.js +2 -2
  26. package/dist/cjs/{index-Cjw0q6gP.js → index-CDKG4xmO.js} +1 -0
  27. package/dist/cjs/loader.cjs.js +2 -2
  28. package/dist/cjs/{scaling-BidPsO53.js → scaling-CIAClQR5.js} +3 -3
  29. package/dist/cjs/{withBodyObserver-C6gLgq_e.js → withBodyObserver-D7BKWN2N.js} +2 -2
  30. package/dist/cjs/{withHasError-B8gHkfV2.js → withHasError-Cl2gTQzA.js} +106 -2
  31. package/dist/cjs/{Order-BGx39pS5.js → withStyled-qd94SSb4.js} +648 -6
  32. package/dist/collection/components/bn-chart-structure/bn-chart-structure.js +65 -13
  33. package/dist/collection/components/bn-chart-time/bn-chart-time.js +63 -11
  34. package/dist/collection/components/bn-layout-card/bn-layout-card.js +43 -6
  35. package/dist/collection/components/bn-layout-page/bn-layout-page.js +12 -7
  36. package/dist/collection/components/bn-table/bn-table.js +83 -19
  37. package/dist/collection/components/bn-table/ibcs-table.js +68 -3
  38. package/dist/collection/utils/withInheritedProps.js +152 -0
  39. package/dist/components/bn-chart-structure.js +1 -1
  40. package/dist/components/bn-chart-time.js +1 -1
  41. package/dist/components/bn-layout-card.js +1 -1
  42. package/dist/components/bn-layout-page.js +1 -1
  43. package/dist/components/bn-table.js +1 -1
  44. package/dist/components/ibcs-table2.js +1 -1
  45. package/dist/components/withInheritedProps.js +1 -0
  46. package/dist/esm/{SVGVariancesStyleGroup-DOIT-zvI.js → bn-asset_20.entry.js} +22048 -7042
  47. package/dist/esm/bn-grid.entry.js +4 -7
  48. package/dist/esm/bn-image.entry.js +4 -7
  49. package/dist/esm/bn-internationalization.entry.js +4 -5
  50. package/dist/esm/bn-template-engine.js +3 -3
  51. package/dist/esm/bn-template.entry.js +2 -3
  52. package/dist/esm/bn-text.entry.js +5 -8
  53. package/dist/esm/bn-tree.entry.js +4 -7
  54. package/dist/esm/{context-protocol-2peaD4y8.js → context-protocol-DdbSplvE.js} +2 -2
  55. package/dist/esm/editor-companion.entry.js +2 -2
  56. package/dist/esm/{index-JNHhIe7t.js → index-B_d-jp99.js} +1 -1
  57. package/dist/esm/loader.js +3 -3
  58. package/dist/esm/{scaling-BOcjT8M0.js → scaling-DGKKkuL9.js} +4 -4
  59. package/dist/esm/{withBodyObserver-DczL5ia8.js → withBodyObserver-AFk2wwHT.js} +2 -2
  60. package/dist/esm/{withHasError-B3QX2emi.js → withHasError-DW_vMDUp.js} +106 -2
  61. package/dist/esm/{Order-sRO-lj7X.js → withStyled-BIkqU2w4.js} +616 -1
  62. package/dist/types/components/bn-chart-structure/bn-chart-structure.d.ts +2 -0
  63. package/dist/types/components/bn-chart-time/bn-chart-time.d.ts +2 -0
  64. package/dist/types/components/bn-layout-card/bn-layout-card.d.ts +16 -2
  65. package/dist/types/components/bn-layout-page/bn-layout-page.d.ts +8 -3
  66. package/dist/types/components/bn-table/bn-table.d.ts +1 -0
  67. package/dist/types/components/bn-table/ibcs-table.d.ts +19 -0
  68. package/dist/types/components.d.ts +8 -8
  69. package/dist/types/utils/withInheritedProps.d.ts +38 -0
  70. package/package.json +1 -1
  71. package/dist/bn-template-engine/p-06946f44.entry.js +0 -1
  72. package/dist/bn-template-engine/p-0fabe296.entry.js +0 -1
  73. package/dist/bn-template-engine/p-355abdf0.entry.js +0 -1
  74. package/dist/bn-template-engine/p-79KuA4Ox.js +0 -1
  75. package/dist/bn-template-engine/p-859cc06d.entry.js +0 -1
  76. package/dist/bn-template-engine/p-8acec99e.entry.js +0 -1
  77. package/dist/bn-template-engine/p-8f490c45.entry.js +0 -1
  78. package/dist/bn-template-engine/p-98cf512f.entry.js +0 -1
  79. package/dist/bn-template-engine/p-9a564f8f.entry.js +0 -1
  80. package/dist/bn-template-engine/p-B7p8beYH.js +0 -1
  81. package/dist/bn-template-engine/p-BDh7GfC5.js +0 -1
  82. package/dist/bn-template-engine/p-BoMtoHJB.js +0 -1
  83. package/dist/bn-template-engine/p-Bs8BqBsb.js +0 -1
  84. package/dist/bn-template-engine/p-CYjZRKdI.js +0 -1
  85. package/dist/bn-template-engine/p-DG-1MR_T.js +0 -1
  86. package/dist/bn-template-engine/p-bdd2b243.entry.js +0 -1
  87. package/dist/bn-template-engine/p-e6b24f15.entry.js +0 -1
  88. package/dist/bn-template-engine/p-f27995c9.entry.js +0 -1
  89. package/dist/bn-template-engine/p-sRO-lj7X.js +0 -1
  90. package/dist/bn-template-engine/p-tzFCK9qn.js +0 -1
  91. package/dist/cjs/bn-asset_16.cjs.entry.js +0 -9018
  92. package/dist/cjs/bn-card.cjs.entry.js +0 -36
  93. package/dist/cjs/bn-chart-time.cjs.entry.js +0 -995
  94. package/dist/cjs/bn-layout-card.cjs.entry.js +0 -248
  95. package/dist/cjs/formatter-4XCS0d2B.js +0 -221
  96. package/dist/cjs/ibcs-chart-time.cjs.entry.js +0 -4137
  97. package/dist/cjs/withComponentStatus-_x4LQZ0N.js +0 -109
  98. package/dist/cjs/withComponentStyle-ClSJfCku.js +0 -128
  99. package/dist/cjs/withStyled-9tG024gQ.js +0 -522
  100. package/dist/esm/bn-asset_16.entry.js +0 -9001
  101. package/dist/esm/bn-card.entry.js +0 -34
  102. package/dist/esm/bn-chart-time.entry.js +0 -993
  103. package/dist/esm/bn-layout-card.entry.js +0 -246
  104. package/dist/esm/formatter-BDh7GfC5.js +0 -215
  105. package/dist/esm/ibcs-chart-time.entry.js +0 -4135
  106. package/dist/esm/withComponentStatus-DodoSXe-.js +0 -107
  107. package/dist/esm/withComponentStyle-D3VWOsto.js +0 -126
  108. package/dist/esm/withStyled-CE3_3taP.js +0 -495
@@ -1,4135 +0,0 @@
1
- import { r as registerInstance, h, H as Host, g as getElement } from './index-JNHhIe7t.js';
2
- import { S as Svg, a as SiPrefix, g as getContrastTextColor, I as IBCSRuleSet, b as alasql, c as getScenarioPrefix, d as IBCS_LAYER_ORDER, D as DataAnalyzer, e as StringAdapter, f as DataFormatDigitsAdapter, F as FontStyleAdapter, h as SVGStyleGroupAdapter, i as SVGStyleAdapter, j as SVGVariancesStyleGroupAdapter, P as PaddingAdapter } from './SVGVariancesStyleGroup-DOIT-zvI.js';
3
- import { k as CompareUtil, l as DateTime, c as StackMode, D as DateDistance, A as AxisLabelsMode, C as ChartMode, m as DateStringFactory, S as StackBy, n as AdapterUtils, o as OrderAdapter, f as AggregationLevel, O as OrderDirection } from './Order-sRO-lj7X.js';
4
- import { C as CalculateSize, F as Formatter, V as VarianceScenario } from './formatter-BDh7GfC5.js';
5
-
6
- // import { IAdapter } from "../../../../../utils/helper/IAdapter";
7
- // import { CompareUtil } from "../../../../../utils/helper/CompareUtil";
8
- /**
9
- * Proportional scale factors for time-series chart elements.
10
- *
11
- * All values are expressed in **font-size multiples** (em-like units), so the chart
12
- * scales uniformly when the base font size changes. The chart renderer multiplies
13
- * each factor by the computed font size to get pixel dimensions.
14
- */
15
- class ScaleFactorsTimeChart {
16
- constructor() {
17
- /** Horizontal gap between adjacent scenario bars within a data point. */
18
- this.scenarioOffset = 0.3;
19
- /** Vertical gap between the scenario label and the top of its column. */
20
- this.scenarioLabelToColumn = 0.3;
21
- /** Vertical gap between the value label and the top of its column. */
22
- this.labelToColumn = 0.3;
23
- /** Gap between axis labels and the axis line. */
24
- this.labelToAxis = 0.3;
25
- /** Width of the variance needle (pin chart element). */
26
- this.needleWidth = 0.3;
27
- /** Width of the arrowhead on variance needles. */
28
- this.needleHeadWidth = 0.6;
29
- /** Width of a single data column (bar). */
30
- this.columnWidth = 2.0;
31
- /** Stroke width of the variance chart axis line. */
32
- this.varianceAxisLineWidth = 0.3;
33
- /** Stroke width of the main value axis line. */
34
- this.axisLineWidth = 0.1;
35
- /** Stroke width of auxiliary/grid lines. */
36
- this.auxiliaryLineWidth = 0.1;
37
- /** Stroke width of scenario indicator lines (e.g. forecast hatching). */
38
- this.scenarioLineWidth = 0.2;
39
- /** Width of plan/previous-period marker symbols. */
40
- this.markerWidth = 0.7;
41
- /** Horizontal offset of markers from the column center. */
42
- this.markerOffset = 0.0;
43
- /** Total horizontal space allocated per data point (bar + padding). */
44
- this.categoryWidth = 3.0;
45
- /** Length of axis tick marks. */
46
- this.axisTickLength = 0.3;
47
- }
48
- }
49
- /** Converts untyped JSON into a validated {@link ScaleFactorsTimeChart}. */
50
- class ScaleFactorsTimeChartAdapter {
51
- adapt(data) {
52
- const scaleFactors = new ScaleFactorsTimeChart();
53
- if (CompareUtil.isNumber(data.scenarioOffset)) {
54
- scaleFactors.scenarioOffset = data.scenarioOffset;
55
- }
56
- if (CompareUtil.isNumber(data.scenarioLabelToColumn)) {
57
- scaleFactors.scenarioLabelToColumn = data.scenarioLabelToColumn;
58
- }
59
- if (CompareUtil.isNumber(data.labelToColumn)) {
60
- scaleFactors.labelToColumn = data.labelToColumn;
61
- }
62
- if (CompareUtil.isNumber(data.labelToAxis)) {
63
- scaleFactors.labelToAxis = data.labelToAxis;
64
- }
65
- if (CompareUtil.isNumber(data.needleWidth)) {
66
- scaleFactors.needleWidth = data.needleWidth;
67
- }
68
- if (CompareUtil.isNumber(data.needleHeadWidth)) {
69
- scaleFactors.needleHeadWidth = data.needleHeadWidth;
70
- }
71
- if (CompareUtil.isNumber(data.columnWidth)) {
72
- scaleFactors.columnWidth = data.columnWidth;
73
- }
74
- if (CompareUtil.isNumber(data.varianceAxisLineWidth)) {
75
- scaleFactors.varianceAxisLineWidth = data.varianceAxisLineWidth;
76
- }
77
- if (CompareUtil.isNumber(data.axisLineWidth)) {
78
- scaleFactors.axisLineWidth = data.axisLineWidth;
79
- }
80
- if (CompareUtil.isNumber(data.auxiliaryLineWidth)) {
81
- scaleFactors.auxiliaryLineWidth = data.auxiliaryLineWidth;
82
- }
83
- if (CompareUtil.isNumber(data.scenarioLineWidth)) {
84
- scaleFactors.scenarioLineWidth = data.scenarioLineWidth;
85
- }
86
- if (CompareUtil.isNumber(data.markerWidth)) {
87
- scaleFactors.markerWidth = data.markerWidth;
88
- }
89
- if (CompareUtil.isNumber(data.markerOffset)) {
90
- scaleFactors.markerOffset = data.markerOffset;
91
- }
92
- if (CompareUtil.isNumber(data.categoryWidth)) {
93
- scaleFactors.categoryWidth = data.categoryWidth;
94
- }
95
- if (CompareUtil.isNumber(data.axisTickLength)) {
96
- scaleFactors.axisTickLength = data.axisTickLength;
97
- }
98
- return scaleFactors;
99
- }
100
- default() {
101
- return new ScaleFactorsTimeChart();
102
- }
103
- }
104
-
105
- // import {FontStyle} from "../../../../utils/model/styles/FontStyle";
106
- /**
107
- * Spatial layout engine for the time chart.
108
- *
109
- * Converts logical data model coordinates (column index, data values) into pixel positions
110
- * for all chart elements. All spacings are derived from the font size multiplied by
111
- * ScaleFactorsTimeChart factors, making the layout scale consistently with typography.
112
- *
113
- * Key coordinate reference points:
114
- * - getColumnPositionY(): the Y coordinate of the horizontal axis baseline
115
- * - getColumnCenterPositionX(index): center X for the column at the given time index
116
- * - getAxisPositionY(isRelative): axis Y adjusted for relative variance offset
117
- *
118
- * The layout accounts for: padding, left-side label space, scenario label offsets,
119
- * data label height, and the min/max data values to position the axis correctly
120
- * so that bars grow upward (positive) or downward (negative) from the baseline.
121
- */
122
- class ElementPositions {
123
- constructor(padding, scaleFactors, fontstyle, smallestDataPoint, highestDataPoint, numberOfColumns, leftSideLabelLength) {
124
- this.categoryPosition = { x: 0, y: 0 };
125
- this.spacings = new ScaleFactorsTimeChart();
126
- this.categoriesBoxOffset = {
127
- width: 0,
128
- height: 0,
129
- };
130
- this.padding = padding;
131
- this.scaleFactors = scaleFactors;
132
- this.fontStlye = fontstyle;
133
- this.dataLabelHeight = this.caluculateDataLabelHeight();
134
- this.axisPosition = { x: 0, y: 0 };
135
- this.columnValue = {
136
- min: smallestDataPoint,
137
- max: highestDataPoint,
138
- };
139
- this.numberOfColumns = numberOfColumns;
140
- this.leftSideLabelLength = leftSideLabelLength;
141
- this.calculateSpacings();
142
- this.calculateCategoryPosition();
143
- this.calculateAxisPosition();
144
- }
145
- caluculateDataLabelHeight() {
146
- const testlable = "123456789";
147
- const height = CalculateSize(testlable, {
148
- font: this.fontStlye.font,
149
- fontSize: this.fontStlye.size + "px",
150
- }).height;
151
- return height * 1.1;
152
- }
153
- getColumnCenterPositionX(index) {
154
- return (this.categoryPosition.y +
155
- this.spacings.scenarioOffset +
156
- index * this.spacings.categoryWidth +
157
- this.leftSideLabelLength +
158
- this.spacings.columnWidth * 0.5);
159
- }
160
- getAxisPositionY(isRelative) {
161
- let value = this.columnValue.max.getScaledUnit();
162
- if (isRelative) {
163
- value = this.columnValue.max.getScaledPercentUnit() + this.getNeedleWidth();
164
- }
165
- return value + this.dataLabelHeight + this.spacings.labelToAxis + this.padding.top;
166
- }
167
- getAxisPositionX() {
168
- return this.padding.left + this.leftSideLabelLength;
169
- }
170
- getColumnPositionX(index, isPrimaryColumn) {
171
- if (isPrimaryColumn) {
172
- return this.getColumnCenterPositionX(index);
173
- }
174
- return this.getColumnCenterPositionX(index) - this.spacings.scenarioOffset;
175
- }
176
- getColumnPositionY() {
177
- return this.columnValue.max.getScaledUnit() + this.dataLabelHeight + this.spacings.labelToColumn + this.padding.top;
178
- }
179
- getNeedlePositionY() {
180
- return (this.columnValue.max.getScaledPercentUnit() +
181
- this.dataLabelHeight +
182
- this.spacings.labelToColumn +
183
- this.getNeedleWidth() +
184
- this.padding.top);
185
- }
186
- getMarkerPositionX(index, isPrimaryMarker) {
187
- if (isPrimaryMarker) {
188
- return this.getColumnCenterPositionX(index) - this.spacings.markerOffset - this.getColumnWidth() * 0.5;
189
- }
190
- return this.getColumnCenterPositionX(index) + this.spacings.markerOffset + this.getColumnWidth() * 0.5;
191
- }
192
- getMarkerPositionY() {
193
- return this.getColumnPositionY();
194
- }
195
- getAxisTitlePositionX(group) {
196
- const offsetToCenterText = group.width();
197
- return this.axisPosition.x - offsetToCenterText;
198
- }
199
- getAxisTitlePositionY(isPositive, isRelative) {
200
- let value = this.columnValue.max.getScaledUnit();
201
- if (isRelative) {
202
- value = this.columnValue.max.getScaledPercentUnit();
203
- }
204
- if (isPositive) {
205
- return value + this.dataLabelHeight + this.spacings.labelToAxis;
206
- }
207
- else {
208
- return value;
209
- }
210
- }
211
- getColumnDataLabelPositionY(scaledUnit) {
212
- const offset = this.spacings.labelToColumn;
213
- if (scaledUnit < 0) {
214
- return this.getColumnPositionY() + Math.abs(scaledUnit) + offset;
215
- }
216
- return this.getColumnPositionY() - scaledUnit - offset;
217
- }
218
- getNeedleDataLabelPositionY(scaledUnit) {
219
- const offset = this.spacings.labelToColumn;
220
- if (scaledUnit < 0) {
221
- return this.getNeedlePositionY() + Math.abs(scaledUnit) + offset + 2 * this.getNeedleWidth();
222
- }
223
- return this.getNeedlePositionY() - scaledUnit - offset - 2 * this.getNeedleWidth();
224
- }
225
- getAxisEndPositionX() {
226
- return this.getAxisPositionX() + (this.numberOfColumns + 1 / 2) * this.spacings.categoryWidth;
227
- }
228
- getColumnWidth() {
229
- return this.spacings.columnWidth;
230
- }
231
- getNeedleWidth() {
232
- return this.spacings.needleWidth;
233
- }
234
- getNeedleHeadWidth() {
235
- return this.spacings.needleHeadWidth;
236
- }
237
- getScenarioLabelPositionOffsetX(isPrimaryColumn) {
238
- if (isPrimaryColumn) {
239
- return this.getColumnWidth() * 0.5 + this.spacings.scenarioLabelToColumn;
240
- }
241
- return -(this.getColumnWidth() * 0.5 + this.spacings.scenarioLabelToColumn);
242
- }
243
- calculateSpacings() {
244
- this.spacings = {
245
- scenarioOffset: this.fontStlye.size * this.scaleFactors.scenarioOffset,
246
- scenarioLabelToColumn: this.fontStlye.size * this.scaleFactors.scenarioLabelToColumn,
247
- markerOffset: this.fontStlye.size * this.scaleFactors.markerOffset,
248
- labelToColumn: this.fontStlye.size * this.scaleFactors.labelToColumn,
249
- labelToAxis: this.fontStlye.size * this.scaleFactors.labelToAxis,
250
- needleWidth: this.fontStlye.size * this.scaleFactors.needleWidth,
251
- needleHeadWidth: this.fontStlye.size * this.scaleFactors.needleHeadWidth,
252
- columnWidth: this.fontStlye.size * this.scaleFactors.columnWidth,
253
- varianceAxisLineWidth: this.fontStlye.size * this.scaleFactors.varianceAxisLineWidth,
254
- axisLineWidth: this.fontStlye.size * this.scaleFactors.axisLineWidth,
255
- auxiliaryLineWidth: this.fontStlye.size * this.scaleFactors.auxiliaryLineWidth,
256
- scenarioLineWidth: this.fontStlye.size * this.scaleFactors.scenarioLineWidth,
257
- markerWidth: this.fontStlye.size * this.scaleFactors.markerWidth,
258
- categoryWidth: this.fontStlye.size * this.scaleFactors.categoryWidth,
259
- axisTickLength: this.fontStlye.size * this.scaleFactors.axisTickLength,
260
- };
261
- }
262
- calculateCategoryPosition() {
263
- this.categoryPosition = {
264
- x: this.padding.left + this.spacings.columnWidth * 0.5,
265
- y: this.padding.top,
266
- };
267
- }
268
- calculateAxisPosition() {
269
- this.axisPosition = {
270
- x: this.getAxisPositionX(),
271
- y: this.getAxisPositionY(false),
272
- };
273
- }
274
- getMarkerScenarioLabelPositionOffsetX(isPrimaryColumn) {
275
- if (isPrimaryColumn) {
276
- return this.spacings.labelToColumn - this.fontStlye.size;
277
- }
278
- return this.spacings.labelToColumn + this.spacings.markerWidth * 0.5;
279
- }
280
- }
281
-
282
- class Padding {
283
- constructor(padding) {
284
- this.top = padding.top;
285
- this.bottom = padding.bottom;
286
- this.left = padding.left;
287
- this.right = padding.right;
288
- }
289
- addBoxTopLeft(addition) {
290
- this.top += addition.height | this.top;
291
- this.left += addition.width | this.top;
292
- return this;
293
- }
294
- }
295
-
296
- // import { SVGPolgonPattern } from "../../../../utils/model";
297
- class MarkerPattern {
298
- constructor(fontSize) {
299
- const backgroundFactor = 1;
300
- const foregroundFactor = 0.7;
301
- const maxBg = fontSize * backgroundFactor;
302
- const maxFg = fontSize * foregroundFactor;
303
- this.bgOffset = (maxBg - maxFg) / 2;
304
- this.markerUp = { top: maxFg / 2 + ",0", left: "0," + maxFg, right: maxFg + "," + maxFg };
305
- this.markerUpBackground = { top: maxBg / 2 + ",0", left: "0," + maxBg, right: maxBg + "," + maxBg };
306
- this.markerDown = { bottom: maxFg / 2 + "," + maxFg, left: "0,0", right: maxFg + ",0" };
307
- this.markerDownBackground = { bottom: maxBg / 2 + "," + maxBg, left: "0,0", right: maxBg + ",0" };
308
- this.markerRight = { bottom: "0," + maxFg, top: "0,0", right: maxFg + "," + maxFg / 2 };
309
- this.markerRightBackground = { bottom: "0," + maxBg, top: "0,0", right: maxBg + "," + maxBg / 2 };
310
- this.markerLeft = { bottom: maxFg + "," + maxFg, top: maxFg + ",0", left: "0," + maxFg / 2 };
311
- this.markerLeftBackground = { bottom: maxBg + "," + maxBg, top: maxBg + ",0", Left: "0," + maxBg / 2 };
312
- }
313
- upMarkerPatternStrings() {
314
- return {
315
- background: this.markerUpBackground.left +
316
- " " +
317
- this.markerUpBackground.right +
318
- " " +
319
- this.markerUpBackground.top +
320
- " " +
321
- this.markerUpBackground.left,
322
- foreground: this.markerUp.left + " " + this.markerUp.right + " " + this.markerUp.top + " " + this.markerUp.left,
323
- bgOffset: this.bgOffset,
324
- };
325
- }
326
- downMarkerPatternStrings() {
327
- return {
328
- background: this.markerDownBackground.left +
329
- " " +
330
- this.markerDownBackground.right +
331
- " " +
332
- this.markerDownBackground.bottom +
333
- " " +
334
- this.markerDownBackground.left,
335
- foreground: this.markerDown.left + " " + this.markerDown.right + " " + this.markerDown.bottom + " " + this.markerDown.left,
336
- bgOffset: this.bgOffset,
337
- };
338
- }
339
- rightMarkerPatternStrings() {
340
- return {
341
- background: this.markerRightBackground.top +
342
- " " +
343
- this.markerRightBackground.right +
344
- " " +
345
- this.markerRightBackground.bottom +
346
- " " +
347
- this.markerRightBackground.top,
348
- foreground: this.markerRight.top +
349
- " " +
350
- this.markerRight.right +
351
- " " +
352
- this.markerRight.bottom +
353
- " " +
354
- this.markerRight.top,
355
- bgOffset: this.bgOffset,
356
- };
357
- }
358
- leftMarkerPatternStrings() {
359
- return {
360
- background: this.markerLeftBackground.top +
361
- " " +
362
- this.markerLeftBackground.Left +
363
- " " +
364
- this.markerLeftBackground.bottom +
365
- " " +
366
- this.markerLeftBackground.top,
367
- foreground: this.markerLeft.top + " " + this.markerLeft.left + " " + this.markerLeft.bottom + " " + this.markerLeft.top,
368
- bgOffset: this.bgOffset,
369
- };
370
- }
371
- createPatternMapForStructureBar() {
372
- const pattern = new Map();
373
- pattern.set("marker-up", this.upMarkerPatternStrings());
374
- pattern.set("marker-down", this.downMarkerPatternStrings());
375
- pattern.set("marker-right", this.rightMarkerPatternStrings());
376
- pattern.set("marker-left", this.leftMarkerPatternStrings());
377
- return pattern;
378
- }
379
- }
380
-
381
- /**
382
- * Generates SVG diagonal-line hatching patterns for forecast (FC) scenario bars.
383
- *
384
- * Creates a 10x10 SVG <pattern> tile with diagonal lines using the FC bar style colors.
385
- * The resulting pattern is used as the fill for FC columns/bars to visually distinguish
386
- * forecast data from actual data per IBCS conventions (hatched = forecast, solid = actual).
387
- *
388
- * bgOffset is computed from font size to center the foreground shape within the background.
389
- */
390
- class CustomPattern {
391
- constructor(styles) {
392
- this.container = new Svg();
393
- this.pattern = this.createFCPattern(this.container.group(), styles);
394
- this.styles = styles;
395
- const backgroundFactor = 1;
396
- const foregroundFactor = 0.7;
397
- let fontSize = 10;
398
- if (styles != null && styles.fontStyles != null && styles.fontStyles.size) {
399
- fontSize = styles.fontStyles.size;
400
- }
401
- const maxBg = fontSize * backgroundFactor;
402
- const maxFg = fontSize * foregroundFactor;
403
- this.bgOffset = (maxBg - maxFg) / 2;
404
- }
405
- createFCPattern(group, styles) {
406
- const _styles = styles;
407
- return group
408
- .pattern(10, 10, function (add) {
409
- add.rect(10, 10).fill(_styles.barStyles.fc.fill);
410
- add
411
- .line(0, 5, 5, 0)
412
- .stroke({ width: _styles.barStyles.fc.width, color: _styles.barStyles.fc.stroke, linecap: "square" });
413
- add
414
- .line(5, 10, 10, 5)
415
- .stroke({ width: _styles.barStyles.fc.width, color: _styles.barStyles.fc.stroke, linecap: "square" });
416
- })
417
- .id("pattern-time-fc");
418
- }
419
- getFCPolygonPattern() {
420
- return { background: "", foreground: "", bgOffset: 0, pattern: this.pattern };
421
- }
422
- toString() {
423
- return this.container.svg();
424
- }
425
- }
426
-
427
- // import { DataFormatDigits } from "../../../../utils/model/DataFormatDigits";
428
- // import { SiPrefix } from "../../../../utils/model/SiPrefix";
429
- /**
430
- * Anchor point for label positioning relative to its coordinates.
431
- * Vertical hooks control how the label is offset from its Y coordinate;
432
- * horizontal hooks control text-anchor alignment (start/middle/end).
433
- */
434
- var HookLocation;
435
- (function (HookLocation) {
436
- HookLocation[HookLocation["Left"] = 0] = "Left";
437
- HookLocation[HookLocation["Center"] = 1] = "Center";
438
- HookLocation[HookLocation["Right"] = 2] = "Right";
439
- HookLocation[HookLocation["Top"] = 3] = "Top";
440
- HookLocation[HookLocation["Bottom"] = 4] = "Bottom";
441
- })(HookLocation || (HookLocation = {}));
442
- /**
443
- * SVG text label used across all chart elements (columns, needles, markers, axes).
444
- *
445
- * Handles numeric formatting via Formatter.number() with configurable type (decimal/percent),
446
- * digit precision, and SI prefix scaling. Variance labels prepend a "+" sign for positive values.
447
- *
448
- * The label is drawn with a semi-transparent white background rectangle to ensure
449
- * readability over chart geometry. For stacked segments, the background is omitted
450
- * and text color is derived from the segment fill for contrast.
451
- *
452
- * Positioning uses a two-axis hook system: verticalHookLocation shifts the label
453
- * above/below/centered on the Y coordinate, horizontalHookLocation sets the SVG
454
- * text-anchor (start/middle/end) relative to X.
455
- */
456
- class Label {
457
- constructor(parent, xPosition, yPosition, groupPrefix, value, styles, verticalHookLocation, horizontalHookLocation) {
458
- this.ID_SCENARIOLABEL = "Label";
459
- this.CSS_CATEGORIES = "categories";
460
- this.isRelativeLabel = false;
461
- this.segmentFillColor = null;
462
- this.x = xPosition;
463
- this.y = yPosition;
464
- this.value = value;
465
- this.group = parent.group().id(this.createElementID(parent.toString(), groupPrefix));
466
- this.styles = styles;
467
- this.isVarianceLabel = false;
468
- this.verticalHookLocation = verticalHookLocation || HookLocation.Top;
469
- this.horizontalHookLocation = horizontalHookLocation || HookLocation.Left;
470
- }
471
- setToVarianceLabel() {
472
- this.isVarianceLabel = true;
473
- return this;
474
- }
475
- setToRelativeVarianceLabel() {
476
- this.isVarianceLabel = true;
477
- this.isRelativeLabel = true;
478
- return this;
479
- }
480
- setSegmentFill(color) {
481
- this.segmentFillColor = color;
482
- return this;
483
- }
484
- updateGroup(newGroup) {
485
- this.group = newGroup;
486
- return this;
487
- }
488
- draw(displayLabel = true, dataFormatDigits = { percent: 2, decimal: 1 }, measureScale = new SiPrefix()) {
489
- if (this.isEmpty()) {
490
- return this;
491
- }
492
- const label = this.group;
493
- let valueStr;
494
- let prefix = "";
495
- if (Number.isNaN(Number(this.value)) === false) {
496
- const value = this.value;
497
- let type = "percent";
498
- let digits = dataFormatDigits.percent;
499
- let digitsMin = dataFormatDigits.percent;
500
- let scale = 1;
501
- if (this.isRelativeLabel === false) {
502
- digits = dataFormatDigits.decimal;
503
- digitsMin = dataFormatDigits.decimal;
504
- scale = measureScale.value;
505
- type = "decimal";
506
- }
507
- valueStr = Formatter.number(Number(value), type, digits, digitsMin, scale);
508
- if (this.isVarianceLabel && Number(this.value) >= 0) {
509
- prefix = "+";
510
- }
511
- }
512
- else {
513
- valueStr = "" + this.value;
514
- // displayLabel = false;
515
- }
516
- const labelStr = prefix + valueStr;
517
- const text = this.drawLabel(label, labelStr);
518
- if (displayLabel === false) {
519
- text.addClass("hide");
520
- label.addClass("hide");
521
- }
522
- return this;
523
- }
524
- isEmpty() {
525
- return this.value == null || "" === this.value;
526
- }
527
- setPos(xPosition, yPosition) {
528
- this.x = xPosition;
529
- this.y = yPosition;
530
- return this;
531
- }
532
- forceStringTypeDraw() {
533
- const label = this.group;
534
- const labelStr = "" + this.value;
535
- this.drawLabel(label, labelStr);
536
- return this;
537
- }
538
- drawLabel(label, labelStr) {
539
- const background = this.styles.fontStyles.background || "#ffffff";
540
- //let text = label.text(labelStr)
541
- // .leading(1)
542
- // .addClass(this.CSS_CATEGORIES)
543
- // .font({anchor: 'middle'})
544
- // .move(this.x, this.y);
545
- let labelAnchor = "start";
546
- const text = label.text(labelStr);
547
- text.move(this.x, this.y);
548
- const boxWidth = text.bbox().w;
549
- const boxHeight = text.bbox().h;
550
- let rectX = 0;
551
- let rectY = 0;
552
- const textX = text.x();
553
- let textY = text.y();
554
- if (this.horizontalHookLocation === HookLocation.Left) {
555
- labelAnchor = "left";
556
- rectX = text.x();
557
- }
558
- else if (this.horizontalHookLocation === HookLocation.Center) {
559
- labelAnchor = "middle";
560
- rectX = text.x() - (boxWidth + 2) / 2;
561
- }
562
- else if (this.horizontalHookLocation === HookLocation.Right) {
563
- labelAnchor = "end";
564
- rectX = text.x() - boxWidth;
565
- }
566
- if (this.verticalHookLocation === HookLocation.Center) {
567
- textY = text.y() - (boxHeight * 1.2) / 2;
568
- rectY = textY + boxHeight * 0.2;
569
- }
570
- else if (this.verticalHookLocation === HookLocation.Top) {
571
- textY -= boxHeight / 4;
572
- rectY = textY + boxHeight * 0.2;
573
- }
574
- else if (this.verticalHookLocation === HookLocation.Bottom) {
575
- textY -= boxHeight;
576
- rectY = textY + boxHeight * 0.2; // + (boxHeight / 2);
577
- }
578
- text.move(textX, textY);
579
- text.font({ anchor: labelAnchor });
580
- if (this.segmentFillColor != null) {
581
- text.fill(getContrastTextColor(this.segmentFillColor));
582
- }
583
- else {
584
- label
585
- .rect(boxWidth + 2, boxHeight * 0.8)
586
- .stroke(background)
587
- .fill(background)
588
- .opacity(0.9)
589
- .move(rectX - 1, rectY)
590
- .insertBefore(text);
591
- }
592
- return text;
593
- }
594
- createElementID(prefix, groupPrefix) {
595
- return prefix + "_" + groupPrefix + "_" + this.ID_SCENARIOLABEL;
596
- }
597
- }
598
-
599
- /**
600
- * Scenario priority for label collision resolution.
601
- * Lower number = higher priority. AC always wins.
602
- */
603
- const SCENARIO_PRIORITY = {
604
- ac: 1,
605
- pp: 2,
606
- fc: 3,
607
- pl: 4,
608
- };
609
- /**
610
- * Direction a label can be placed relative to its marker.
611
- */
612
- var LabelDirection;
613
- (function (LabelDirection) {
614
- LabelDirection[LabelDirection["Above"] = 0] = "Above";
615
- LabelDirection[LabelDirection["Below"] = 1] = "Below";
616
- LabelDirection[LabelDirection["Left"] = 2] = "Left";
617
- LabelDirection[LabelDirection["Right"] = 3] = "Right";
618
- })(LabelDirection || (LabelDirection = {}));
619
- /**
620
- * Manages label collision detection across multiple line series in line charts.
621
- * Tracks the bounding boxes of all registered labels and detects overlaps.
622
- * Supports scenario-based priority: when labels collide and cannot be repositioned,
623
- * lower-priority scenario labels are hidden (AC > PP > FC > PL).
624
- *
625
- * Uses 4-direction placement: Above, Below, Left, Right.
626
- */
627
- class LabelCollisionManager {
628
- constructor() {
629
- this.labels = [];
630
- this.scenarioLabels = [];
631
- }
632
- /**
633
- * Clears all registered labels. Call this before drawing a new chart.
634
- */
635
- clear() {
636
- this.labels = [];
637
- this.scenarioLabels = [];
638
- }
639
- /**
640
- * Registers a label's bounding box for collision detection.
641
- */
642
- register(bounds) {
643
- this.labels.push(bounds);
644
- }
645
- /**
646
- * Checks if a label at the given bounds would collide with any existing labels.
647
- */
648
- hasCollision(bounds) {
649
- return this.labels.some((existing) => this.intersects(bounds, existing));
650
- }
651
- /**
652
- * Tries each direction in priorityOrder to find a non-colliding placement.
653
- * Returns the first non-colliding LabelPlacement, or null if all 4 collide
654
- * with higher-priority scenario labels (meaning this label should be hidden).
655
- *
656
- * @param centerX Center X position of the marker
657
- * @param markerY Y position of the marker center
658
- * @param width Estimated label width
659
- * @param height Estimated label height
660
- * @param pointIndex The data point index
661
- * @param markerSize The marker size
662
- * @param scenarioType e.g. "ac", "pp", "fc", "pl"
663
- * @param priorityOrder Directions to try, in priority order
664
- */
665
- getOptimalPlacement(centerX, markerY, width, height, pointIndex, markerSize, scenarioType, priorityOrder) {
666
- const priority = SCENARIO_PRIORITY[scenarioType] || 99;
667
- const gap = 8;
668
- const halfMarker = markerSize / 2;
669
- // Try each direction in the caller's preferred order
670
- for (const direction of priorityOrder) {
671
- const placement = this.calculatePlacementForDirection(centerX, markerY, width, height, pointIndex, halfMarker, gap, direction);
672
- if (!this.hasCollision(placement.bounds)) {
673
- return placement;
674
- }
675
- }
676
- // All 4 positions collide. Check if any collide ONLY with lower-priority
677
- // labels (meaning we could still place here — the other label would lose).
678
- // But to keep it simple: hide only if all positions collide with higher-priority labels.
679
- for (const direction of priorityOrder) {
680
- const placement = this.calculatePlacementForDirection(centerX, markerY, width, height, pointIndex, halfMarker, gap, direction);
681
- if (!this.collidesWithHigherPriority(placement.bounds, priority)) {
682
- // This position only collides with equal or lower priority — claim it
683
- return placement;
684
- }
685
- }
686
- // All positions collide with higher-priority labels — hide
687
- return null;
688
- }
689
- /**
690
- * Computes the LabelPlacement for a given direction.
691
- */
692
- calculatePlacementForDirection(centerX, markerY, width, height, pointIndex, halfMarker, gap, direction) {
693
- let labelX;
694
- let labelY;
695
- let verticalHook;
696
- let horizontalHook;
697
- let boundsX;
698
- let boundsY;
699
- switch (direction) {
700
- case LabelDirection.Above:
701
- labelX = centerX;
702
- labelY = markerY - halfMarker - gap;
703
- verticalHook = HookLocation.Bottom;
704
- horizontalHook = HookLocation.Center;
705
- boundsX = centerX - width / 2;
706
- boundsY = markerY - halfMarker - gap - height;
707
- break;
708
- case LabelDirection.Below:
709
- labelX = centerX;
710
- labelY = markerY + halfMarker + gap;
711
- verticalHook = HookLocation.Top;
712
- horizontalHook = HookLocation.Center;
713
- boundsX = centerX - width / 2;
714
- // Top hook shifts text up by height/4, so bounds start earlier
715
- boundsY = markerY + halfMarker + gap - height / 4;
716
- break;
717
- case LabelDirection.Left:
718
- labelX = centerX - halfMarker - gap;
719
- labelY = markerY;
720
- verticalHook = HookLocation.Center;
721
- horizontalHook = HookLocation.Right;
722
- boundsX = centerX - halfMarker - gap - width;
723
- // Center hook shifts text up by height*0.6
724
- boundsY = markerY - height * 0.6;
725
- break;
726
- case LabelDirection.Right:
727
- labelX = centerX + halfMarker + gap;
728
- labelY = markerY;
729
- verticalHook = HookLocation.Center;
730
- horizontalHook = HookLocation.Left;
731
- boundsX = centerX + halfMarker + gap;
732
- // Center hook shifts text up by height*0.6
733
- boundsY = markerY - height * 0.6;
734
- break;
735
- }
736
- const bounds = {
737
- x: boundsX,
738
- y: boundsY,
739
- width,
740
- height,
741
- pointIndex,
742
- preferredHook: verticalHook,
743
- };
744
- return { labelX, labelY, verticalHook, horizontalHook, bounds };
745
- }
746
- /**
747
- * Checks if bounds collide with any registered label that has higher priority.
748
- */
749
- collidesWithHigherPriority(bounds, priority) {
750
- return this.labels.some((existing) => {
751
- if (!existing.scenarioType)
752
- return false;
753
- const existingPriority = SCENARIO_PRIORITY[existing.scenarioType] || 99;
754
- return existingPriority < priority && this.intersects(bounds, existing);
755
- });
756
- }
757
- /**
758
- * Checks whether a scenario label at the end of a line should be hidden
759
- * because it's too close to a higher-priority scenario label.
760
- */
761
- shouldHideScenarioLabel(x, y, scenarioType, proximityThreshold = 20) {
762
- const priority = SCENARIO_PRIORITY[scenarioType] || 99;
763
- if (priority <= 1)
764
- return false; // AC is never hidden
765
- return this.scenarioLabels.some((existing) => {
766
- const existingPriority = SCENARIO_PRIORITY[existing.scenarioType] || 99;
767
- if (existingPriority >= priority)
768
- return false;
769
- const dy = Math.abs(y - existing.y);
770
- const dx = Math.abs(x - existing.x);
771
- return dy < proximityThreshold && dx < proximityThreshold;
772
- });
773
- }
774
- /**
775
- * Registers a scenario label position for proximity checking.
776
- */
777
- registerScenarioLabel(x, y, scenarioType) {
778
- this.scenarioLabels.push({ x, y, scenarioType });
779
- }
780
- /**
781
- * Checks if two bounding boxes intersect (overlap).
782
- */
783
- intersects(a, b) {
784
- return !(a.x + a.width < b.x || // a is completely to the left of b
785
- b.x + b.width < a.x || // b is completely to the left of a
786
- a.y + a.height < b.y || // a is completely above b
787
- b.y + b.height < a.y // b is completely above a
788
- );
789
- }
790
- /**
791
- * Gets the number of registered labels.
792
- */
793
- getLabelCount() {
794
- return this.labels.length;
795
- }
796
- }
797
-
798
- /**
799
- * A single renderable data point in a time-series chart.
800
- *
801
- * Encapsulates a numeric value, its IBCS scenario type, and the vertical scale factor.
802
- * Provides scaling and variance styling logic used by the chart renderer.
803
- *
804
- * Variance direction follows IBCS convention: the declared variance ("pos"/"neg") applies
805
- * to non-negative values; for negative values, the style is flipped (pos becomes neg and
806
- * vice versa) so that visual encoding always reflects the economic meaning.
807
- */
808
- class DataPoint {
809
- constructor(value, scenario, pixelPerUnit, variance) {
810
- this.value = value;
811
- this.scenario = scenario;
812
- this.pixelPerUnit = pixelPerUnit || 1;
813
- if (variance === "neg" || variance === Scenario.NEG) {
814
- this.variance = Scenario.NEG;
815
- }
816
- else if (variance === "pos" || variance === Scenario.POS) {
817
- this.variance = Scenario.POS;
818
- }
819
- else {
820
- this.variance = Scenario.NEU;
821
- }
822
- }
823
- isEmpty() {
824
- return undefined === this.value || null == this.scenario;
825
- }
826
- /** Returns the value scaled to pixel height for absolute (non-percentage) bars. */
827
- getScaledUnit() {
828
- if (this.value == null) {
829
- return 0;
830
- }
831
- return this.value * this.pixelPerUnit;
832
- }
833
- /**
834
- * Returns the percentage value scaled to pixel height, clipped at +/-145%.
835
- *
836
- * Values beyond +/-1.45 (145%) are clamped to prevent extreme bars from
837
- * distorting the chart layout. Use {@link isClipped} to check if clipping occurred.
838
- */
839
- getScaledPercentUnit() {
840
- if (this.value == null) {
841
- return 0;
842
- }
843
- if (this.value > 1.45) {
844
- return 1.45 * this.pixelPerUnit;
845
- }
846
- if (this.value < -1.45) {
847
- return -1.45 * this.pixelPerUnit;
848
- }
849
- return this.value * this.pixelPerUnit;
850
- }
851
- /**
852
- * Returns the IBCS variance color style, flipping pos/neg for negative values.
853
- *
854
- * IBCS rule: a "positive variance" on a negative value is economically unfavorable,
855
- * so the visual style must invert. NEU (neutral) is never flipped.
856
- */
857
- getVarianceStyle() {
858
- if (this.value == null) {
859
- return this.variance;
860
- }
861
- if (this.value >= 0) {
862
- return this.variance;
863
- }
864
- //flip the style
865
- if (Scenario.NEU === this.variance) {
866
- return Scenario.NEU;
867
- }
868
- if (Scenario.POS === this.variance) {
869
- return Scenario.NEG;
870
- }
871
- return Scenario.POS;
872
- }
873
- /** Returns true if the percentage value exceeds the +/-145% clipping threshold. */
874
- isClipped() {
875
- if (this.value == null) {
876
- return false;
877
- }
878
- return Math.abs(this.value) > 1.45;
879
- }
880
- /** Returns the fixed display value (145) shown on clipped percentage bars. */
881
- getClippedValue() {
882
- return 145;
883
- }
884
- /** Extracts the 2-character scenario type prefix (e.g. "ac" from "ac1", "pl" from "pl2"). */
885
- getScenario() {
886
- var _a;
887
- return (_a = this.scenario) === null || _a === void 0 ? void 0 : _a.slice(0, 2);
888
- }
889
- }
890
-
891
- // import { IAdapter } from "../../../../utils/helper/IAdapter";
892
- // import { CompareUtil } from "../../../../utils/helper/CompareUtil";
893
- /**
894
- * IBCS-compliant data row for time-series chart visualizations.
895
- *
896
- * Extends the standard table data row schema with a Luxon {@link DateTime} field for temporal
897
- * positioning on the x-axis. Shares the same three-level row hierarchy, two-level column hierarchy,
898
- * and 16 scenario value slots as {@link TableDataRow}.
899
- */
900
- class TimeChartDataRow {
901
- constructor() {
902
- this.operation = "+";
903
- }
904
- addRowGroup(name, index) {
905
- this.rowGroup = name;
906
- this.rowGroupIndex = index;
907
- }
908
- addCategory(name, index) {
909
- this.category = name;
910
- this.categoryIndex = index;
911
- }
912
- addSubCategory(name, index) {
913
- this.subCategory = name;
914
- this.subCategoryIndex = index;
915
- }
916
- addColumnGroup(name, index) {
917
- this.columnGroup = name;
918
- this.columnGroupIndex = index;
919
- }
920
- addSubColumnGroup(name, index) {
921
- this.columnSubGroup = name;
922
- this.columnSubGroupIndex = index;
923
- }
924
- }
925
- /**
926
- * Converts untyped JSON records into validated {@link TimeChartDataRow} instances.
927
- *
928
- * Parses the `date` field from an ISO 8601 string into a Luxon DateTime.
929
- * Invalid dates are silently dropped (field remains undefined).
930
- */
931
- class TimeChartDataRowAdapter {
932
- constructor() { }
933
- adapt(data) {
934
- const dataRow = new TimeChartDataRow();
935
- if (CompareUtil.isString(data.date)) {
936
- dataRow.date = this.parseDateString(data.date);
937
- }
938
- //if (CompareUtil.isExisting(data.date)) {
939
- // else if (CompareUtil.isDate(data.date)) {
940
- // dataRow.date = data.date;
941
- // }
942
- //}
943
- if (CompareUtil.isOperator(data.operation)) {
944
- dataRow.operation = data.operation;
945
- }
946
- if (CompareUtil.isNumber(data.rowGroupIndex) && CompareUtil.isString(data.rowGroup)) {
947
- dataRow.addRowGroup(data.rowGroup, data.rowGroupIndex);
948
- }
949
- if (CompareUtil.isNumber(data.categoryIndex) && CompareUtil.isString(data.category)) {
950
- dataRow.addCategory(data.category, data.categoryIndex);
951
- }
952
- if (CompareUtil.isNumber(data.subCategoryIndex) && CompareUtil.isString(data.subCategory)) {
953
- dataRow.addSubCategory(data.subCategory, data.subCategoryIndex);
954
- }
955
- if (CompareUtil.isNumber(data.columnGroupIndex) && CompareUtil.isString(data.columnGroup)) {
956
- dataRow.addColumnGroup(data.columnGroup, data.columnGroupIndex);
957
- }
958
- if (CompareUtil.isNumber(data.columnSubGroupIndex) && CompareUtil.isString(data.columnSubGroup)) {
959
- dataRow.addSubColumnGroup(data.columnSubGroup, data.columnSubGroupIndex);
960
- }
961
- this.setActualValues(data, dataRow);
962
- this.setPlanValues(data, dataRow);
963
- this.setPreviousPeriodValues(data, dataRow);
964
- this.setForecastValues(data, dataRow);
965
- return dataRow;
966
- }
967
- parseDateString(date) {
968
- const timestamp = DateTime.fromISO(date);
969
- if (timestamp.isValid) {
970
- return timestamp;
971
- }
972
- console.warn(`TimeChartDataRow: invalid date value '${date}' — skipping row`);
973
- return undefined;
974
- }
975
- default() {
976
- return new TimeChartDataRow();
977
- }
978
- setActualValues(data, dataRow) {
979
- if (CompareUtil.isNumber(data.ac1)) {
980
- dataRow.ac1 = data.ac1;
981
- }
982
- if (CompareUtil.isNumber(data.ac2)) {
983
- dataRow.ac2 = data.ac2;
984
- }
985
- if (CompareUtil.isNumber(data.ac3)) {
986
- dataRow.ac3 = data.ac3;
987
- }
988
- if (CompareUtil.isNumber(data.ac4)) {
989
- dataRow.ac4 = data.ac4;
990
- }
991
- }
992
- setPlanValues(data, dataRow) {
993
- if (CompareUtil.isNumber(data.pl1)) {
994
- dataRow.pl1 = data.pl1;
995
- }
996
- if (CompareUtil.isNumber(data.pl2)) {
997
- dataRow.pl2 = data.pl2;
998
- }
999
- if (CompareUtil.isNumber(data.pl3)) {
1000
- dataRow.pl3 = data.pl3;
1001
- }
1002
- if (CompareUtil.isNumber(data.pl4)) {
1003
- dataRow.pl4 = data.pl4;
1004
- }
1005
- }
1006
- setPreviousPeriodValues(data, dataRow) {
1007
- if (CompareUtil.isNumber(data.pp1)) {
1008
- dataRow.pp1 = data.pp1;
1009
- }
1010
- if (CompareUtil.isNumber(data.pp2)) {
1011
- dataRow.pp2 = data.pp2;
1012
- }
1013
- if (CompareUtil.isNumber(data.pp3)) {
1014
- dataRow.pp3 = data.pp3;
1015
- }
1016
- if (CompareUtil.isNumber(data.pp4)) {
1017
- dataRow.pp4 = data.pp4;
1018
- }
1019
- }
1020
- setForecastValues(data, dataRow) {
1021
- if (CompareUtil.isNumber(data.fc1)) {
1022
- dataRow.fc1 = data.fc1;
1023
- }
1024
- if (CompareUtil.isNumber(data.fc2)) {
1025
- dataRow.fc2 = data.fc2;
1026
- }
1027
- if (CompareUtil.isNumber(data.fc3)) {
1028
- dataRow.fc3 = data.fc3;
1029
- }
1030
- if (CompareUtil.isNumber(data.fc4)) {
1031
- dataRow.fc4 = data.fc4;
1032
- }
1033
- }
1034
- }
1035
-
1036
- // import { IAdapter } from "../../../../../utils/helper/IAdapter";
1037
- // import { SVGPolgonPattern } from "../../../../../utils/model";
1038
- /** Aggregates all style configuration for a time chart: scale factors, fonts, colors, patterns, and padding. */
1039
- class TimeChartStyle {
1040
- constructor(scaleFactors, fontStyles, axisStyles, barStyles, varianceStyles, padding) {
1041
- this.scaleFactors = scaleFactors;
1042
- this.fontStyles = fontStyles;
1043
- this.axisStyles = axisStyles;
1044
- this.barStyles = barStyles;
1045
- this.varianceStyles = varianceStyles;
1046
- this.padding = padding;
1047
- this.pattern = new Map();
1048
- this.stackColors = ["#000000", "#c0c0c0", "#808080"];
1049
- }
1050
- }
1051
- /** Adapts raw componentStyle JSON into a TimeChartStyle, falling back to defaults for missing properties. */
1052
- class TimeChartStylesAdapter {
1053
- constructor(scaleFactorsStructureChartAdapter, fontStyleAdapter, svgStyleGroupAdapter, svgVariancesStyleGroupAdapter, paddingadapter) {
1054
- this.scaleFactorsStructureChartAdapter = scaleFactorsStructureChartAdapter;
1055
- this.fontStyleAdapter = fontStyleAdapter;
1056
- this.svgStyleGroupAdapter = svgStyleGroupAdapter;
1057
- this.svgVariancesStyleGroupAdapter = svgVariancesStyleGroupAdapter;
1058
- this.paddingadapter = paddingadapter;
1059
- }
1060
- adapt(data) {
1061
- const styles = new TimeChartStyle(this.scaleFactorsStructureChartAdapter.default(), this.fontStyleAdapter.default(), this.svgStyleGroupAdapter.default(), this.svgStyleGroupAdapter.default(), this.svgVariancesStyleGroupAdapter.default(), this.paddingadapter.default());
1062
- if (CompareUtil.isExisting(data)) {
1063
- if (CompareUtil.isExisting(data.scaleFactors)) {
1064
- styles.scaleFactors = this.scaleFactorsStructureChartAdapter.adapt(data.scaleFactors);
1065
- }
1066
- if (CompareUtil.isExisting(data.fontStyles)) {
1067
- styles.fontStyles = this.fontStyleAdapter.adapt(data.fontStyles);
1068
- }
1069
- if (CompareUtil.isExisting(data.axisStyles)) {
1070
- styles.axisStyles = this.svgStyleGroupAdapter.adapt(data.axisStyles);
1071
- }
1072
- if (CompareUtil.isExisting(data.barStyles)) {
1073
- styles.barStyles = this.svgStyleGroupAdapter.adapt(data.barStyles);
1074
- }
1075
- if (CompareUtil.isExisting(data.varianceStyles)) {
1076
- styles.varianceStyles = this.svgVariancesStyleGroupAdapter.adapt(data.varianceStyles);
1077
- }
1078
- if (CompareUtil.isExisting(data.padding)) {
1079
- styles.padding = this.paddingadapter.adapt(data.padding);
1080
- }
1081
- if (Array.isArray(data.stackColors) && data.stackColors.length > 0) {
1082
- styles.stackColors = data.stackColors;
1083
- }
1084
- styles.pattern = new MarkerPattern(styles.fontStyles.size).createPatternMapForStructureBar();
1085
- }
1086
- return styles;
1087
- }
1088
- default() {
1089
- return new TimeChartStyle(this.scaleFactorsStructureChartAdapter.default(), this.fontStyleAdapter.default(), this.svgStyleGroupAdapter.default(), this.svgStyleGroupAdapter.default(), this.svgVariancesStyleGroupAdapter.default(), this.paddingadapter.default());
1090
- }
1091
- }
1092
-
1093
- /**
1094
- * IBCS scenario enumeration for time-series charts.
1095
- *
1096
- * Includes all 16 scenario slots (4 each of ac, pp, fc, pl) plus three
1097
- * variance direction markers: POS (positive/favorable), NEG (negative/unfavorable),
1098
- * NEU (neutral).
1099
- */
1100
- var Scenario;
1101
- (function (Scenario) {
1102
- Scenario["AC1"] = "ac1";
1103
- Scenario["PP1"] = "pp1";
1104
- Scenario["FC1"] = "fc1";
1105
- Scenario["PL1"] = "pl1";
1106
- Scenario["AC2"] = "ac2";
1107
- Scenario["PP2"] = "pp2";
1108
- Scenario["FC2"] = "fc2";
1109
- Scenario["PL2"] = "pl2";
1110
- Scenario["AC3"] = "ac3";
1111
- Scenario["PP3"] = "pp3";
1112
- Scenario["FC3"] = "fc3";
1113
- Scenario["PL3"] = "pl3";
1114
- Scenario["AC4"] = "ac4";
1115
- Scenario["PP4"] = "pp4";
1116
- Scenario["FC4"] = "fc4";
1117
- Scenario["PL4"] = "pl4";
1118
- /** Positive/favorable variance (rendered in green per IBCS). */
1119
- Scenario["POS"] = "pos";
1120
- /** Negative/unfavorable variance (rendered in red per IBCS). */
1121
- Scenario["NEG"] = "neg";
1122
- /** Neutral variance (rendered in grey per IBCS). */
1123
- Scenario["NEU"] = "neu";
1124
- })(Scenario || (Scenario = {}));
1125
- /** Chart-internal table aggregation modes. */
1126
- var TableType;
1127
- (function (TableType) {
1128
- TableType["LIST"] = "LIST";
1129
- TableType["SUM"] = "SUM";
1130
- TableType["OPT"] = "OPT";
1131
- })(TableType || (TableType = {}));
1132
-
1133
- /**
1134
- * Renders the horizontal baseline axis for a time chart.
1135
- *
1136
- * The axis line spans from the left padding to the end of the data area.
1137
- * A CSS class based on the scenario type (e.g. "axis-ac", "axis-pp") is applied
1138
- * to control stroke style (solid for AC, dashed for FC, etc. per IBCS rules).
1139
- * An optional title label (e.g. "AC" or variance expression) is drawn above the axis.
1140
- */
1141
- class Axis {
1142
- constructor(axis, position, svgParentGroup) {
1143
- this.ID_AXIS = "axis";
1144
- this.CSS_AXIS_TITLE = "categories";
1145
- this.scenarioType = axis.scenarioType;
1146
- this.labelText = axis.labelText || null;
1147
- this.isRelative = axis.isRelative || false;
1148
- this.position = position;
1149
- this.svgGroup = svgParentGroup.group().id(this.ID_AXIS);
1150
- }
1151
- drawAxisTitle(group, text) {
1152
- if (null == text) {
1153
- text = "";
1154
- }
1155
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1156
- const title = group.text(text).addClass(this.CSS_AXIS_TITLE).attr("text-anchor", "middle");
1157
- title.move(this.position.getAxisTitlePositionX(group), this.position.getAxisTitlePositionY(true, this.isRelative));
1158
- }
1159
- draw() {
1160
- if (this.labelText) {
1161
- this.drawAxisTitle(this.svgGroup, this.labelText);
1162
- }
1163
- this.svgGroup
1164
- .line(this.position.getAxisPositionX(), this.position.getAxisPositionY(this.isRelative), this.position.getAxisEndPositionX(), this.position.getAxisPositionY(this.isRelative))
1165
- .addClass(this.ID_AXIS + "-" + this.convertScenarioType());
1166
- return this;
1167
- }
1168
- convertScenarioType() {
1169
- if (this.scenarioType === undefined || this.scenarioType == null) {
1170
- return "default";
1171
- }
1172
- return `${this.scenarioType}`.slice(0, 2);
1173
- }
1174
- }
1175
-
1176
- // import { DataFormatDigits } from "../../../../utils/model/DataFormatDigits";
1177
- // import { SiPrefix } from "../../../../utils/model/SiPrefix";
1178
- /**
1179
- * Renders a vertical bar (column) in an IBCS time chart.
1180
- *
1181
- * Coordinate system: SVG Y-axis is inverted -- positive values grow upward from the
1182
- * axis baseline, so yPos decreases as value increases. Negative values extend downward.
1183
- *
1184
- * Overflow handling: When a bar exceeds the available chart height (determined by
1185
- * OverflowConfig), the bar is split into a base segment and an overdrive segment
1186
- * separated by a zigzag break indicator. The overdrive zone maps the overflow amount
1187
- * proportionally into a fixed pixel region so all overflowing bars remain comparable.
1188
- *
1189
- * Primary columns (AC foreground) carry data labels and scenario labels;
1190
- * secondary columns (PP background) render without labels by default.
1191
- */
1192
- class Column {
1193
- constructor(position, styles, dataPoint, index, isPrimaryColumn, scenarioGroup, columnLabel, overflowConfig = null) {
1194
- this.ID_DATA_PREFIX = "DATA";
1195
- this.ID_SCENARIO_PREFIX = "SCENARIO";
1196
- this.ID_RECT = "RECT";
1197
- this.FALLBACK_COLOUR = "#000000";
1198
- this.label = null;
1199
- this.scenarioLabel = null;
1200
- this.isVarianceColumn = false;
1201
- this.overflowConfig = null;
1202
- this.isOverflowing = false;
1203
- this.overdriveHeight = 0;
1204
- this.dimensions = {
1205
- columnLength: 0,
1206
- xPos: 0,
1207
- yPos: 0,
1208
- labelYPos: 0,
1209
- scenarioLabelXPos: 0,
1210
- scenarioLabelYPos: 0,
1211
- clipped: false,
1212
- };
1213
- this.hasData = false;
1214
- this.dataPoint = dataPoint;
1215
- this.index = index;
1216
- this.isPrimaryColumn = isPrimaryColumn;
1217
- this.position = position;
1218
- this.columnBarStyles = styles.barStyles;
1219
- this.overflowConfig = overflowConfig;
1220
- this.scenarioGroup = scenarioGroup;
1221
- this.styles = styles;
1222
- this.columnGroup = scenarioGroup.group().id(scenarioGroup.toString() + "_" + this.ID_RECT);
1223
- if ((dataPoint === null || dataPoint === void 0 ? void 0 : dataPoint.isEmpty()) !== true) {
1224
- this.hasData = true;
1225
- this.dimensions = this.createDimensions(dataPoint, index, isPrimaryColumn);
1226
- this.label = this.getDataLabel(dataPoint);
1227
- this.scenarioLabel = this.getScenarioLabel(columnLabel);
1228
- }
1229
- }
1230
- setAsVariance() {
1231
- var _a;
1232
- this.isVarianceColumn = true;
1233
- (_a = this.label) === null || _a === void 0 ? void 0 : _a.setToVarianceLabel();
1234
- return this;
1235
- }
1236
- updateLabelGroup(newGroup) {
1237
- var _a;
1238
- if (this.isEmpty()) {
1239
- return this;
1240
- }
1241
- (_a = this.label) === null || _a === void 0 ? void 0 : _a.updateGroup(newGroup);
1242
- return this;
1243
- }
1244
- draw(dataFormatDigits = { percent: 2, decimal: 1 }, measureScale = new SiPrefix()) {
1245
- // TODE: JHE: Remove DataFOrmatDigits Type Duplicates
1246
- if (this.isEmpty()) {
1247
- return this;
1248
- }
1249
- const scenarioStyle = this.getScenarioStyle();
1250
- const strokeStyle = this.convertToSVGStyle(scenarioStyle, "stroke");
1251
- const fillStyle = this.getFillStyle(scenarioStyle);
1252
- if (this.columnGroup != null) {
1253
- if (this.isOverflowing && this.overflowConfig) {
1254
- this.drawOverdriveBar(fillStyle, strokeStyle);
1255
- }
1256
- else {
1257
- this.columnGroup
1258
- .rect(this.position.getColumnWidth(), this.dimensions.columnLength)
1259
- .fill(fillStyle)
1260
- .stroke(strokeStyle)
1261
- .y(this.dimensions.yPos)
1262
- .cx(this.dimensions.xPos);
1263
- }
1264
- }
1265
- this.drawColumnDataLabel(dataFormatDigits, measureScale);
1266
- this.drawScenarioLabel();
1267
- }
1268
- /**
1269
- * Draws a broken bar: base segment + break gap + overdrive segment.
1270
- * The break gap is filled with a white background and zigzag lines.
1271
- */
1272
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1273
- drawOverdriveBar(fillStyle, strokeStyle) {
1274
- if (!this.columnGroup || !this.overflowConfig)
1275
- return;
1276
- const axisY = this.position.getColumnPositionY();
1277
- const colWidth = this.position.getColumnWidth();
1278
- const effectiveCut = this.dimensions.columnLength; // scenario-aware cut height
1279
- const { breakGap } = this.overflowConfig;
1280
- // Base bar: from axis up to effective cut height
1281
- const baseY = axisY - effectiveCut;
1282
- this.columnGroup.rect(colWidth, effectiveCut).fill(fillStyle).stroke(strokeStyle).y(baseY).cx(this.dimensions.xPos);
1283
- // Overdrive bar: above the break gap
1284
- const overdriveY = baseY - breakGap - this.overdriveHeight;
1285
- this.columnGroup
1286
- .rect(colWidth, this.overdriveHeight)
1287
- .fill(fillStyle)
1288
- .stroke(strokeStyle)
1289
- .y(overdriveY)
1290
- .cx(this.dimensions.xPos);
1291
- // Break indicator: zigzag lines across bar width
1292
- this.drawBreakIndicator(baseY, breakGap);
1293
- }
1294
- /** Draws top and bottom zigzag lines across the column width to indicate a broken axis. */
1295
- drawBreakIndicator(baseY, breakGap) {
1296
- if (!this.columnGroup)
1297
- return;
1298
- const colWidth = this.position.getColumnWidth();
1299
- const xLeft = this.dimensions.xPos - colWidth / 2;
1300
- const midY = baseY - breakGap / 2;
1301
- const halfGap = breakGap * 0.35;
1302
- const zigCount = 3;
1303
- const segWidth = colWidth / zigCount;
1304
- // Top zigzag line
1305
- let topPath = `M ${xLeft} ${midY - halfGap}`;
1306
- for (let i = 0; i < zigCount; i++) {
1307
- const x1 = xLeft + segWidth * (i + 0.5);
1308
- const x2 = xLeft + segWidth * (i + 1);
1309
- const yPeak = midY - halfGap - breakGap * 0.3;
1310
- topPath += ` L ${x1} ${yPeak} L ${x2} ${midY - halfGap}`;
1311
- }
1312
- // Bottom zigzag line
1313
- let bottomPath = `M ${xLeft} ${midY + halfGap}`;
1314
- for (let i = 0; i < zigCount; i++) {
1315
- const x1 = xLeft + segWidth * (i + 0.5);
1316
- const x2 = xLeft + segWidth * (i + 1);
1317
- const yPeak = midY + halfGap + breakGap * 0.3;
1318
- bottomPath += ` L ${x1} ${yPeak} L ${x2} ${midY + halfGap}`;
1319
- }
1320
- // White background to cover the bar behind the break
1321
- this.columnGroup
1322
- .rect(colWidth + 2, breakGap)
1323
- .fill("#ffffff")
1324
- .stroke("none")
1325
- .y(baseY - breakGap)
1326
- .cx(this.dimensions.xPos);
1327
- this.columnGroup.path(topPath).fill("none").stroke({ color: "#000000", width: 1 });
1328
- this.columnGroup.path(bottomPath).fill("none").stroke({ color: "#000000", width: 1 });
1329
- }
1330
- /**
1331
- * Computes the pixel geometry for the column: position, height, label anchors.
1332
- * Handles three cases: overflow (broken bar), negative value, and normal positive.
1333
- * For overflow, the column is capped at effectiveCut height and an overdrive zone is added.
1334
- */
1335
- createDimensions(dataPoint, index, isPrimaryBar) {
1336
- const scaledUnit = dataPoint.getScaledUnit();
1337
- // Determine effective cut height: AC scenarios use full cutHeight, others break lower
1338
- if (this.overflowConfig && scaledUnit > 0) {
1339
- const isAC = dataPoint.getScenario() === "ac";
1340
- const effectiveCut = isAC
1341
- ? this.overflowConfig.cutHeight
1342
- : this.overflowConfig.cutHeight - this.overflowConfig.scenarioCutOffset;
1343
- if (scaledUnit > effectiveCut) {
1344
- this.isOverflowing = true;
1345
- const { breakGap, overdriveZoneHeight, maxOverflow } = this.overflowConfig;
1346
- const overflowAmount = scaledUnit - effectiveCut;
1347
- this.overdriveHeight = maxOverflow > 0 ? (overflowAmount / maxOverflow) * overdriveZoneHeight : 0;
1348
- const totalVisualHeight = effectiveCut + breakGap + this.overdriveHeight;
1349
- const axisY = this.position.getColumnPositionY();
1350
- return {
1351
- clipped: false,
1352
- columnLength: effectiveCut,
1353
- xPos: this.position.getColumnPositionX(index, isPrimaryBar),
1354
- yPos: axisY - effectiveCut,
1355
- labelYPos: axisY - totalVisualHeight - this.position.spacings.labelToColumn,
1356
- scenarioLabelXPos: this.position.getColumnPositionX(index, isPrimaryBar) +
1357
- this.position.getScenarioLabelPositionOffsetX(isPrimaryBar),
1358
- scenarioLabelYPos: axisY - effectiveCut * 0.5,
1359
- };
1360
- }
1361
- }
1362
- if (scaledUnit < 0) {
1363
- return {
1364
- clipped: false,
1365
- columnLength: Math.abs(scaledUnit),
1366
- xPos: this.position.getColumnPositionX(index, isPrimaryBar),
1367
- yPos: this.position.getColumnPositionY(),
1368
- labelYPos: this.position.getColumnDataLabelPositionY(scaledUnit),
1369
- scenarioLabelXPos: this.position.getColumnPositionX(index, isPrimaryBar) +
1370
- this.position.getScenarioLabelPositionOffsetX(isPrimaryBar),
1371
- scenarioLabelYPos: this.position.getColumnPositionY() + Math.abs(scaledUnit) * 0.5,
1372
- };
1373
- }
1374
- else {
1375
- return {
1376
- clipped: false,
1377
- columnLength: scaledUnit,
1378
- xPos: this.position.getColumnPositionX(index, isPrimaryBar),
1379
- yPos: this.position.getColumnPositionY() - scaledUnit,
1380
- labelYPos: this.position.getColumnDataLabelPositionY(scaledUnit),
1381
- scenarioLabelXPos: this.position.getColumnPositionX(index, isPrimaryBar) +
1382
- this.position.getScenarioLabelPositionOffsetX(isPrimaryBar),
1383
- scenarioLabelYPos: this.position.getColumnPositionY() - Math.abs(scaledUnit) * 0.5,
1384
- };
1385
- }
1386
- }
1387
- getDataLabel(dataPoint) {
1388
- let labelHook = HookLocation.Bottom;
1389
- if (dataPoint.value != null && dataPoint.value < 0) {
1390
- labelHook = HookLocation.Top;
1391
- }
1392
- const labelY = this.isOverflowing
1393
- ? this.dimensions.labelYPos
1394
- : this.position.getColumnDataLabelPositionY(this.dataPoint.getScaledUnit());
1395
- return new Label(this.scenarioGroup, this.position.getColumnCenterPositionX(this.index), labelY, this.ID_DATA_PREFIX, dataPoint.value, this.styles, labelHook, HookLocation.Center);
1396
- }
1397
- getScenarioLabel(columnLabel) {
1398
- if (this.isPrimaryColumn) {
1399
- return new Label(this.scenarioGroup, -1, -1, this.ID_SCENARIO_PREFIX, columnLabel, this.styles, HookLocation.Center, HookLocation.Left);
1400
- }
1401
- return new Label(this.scenarioGroup, -1, -1, this.ID_SCENARIO_PREFIX, columnLabel, this.styles, HookLocation.Center, HookLocation.Right);
1402
- }
1403
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1404
- convertToSVGStyle(style, mode) {
1405
- if (style == null) {
1406
- style = [];
1407
- }
1408
- style["color"] = style[mode] || this.FALLBACK_COLOUR;
1409
- return Object.assign({}, style);
1410
- }
1411
- drawScenarioLabel() {
1412
- if (this.scenarioLabel != null && !this.scenarioLabel.isEmpty() && !this.isVarianceColumn) {
1413
- this.scenarioLabel.setPos(this.dimensions.scenarioLabelXPos, this.dimensions.scenarioLabelYPos).draw(true);
1414
- }
1415
- }
1416
- drawColumnDataLabel(dataFormatDigits, measureScale = new SiPrefix()) {
1417
- var _a;
1418
- (_a = this.label) === null || _a === void 0 ? void 0 : _a.draw(this.isPrimaryColumn, dataFormatDigits, measureScale);
1419
- }
1420
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1421
- getFillStyle(scenarioStyle) {
1422
- var _a, _b, _c, _d;
1423
- const pattern = this.columnBarStyles[this.dataPoint.getScenario()];
1424
- if ((pattern === null || pattern === void 0 ? void 0 : pattern.fillpattern) && ((_a = this.styles.pattern.get(pattern.fillpattern)) === null || _a === void 0 ? void 0 : _a.pattern)) {
1425
- return (_d = (_c = (_b = this.styles) === null || _b === void 0 ? void 0 : _b.pattern) === null || _c === void 0 ? void 0 : _c.get(pattern.fillpattern)) === null || _d === void 0 ? void 0 : _d.pattern;
1426
- }
1427
- return this.convertToSVGStyle(scenarioStyle, "fill");
1428
- }
1429
- getScenarioStyle() {
1430
- var _a;
1431
- if (this.isVarianceColumn) {
1432
- return (_a = this.styles) === null || _a === void 0 ? void 0 : _a.varianceStyles.getSVGStyle(this.dataPoint.getVarianceStyle());
1433
- }
1434
- return this.columnBarStyles[this.dataPoint.getScenario()];
1435
- }
1436
- isEmpty() {
1437
- return false === this.hasData || Number.isNaN(this.dataPoint.value);
1438
- }
1439
- }
1440
-
1441
- /**
1442
- * Renders a diamond/triangle marker indicator for PP or PL reference values in a time chart.
1443
- *
1444
- * Markers are small polygon shapes (defined by SVGPolgonPattern) positioned at the
1445
- * data point's scaled value height. They consist of a white background polygon for
1446
- * contrast and a foreground polygon with scenario-specific fill/stroke.
1447
- *
1448
- * Primary markers appear to the left of the column center; secondary markers to the right.
1449
- * Each carries an optional scenario label that is drawn at the marker's data level.
1450
- */
1451
- class Marker {
1452
- constructor(position, markerGroup, markerPattern, scenario, styles, dataPoint, index, labelText, isPrimaryMarker) {
1453
- this.ID_DATA_PREFIX = "DATA";
1454
- this.ID_SCENARIO_PREFIX = "SCENARIO";
1455
- this.FALLBACK_COLOUR = "#000000";
1456
- this.scenarioLabel = null;
1457
- this._defaultMarkerPattern = null;
1458
- this.dimensions = {
1459
- columnLength: 0,
1460
- xPos: 0,
1461
- yPos: 0,
1462
- labelYPos: 0,
1463
- scenarioLabelXPos: 0,
1464
- scenarioLabelYPos: 0,
1465
- clipped: false,
1466
- };
1467
- this.hasData = false;
1468
- this.position = position;
1469
- this.markerGroup = markerGroup || null;
1470
- this.markerPattern = markerPattern || this._defaultMarkerPattern;
1471
- this.styles = styles;
1472
- this.barStyles = styles ? styles.barStyles : null;
1473
- this.scenario = scenario;
1474
- if ((dataPoint === null || dataPoint === void 0 ? void 0 : dataPoint.isEmpty()) !== true) {
1475
- this.hasData = true;
1476
- this.dimensions = this.createMarkerDimensions(dataPoint, index, isPrimaryMarker);
1477
- this.scenarioLabel = this.getScenarioLabel(labelText, styles, isPrimaryMarker);
1478
- }
1479
- }
1480
- draw() {
1481
- if (this.isEmpty()) {
1482
- return this;
1483
- }
1484
- const whiteBorder = "#ffffff";
1485
- const strokeStyle = this.convertToSVGStyle(this.barStyles[this.getScenario()], "stroke");
1486
- let fillStyle = this.convertToSVGStyle(this.barStyles[this.getScenario()], "fill");
1487
- const pattern = this.barStyles[this.getScenario()];
1488
- if (pattern != null && pattern.fillpattern) {
1489
- const polygonPattern = this.styles.pattern.get(pattern.fillpattern);
1490
- if (polygonPattern != null) {
1491
- fillStyle = polygonPattern.pattern;
1492
- }
1493
- }
1494
- this.markerGroup
1495
- .polygon(this.markerPattern.background)
1496
- .fill(whiteBorder)
1497
- .cy(this.dimensions.yPos - this.dimensions.columnLength)
1498
- .cx(this.dimensions.xPos);
1499
- this.markerGroup
1500
- .polygon(this.markerPattern.foreground)
1501
- .fill(fillStyle)
1502
- .stroke(strokeStyle)
1503
- .cy(this.dimensions.yPos - this.dimensions.columnLength)
1504
- .cx(this.dimensions.xPos);
1505
- if (this.scenarioLabel != null && !this.scenarioLabel.isEmpty()) {
1506
- this.scenarioLabel.setPos(this.dimensions.scenarioLabelXPos, this.dimensions.scenarioLabelYPos).draw();
1507
- }
1508
- return this;
1509
- }
1510
- createMarkerDimensions(dataPoint, index, isPrimaryMarker) {
1511
- if (dataPoint.getScaledUnit() < 0) {
1512
- return {
1513
- clipped: false,
1514
- labelYPos: 0,
1515
- columnLength: dataPoint.getScaledUnit(),
1516
- xPos: this.position.getMarkerPositionX(index, isPrimaryMarker),
1517
- yPos: this.position.getMarkerPositionY(),
1518
- scenarioLabelXPos: this.position.getMarkerPositionX(index, isPrimaryMarker) +
1519
- this.position.getMarkerScenarioLabelPositionOffsetX(isPrimaryMarker),
1520
- scenarioLabelYPos: this.position.getMarkerPositionY() + Math.abs(dataPoint.getScaledUnit()),
1521
- };
1522
- }
1523
- else {
1524
- return {
1525
- clipped: false,
1526
- labelYPos: 0,
1527
- columnLength: dataPoint.getScaledUnit(),
1528
- xPos: this.position.getMarkerPositionX(index, isPrimaryMarker),
1529
- yPos: this.position.getMarkerPositionY(),
1530
- scenarioLabelXPos: this.position.getMarkerPositionX(index, isPrimaryMarker) +
1531
- this.position.getMarkerScenarioLabelPositionOffsetX(isPrimaryMarker),
1532
- scenarioLabelYPos: this.position.getMarkerPositionY() - Math.abs(dataPoint.getScaledUnit()),
1533
- };
1534
- }
1535
- }
1536
- getScenarioLabel(labelText, styles, isPrimaryMarker) {
1537
- if (this.markerGroup == null) {
1538
- return null;
1539
- }
1540
- if (isPrimaryMarker) {
1541
- return new Label(this.markerGroup, -1, -1, this.ID_DATA_PREFIX, labelText, styles, HookLocation.Center, HookLocation.Right);
1542
- }
1543
- return new Label(this.markerGroup, -1, -1, this.ID_DATA_PREFIX, labelText, styles, HookLocation.Center, HookLocation.Left);
1544
- }
1545
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1546
- convertToSVGStyle(style, mode) {
1547
- if (style == null) {
1548
- style = [];
1549
- }
1550
- style["color"] = style[mode] || this.FALLBACK_COLOUR;
1551
- return Object.assign({}, style);
1552
- }
1553
- isEmpty() {
1554
- return false === this.hasData;
1555
- }
1556
- getScenario() {
1557
- var _a;
1558
- return (_a = this.scenario) === null || _a === void 0 ? void 0 : _a.slice(0, 2);
1559
- }
1560
- }
1561
-
1562
- // import {SVGVariancesStyleGroup} from "../../../../utils/model/styles/SVGVariancesStyleGroup";
1563
- /**
1564
- * Renders a relative variance pin (needle) in an IBCS time chart.
1565
- *
1566
- * A needle is a thin vertical bar representing a percentage variance value,
1567
- * topped with an arrowhead. The head style depends on clipping:
1568
- * - Normal: a rectangular crossbar (T-shape)
1569
- * - Clipped (value exceeds 145% scale): a double-arrow polygon indicating the
1570
- * value was truncated to fit the chart area
1571
- *
1572
- * The needle body uses variance-based fill (positive/negative coloring),
1573
- * while the head always uses the AC scenario style for visual emphasis.
1574
- */
1575
- class Needle {
1576
- constructor(position, styles, dataPoint, index, scenarioGroup) {
1577
- this.ID_DATA_PREFIX = "DATA";
1578
- this.ID_SCENARIO_PREFIX = "SCENARIO";
1579
- this.ID_RECT = "RECT";
1580
- this.FALLBACK_COLOUR = "#000000";
1581
- this.dataLabel = null;
1582
- this.dimensions = {
1583
- columnLength: 0,
1584
- xPos: 0,
1585
- yPos: 0,
1586
- labelYPos: 0,
1587
- scenarioLabelXPos: 0,
1588
- scenarioLabelYPos: 0,
1589
- clipped: false,
1590
- };
1591
- this.hasData = false;
1592
- this.dataPoint = dataPoint;
1593
- this.index = index;
1594
- this.position = position;
1595
- this.barStyles = styles.barStyles;
1596
- this.scenarioGroup = scenarioGroup;
1597
- this.styles = styles;
1598
- this.barGroup = scenarioGroup.group().id(scenarioGroup.toString() + "_" + this.ID_RECT);
1599
- if ((dataPoint === null || dataPoint === void 0 ? void 0 : dataPoint.isEmpty()) !== true) {
1600
- this.hasData = true;
1601
- this.dimensions = this.createDimensions(position, dataPoint, index);
1602
- this.dataLabel = new Label(this.scenarioGroup, this.position.getColumnCenterPositionX(this.index), this.position.getNeedleDataLabelPositionY(this.dataPoint.getScaledPercentUnit()), this.ID_DATA_PREFIX, dataPoint.value, this.styles, HookLocation.Center, HookLocation.Center);
1603
- this.dataLabel.setToRelativeVarianceLabel();
1604
- }
1605
- }
1606
- updateLabelGroup(newGroup) {
1607
- var _a;
1608
- if (this.isEmpty()) {
1609
- return this;
1610
- }
1611
- (_a = this.dataLabel) === null || _a === void 0 ? void 0 : _a.updateGroup(newGroup);
1612
- return this;
1613
- }
1614
- draw() {
1615
- var _a;
1616
- if (this.isEmpty()) {
1617
- return this;
1618
- }
1619
- const scenarioStyle = this.styles.varianceStyles[this.dataPoint.getVarianceStyle()];
1620
- const strokeStyle = this.convertToSVGStyle(scenarioStyle, "stroke");
1621
- let fillStyle = this.convertToSVGStyle(scenarioStyle, "fill");
1622
- const strokeStyleHead = this.convertToSVGStyle(this.styles.varianceStyles["ac"], "stroke");
1623
- const fillStyleHead = this.convertToSVGStyle(this.styles.varianceStyles["ac"], "fill");
1624
- const pattern = this.barStyles[this.dataPoint.getScenario()];
1625
- if (pattern != null && pattern.fillpattern) {
1626
- const polygonPattern = this.styles.pattern.get(pattern.fillpattern);
1627
- if (polygonPattern != null) {
1628
- fillStyle = polygonPattern.pattern;
1629
- }
1630
- }
1631
- if (this.dimensions.clipped) {
1632
- this.createClippedNeedleHead(fillStyle, strokeStyle);
1633
- }
1634
- else {
1635
- this.createNeedleHead(strokeStyleHead, fillStyleHead);
1636
- }
1637
- this.barGroup
1638
- .rect(this.position.getNeedleWidth(), this.dimensions.columnLength)
1639
- .cx(this.dimensions.xPos)
1640
- .y(this.dimensions.yPos)
1641
- .fill(fillStyle)
1642
- .stroke(strokeStyle);
1643
- (_a = this.dataLabel) === null || _a === void 0 ? void 0 : _a.draw();
1644
- }
1645
- createDimensions(position, dataPoint, index) {
1646
- if (dataPoint.getScaledPercentUnit() < 0) {
1647
- return {
1648
- labelYPos: 0,
1649
- scenarioLabelXPos: 0,
1650
- scenarioLabelYPos: 0,
1651
- columnLength: Math.abs(dataPoint.getScaledPercentUnit()),
1652
- xPos: position.getColumnCenterPositionX(index),
1653
- yPos: position.getNeedlePositionY(),
1654
- clipped: dataPoint.isClipped(),
1655
- };
1656
- }
1657
- else {
1658
- return {
1659
- columnLength: dataPoint.getScaledPercentUnit(),
1660
- xPos: position.getColumnCenterPositionX(index),
1661
- yPos: position.getNeedlePositionY() - dataPoint.getScaledPercentUnit(),
1662
- labelYPos: 0,
1663
- scenarioLabelXPos: 0,
1664
- scenarioLabelYPos: 0,
1665
- clipped: dataPoint.isClipped(),
1666
- };
1667
- }
1668
- }
1669
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1670
- convertToSVGStyle(style, mode) {
1671
- if (style == null) {
1672
- style = [];
1673
- }
1674
- style["color"] = style[mode] || this.FALLBACK_COLOUR;
1675
- return Object.assign({}, style);
1676
- }
1677
- createClippedNeedleHead(fillStyle, strokeStyle) {
1678
- const arrowUp = "0,0 5,9 -5,9 0,0 0,5 5,13 -5,13 0,5";
1679
- const head = this.barGroup
1680
- .polygon(arrowUp)
1681
- .fill(fillStyle)
1682
- .cx(this.dimensions.xPos)
1683
- .cy(this.getHeadYPosition())
1684
- .fill(fillStyle)
1685
- .stroke(strokeStyle);
1686
- if (this.dataPoint.value != null && this.dataPoint.value < 0) {
1687
- head.flip("y");
1688
- }
1689
- }
1690
- createNeedleHead(strokeStyleHead, fillStyleHead) {
1691
- this.barGroup
1692
- .rect(2 * this.position.getNeedleWidth(), this.position.getNeedleHeadWidth())
1693
- .cx(this.dimensions.xPos)
1694
- .cy(this.getHeadYPosition())
1695
- .fill(strokeStyleHead)
1696
- .stroke(fillStyleHead);
1697
- }
1698
- isEmpty() {
1699
- return false === this.hasData || Number.isNaN(this.dataPoint.value);
1700
- }
1701
- getHeadYPosition() {
1702
- let yPosition = this.dimensions.yPos;
1703
- if (this.dataPoint.value != null && this.dataPoint.value < 0) {
1704
- yPosition += this.dimensions.columnLength;
1705
- }
1706
- return yPosition;
1707
- }
1708
- }
1709
-
1710
- const IBCS_LINE_STYLES = {
1711
- ac: { markerFill: "#000000", markerStroke: "#000000", lineColor: "#000000" },
1712
- pp: { markerFill: "#999999", markerStroke: "#999999", lineColor: "#999999" },
1713
- fc: { markerFill: "#ffffff", markerStroke: "#000000", lineColor: "#000000", lineDashArray: "4,4" },
1714
- pl: { markerFill: "#ffffff", markerStroke: "#000000", lineColor: "#000000" },
1715
- };
1716
- class LineSeries {
1717
- constructor(position, styles, dataPoints, scenarioGroup, labelGroup, scenarioName, scenarioLabel, _i18n, collisionManager = null) {
1718
- this.MARKER_SIZE = 8;
1719
- this.LINE_WIDTH = 2;
1720
- this.ID_LINE_PREFIX = "LINE";
1721
- this.ID_MARKER_PREFIX = "MARKER";
1722
- this.ID_LABEL_PREFIX = "LABEL";
1723
- this.ESTIMATED_LABEL_WIDTH = 56;
1724
- this.ESTIMATED_LABEL_HEIGHT = 24;
1725
- this.position = position;
1726
- this.styles = styles;
1727
- this.dataPoints = dataPoints;
1728
- this.scenarioGroup = scenarioGroup;
1729
- this.labelGroup = labelGroup;
1730
- this.scenarioName = scenarioName;
1731
- this.scenarioLabel = scenarioLabel;
1732
- this.collisionManager = collisionManager;
1733
- }
1734
- /**
1735
- * Backward-compatible: draws everything (geometry + labels) in one call.
1736
- */
1737
- draw(dataFormatDigits = { percent: 2, decimal: 1 }, measureScale = new SiPrefix()) {
1738
- this.drawGeometry();
1739
- this.drawLabels(dataFormatDigits, measureScale);
1740
- return this;
1741
- }
1742
- /**
1743
- * Phase 1: Draw only geometry (lines + markers). No labels.
1744
- */
1745
- drawGeometry() {
1746
- if (this.dataPoints.length === 0) {
1747
- return this;
1748
- }
1749
- const lineStyle = this.getLineStyle();
1750
- this.drawLines(lineStyle);
1751
- this.drawMarkers(lineStyle);
1752
- return this;
1753
- }
1754
- /**
1755
- * Phase 2: Draw only labels (value labels + scenario label).
1756
- * Call this after all series geometry is drawn, in priority order.
1757
- */
1758
- drawLabels(dataFormatDigits = { percent: 2, decimal: 1 }, measureScale = new SiPrefix()) {
1759
- if (this.dataPoints.length === 0) {
1760
- return this;
1761
- }
1762
- // Draw scenario labels first (behind), then value labels on top
1763
- this.drawScenarioLabel();
1764
- this.drawValueLabels(dataFormatDigits, measureScale);
1765
- return this;
1766
- }
1767
- getLineStyle() {
1768
- var _a, _b;
1769
- const scenarioType = ((_b = (_a = this.scenarioName) === null || _a === void 0 ? void 0 : _a.slice(0, 2)) === null || _b === void 0 ? void 0 : _b.toLowerCase()) || "ac";
1770
- return IBCS_LINE_STYLES[scenarioType] || IBCS_LINE_STYLES.ac;
1771
- }
1772
- /**
1773
- * Extracts the scenario variant number (1-4) from the scenario name.
1774
- * e.g., "ac1" -> 1, "pp2" -> 2, "fc3" -> 3, "pl4" -> 4
1775
- */
1776
- getScenarioVariant() {
1777
- var _a;
1778
- const variant = parseInt(((_a = this.scenarioName) === null || _a === void 0 ? void 0 : _a.slice(-1)) || "1", 10);
1779
- return isNaN(variant) ? 1 : Math.min(Math.max(variant, 1), 4);
1780
- }
1781
- /**
1782
- * Draws a square marker (variant 1: ac1, pp1, fc1, pl1)
1783
- */
1784
- drawSquareMarker(group, cx, cy, style) {
1785
- const halfSize = this.MARKER_SIZE / 2;
1786
- group
1787
- .rect(this.MARKER_SIZE, this.MARKER_SIZE)
1788
- .fill(style.markerFill)
1789
- .stroke({ color: style.markerStroke, width: 1 })
1790
- .move(cx - halfSize, cy - halfSize);
1791
- }
1792
- /**
1793
- * Draws a circle marker (variant 2: ac2, pp2, fc2, pl2)
1794
- */
1795
- drawCircleMarker(group, cx, cy, style) {
1796
- group
1797
- .circle(this.MARKER_SIZE)
1798
- .fill(style.markerFill)
1799
- .stroke({ color: style.markerStroke, width: 1 })
1800
- .center(cx, cy);
1801
- }
1802
- /**
1803
- * Draws a triangle marker pointing up (variant 3: ac3, pp3, fc3, pl3)
1804
- */
1805
- drawTriangleMarker(group, cx, cy, style) {
1806
- const s = this.MARKER_SIZE / 2;
1807
- group
1808
- .polygon(`${cx},${cy - s} ${cx - s},${cy + s} ${cx + s},${cy + s}`)
1809
- .fill(style.markerFill)
1810
- .stroke({ color: style.markerStroke, width: 1 });
1811
- }
1812
- /**
1813
- * Draws a diamond marker (variant 4: ac4, pp4, fc4, pl4)
1814
- */
1815
- drawDiamondMarker(group, cx, cy, style) {
1816
- const s = this.MARKER_SIZE / 2;
1817
- group
1818
- .polygon(`${cx},${cy - s} ${cx + s},${cy} ${cx},${cy + s} ${cx - s},${cy}`)
1819
- .fill(style.markerFill)
1820
- .stroke({ color: style.markerStroke, width: 1 });
1821
- }
1822
- drawLines(lineStyle) {
1823
- const lineGroup = this.scenarioGroup.group().id(this.ID_LINE_PREFIX);
1824
- for (let i = 1; i < this.dataPoints.length; i++) {
1825
- const prevPoint = this.dataPoints[i - 1];
1826
- const currPoint = this.dataPoints[i];
1827
- // Skip if either point has no data
1828
- if (prevPoint.dataPoint.isEmpty() || currPoint.dataPoint.isEmpty()) {
1829
- continue;
1830
- }
1831
- const prevX = this.position.getColumnCenterPositionX(prevPoint.index);
1832
- const prevY = this.position.getColumnPositionY() - prevPoint.dataPoint.getScaledUnit();
1833
- const currX = this.position.getColumnCenterPositionX(currPoint.index);
1834
- const currY = this.position.getColumnPositionY() - currPoint.dataPoint.getScaledUnit();
1835
- const line = lineGroup
1836
- .line([
1837
- [prevX, prevY],
1838
- [currX, currY],
1839
- ])
1840
- .stroke({
1841
- color: lineStyle.lineColor,
1842
- width: this.LINE_WIDTH,
1843
- linecap: "round",
1844
- })
1845
- .fill("none");
1846
- if (lineStyle.lineDashArray) {
1847
- line.attr("stroke-dasharray", lineStyle.lineDashArray);
1848
- }
1849
- }
1850
- }
1851
- drawMarkers(lineStyle) {
1852
- const markerGroup = this.scenarioGroup.group().id(this.ID_MARKER_PREFIX);
1853
- const variant = this.getScenarioVariant();
1854
- for (const point of this.dataPoints) {
1855
- if (point.dataPoint.isEmpty()) {
1856
- continue;
1857
- }
1858
- const centerX = this.position.getColumnCenterPositionX(point.index);
1859
- const centerY = this.position.getColumnPositionY() - point.dataPoint.getScaledUnit();
1860
- // Draw marker shape based on scenario variant
1861
- switch (variant) {
1862
- case 2:
1863
- this.drawCircleMarker(markerGroup, centerX, centerY, lineStyle);
1864
- break;
1865
- case 3:
1866
- this.drawTriangleMarker(markerGroup, centerX, centerY, lineStyle);
1867
- break;
1868
- case 4:
1869
- this.drawDiamondMarker(markerGroup, centerX, centerY, lineStyle);
1870
- break;
1871
- default: // variant 1 or unknown
1872
- this.drawSquareMarker(markerGroup, centerX, centerY, lineStyle);
1873
- break;
1874
- }
1875
- }
1876
- }
1877
- /**
1878
- * Returns direction priority based on line direction at a given point.
1879
- * Default: Above. Only use Below first for true local minima
1880
- * (both neighbors higher than current point).
1881
- */
1882
- getLabelPositionPriority(pointIndex) {
1883
- const current = this.dataPoints[pointIndex];
1884
- // Find nearest non-empty neighbor forward
1885
- let next = null;
1886
- for (let j = pointIndex + 1; j < this.dataPoints.length; j++) {
1887
- if (!this.dataPoints[j].dataPoint.isEmpty()) {
1888
- next = this.dataPoints[j];
1889
- break;
1890
- }
1891
- }
1892
- // Find nearest non-empty neighbor backward
1893
- let prev = null;
1894
- for (let j = pointIndex - 1; j >= 0; j--) {
1895
- if (!this.dataPoints[j].dataPoint.isEmpty()) {
1896
- prev = this.dataPoints[j];
1897
- break;
1898
- }
1899
- }
1900
- // True local minimum: both neighbors exist and are higher
1901
- const currentVal = current.dataPoint.getScaledUnit();
1902
- const isLocalMin = prev && next && prev.dataPoint.getScaledUnit() > currentVal && next.dataPoint.getScaledUnit() > currentVal;
1903
- if (isLocalMin) {
1904
- return [LabelDirection.Below, LabelDirection.Left, LabelDirection.Right, LabelDirection.Above];
1905
- }
1906
- // Default: Above first
1907
- return [LabelDirection.Above, LabelDirection.Left, LabelDirection.Right, LabelDirection.Below];
1908
- }
1909
- getScenarioType() {
1910
- var _a, _b;
1911
- return ((_b = (_a = this.scenarioName) === null || _a === void 0 ? void 0 : _a.slice(0, 2)) === null || _b === void 0 ? void 0 : _b.toLowerCase()) || "ac";
1912
- }
1913
- drawValueLabels(dataFormatDigits, measureScale) {
1914
- const scenarioType = this.getScenarioType();
1915
- for (let i = 0; i < this.dataPoints.length; i++) {
1916
- const point = this.dataPoints[i];
1917
- if (point.dataPoint.isEmpty() || point.dataPoint.value === null) {
1918
- continue;
1919
- }
1920
- const centerX = this.position.getColumnCenterPositionX(point.index);
1921
- const markerY = this.position.getColumnPositionY() - point.dataPoint.getScaledUnit();
1922
- // Use collision manager with 4-direction placement if available
1923
- let labelX = centerX;
1924
- let labelY = markerY - this.MARKER_SIZE / 2 - 2;
1925
- let verticalHook = HookLocation.Bottom;
1926
- let horizontalHook = HookLocation.Center;
1927
- if (this.collisionManager) {
1928
- const directionPriority = this.getLabelPositionPriority(i);
1929
- const placement = this.collisionManager.getOptimalPlacement(centerX, markerY, this.ESTIMATED_LABEL_WIDTH, this.ESTIMATED_LABEL_HEIGHT, point.index, this.MARKER_SIZE, scenarioType, directionPriority);
1930
- if (placement === null) {
1931
- continue; // All positions collide with higher-priority labels — hide
1932
- }
1933
- labelX = placement.labelX;
1934
- labelY = placement.labelY;
1935
- verticalHook = placement.verticalHook;
1936
- horizontalHook = placement.horizontalHook;
1937
- // Register bounds with scenario type
1938
- const bounds = Object.assign(Object.assign({}, placement.bounds), { scenarioType });
1939
- this.collisionManager.register(bounds);
1940
- }
1941
- const label = new Label(this.labelGroup, labelX, labelY, this.ID_LABEL_PREFIX, point.dataPoint.value, this.styles, verticalHook, horizontalHook);
1942
- label.draw(true, dataFormatDigits, measureScale);
1943
- }
1944
- }
1945
- drawScenarioLabel() {
1946
- if (!this.scenarioLabel) {
1947
- return;
1948
- }
1949
- // Find the last non-empty data point
1950
- let lastValidPoint = null;
1951
- for (let i = this.dataPoints.length - 1; i >= 0; i--) {
1952
- if (!this.dataPoints[i].dataPoint.isEmpty()) {
1953
- lastValidPoint = this.dataPoints[i];
1954
- break;
1955
- }
1956
- }
1957
- if (!lastValidPoint) {
1958
- return;
1959
- }
1960
- const lastX = this.position.getColumnCenterPositionX(lastValidPoint.index) + this.MARKER_SIZE + 4;
1961
- const lastY = this.position.getColumnPositionY() - lastValidPoint.dataPoint.getScaledUnit();
1962
- const scenarioType = this.getScenarioType();
1963
- // Hide this scenario label if it's too close to a higher-priority one (e.g. AC)
1964
- if (this.collisionManager) {
1965
- if (this.collisionManager.shouldHideScenarioLabel(lastX, lastY, scenarioType)) {
1966
- return;
1967
- }
1968
- this.collisionManager.registerScenarioLabel(lastX, lastY, scenarioType);
1969
- }
1970
- const scenarioLabelElement = new Label(this.labelGroup, lastX, lastY, "SCENARIO_LABEL", this.scenarioLabel, this.styles, HookLocation.Center, HookLocation.Left);
1971
- scenarioLabelElement.forceStringTypeDraw();
1972
- }
1973
- }
1974
-
1975
- /**
1976
- * Renders a single segment within a stacked bar column in a time chart.
1977
- *
1978
- * Each StackedColumn represents one layer of the stack. It is positioned vertically
1979
- * based on its cumulative baseline value and draws a colored rectangle.
1980
- *
1981
- * Supports three stacking modes:
1982
- * - ABSOLUTE: segment height = value * pixelPerUnit
1983
- * - RELATIVE (100%): segment height proportional to its share of totalValue
1984
- * - ABSOLUTE_RELATIVE: same as absolute but labels show percentages
1985
- *
1986
- * Segment labels are shown only when the segment is tall enough (>= 18px) to avoid clutter.
1987
- * The topmost segment can draw a total label above the full stack via drawTotalLabel().
1988
- */
1989
- class StackedColumn {
1990
- constructor(position, styles, dataPoint, index, baselineValue, _segmentLabel, segmentIndex, stackMode, totalValue, _isScenarioStack, parentGroup) {
1991
- this.hasData = false;
1992
- this.position = position;
1993
- this.styles = styles;
1994
- this.dataPoint = dataPoint;
1995
- this.index = index;
1996
- this.baselineValue = baselineValue;
1997
- this.segmentIndex = segmentIndex;
1998
- this.stackMode = stackMode;
1999
- this.totalValue = totalValue;
2000
- this.group = parentGroup;
2001
- this.columnGroup = parentGroup.group().id(`stacked_col_${index}_seg_${segmentIndex}`);
2002
- if ((dataPoint === null || dataPoint === void 0 ? void 0 : dataPoint.isEmpty()) !== true && dataPoint.value != null) {
2003
- this.hasData = true;
2004
- }
2005
- }
2006
- draw(dataFormatDigits = { percent: 2, decimal: 1 }, measureScale = new SiPrefix()) {
2007
- if (!this.hasData || this.dataPoint.value == null) {
2008
- return;
2009
- }
2010
- const value = this.dataPoint.value;
2011
- const pixelPerUnit = this.dataPoint.pixelPerUnit;
2012
- let segmentHeight;
2013
- let yPos;
2014
- const axisY = this.position.getColumnPositionY();
2015
- if (this.stackMode === StackMode.RELATIVE) {
2016
- // 100% stacked: segment height is proportion of total
2017
- const proportion = this.totalValue !== 0 ? Math.abs(value) / Math.abs(this.totalValue) : 0;
2018
- // Use a fixed total height based on pixelPerUnit (total=1.0 for 100%)
2019
- const totalPixelHeight = pixelPerUnit; // pixelPerUnit represents the height for 100%
2020
- segmentHeight = proportion * totalPixelHeight;
2021
- const baselinePixels = (this.baselineValue / Math.abs(this.totalValue)) * totalPixelHeight;
2022
- yPos = axisY - baselinePixels - segmentHeight;
2023
- }
2024
- else {
2025
- // Absolute or absolute-relative: use real pixel scaling
2026
- segmentHeight = Math.abs(value * pixelPerUnit);
2027
- const baselinePixels = this.baselineValue * pixelPerUnit;
2028
- yPos = axisY - baselinePixels - segmentHeight;
2029
- }
2030
- const xPos = this.position.getColumnCenterPositionX(this.index);
2031
- const columnWidth = this.position.getColumnWidth();
2032
- const colors = this.styles.stackColors;
2033
- const fillColor = colors[this.segmentIndex % colors.length];
2034
- const fillStyle = { color: fillColor };
2035
- const strokeStyle = { color: fillColor, width: 0.5 };
2036
- // Draw rectangle
2037
- this.columnGroup
2038
- .rect(columnWidth, Math.max(segmentHeight, 0.5))
2039
- .fill(fillStyle)
2040
- .stroke(strokeStyle)
2041
- .y(yPos)
2042
- .cx(xPos);
2043
- // Draw segment value label if segment is tall enough (min ~18px)
2044
- const MIN_SEGMENT_HEIGHT_FOR_LABEL = 18;
2045
- if (segmentHeight >= MIN_SEGMENT_HEIGHT_FOR_LABEL) {
2046
- const labelY = yPos + segmentHeight / 2;
2047
- if (this.stackMode === StackMode.RELATIVE || this.stackMode === StackMode.ABSOLUTE_RELATIVE) {
2048
- const pct = this.totalValue !== 0 ? (value / this.totalValue) * 100 : 0;
2049
- const labelValue = pct.toFixed(dataFormatDigits.percent) + "%";
2050
- new Label(this.group, xPos, labelY, "STACK_SEG", labelValue, this.styles, HookLocation.Center, HookLocation.Center)
2051
- .setSegmentFill(fillColor)
2052
- .forceStringTypeDraw();
2053
- }
2054
- else {
2055
- // Pass raw numeric value — Label.draw() formats with measureScale
2056
- new Label(this.group, xPos, labelY, "STACK_SEG", value, this.styles, HookLocation.Center, HookLocation.Center)
2057
- .setSegmentFill(fillColor)
2058
- .draw(true, dataFormatDigits, measureScale);
2059
- }
2060
- }
2061
- }
2062
- /**
2063
- * Draw the total label above the topmost segment.
2064
- */
2065
- drawTotalLabel(dataFormatDigits = { percent: 2, decimal: 1 }, measureScale = new SiPrefix()) {
2066
- if (this.stackMode === StackMode.RELATIVE) {
2067
- // Don't show total for 100% stacked (always 100%)
2068
- return;
2069
- }
2070
- const xPos = this.position.getColumnCenterPositionX(this.index);
2071
- const axisY = this.position.getColumnPositionY();
2072
- const totalPixels = this.totalValue * this.dataPoint.pixelPerUnit;
2073
- const labelY = axisY - totalPixels - this.position.spacings.labelToColumn;
2074
- const label = new Label(this.group, xPos, labelY, "STACK_TOTAL", this.totalValue, this.styles, HookLocation.Bottom, HookLocation.Center);
2075
- label.draw(true, dataFormatDigits, measureScale);
2076
- }
2077
- }
2078
-
2079
- /**
2080
- * IBCS-style area fill colors for stacked area charts.
2081
- */
2082
- const SCENARIO_AREA_STYLES = {
2083
- ac: { fill: "#000000", opacity: 0.3, lineColor: "#000000" },
2084
- pp: { fill: "#999999", opacity: 0.3, lineColor: "#999999" },
2085
- fc: { fill: "#000000", opacity: 0.2, lineColor: "#000000", dashArray: "4,4" },
2086
- pl: { fill: "#000000", opacity: 0.1, lineColor: "#000000" },
2087
- };
2088
- const GRAYSCALE_AREA_STYLES = [
2089
- { fill: "#000000", opacity: 0.3 },
2090
- { fill: "#555555", opacity: 0.25 },
2091
- { fill: "#999999", opacity: 0.2 },
2092
- { fill: "#bbbbbb", opacity: 0.15 },
2093
- { fill: "#dddddd", opacity: 0.1 },
2094
- ];
2095
- /**
2096
- * Draws an SVG path filling the area between an upper boundary polyline
2097
- * and a lower boundary polyline — used for stacked area charts.
2098
- */
2099
- class AreaFill {
2100
- constructor(parentGroup, upperPoints, lowerPoints, scenarioType, segmentIndex, isScenarioStack) {
2101
- this.group = parentGroup.group().id(`area_fill_${segmentIndex}`);
2102
- this.upperPoints = upperPoints;
2103
- this.lowerPoints = lowerPoints;
2104
- this.scenarioType = scenarioType;
2105
- this.segmentIndex = segmentIndex;
2106
- this.isScenarioStack = isScenarioStack;
2107
- }
2108
- draw() {
2109
- if (this.upperPoints.length < 2 || this.lowerPoints.length < 2) {
2110
- return;
2111
- }
2112
- // Build SVG path: upper line forward, then lower line backward
2113
- let pathStr = `M ${this.upperPoints[0].x},${this.upperPoints[0].y}`;
2114
- for (let i = 1; i < this.upperPoints.length; i++) {
2115
- pathStr += ` L ${this.upperPoints[i].x},${this.upperPoints[i].y}`;
2116
- }
2117
- // Walk lower points in reverse to close the shape
2118
- for (let i = this.lowerPoints.length - 1; i >= 0; i--) {
2119
- pathStr += ` L ${this.lowerPoints[i].x},${this.lowerPoints[i].y}`;
2120
- }
2121
- pathStr += " Z";
2122
- let fill;
2123
- let opacity;
2124
- if (this.isScenarioStack && this.scenarioType) {
2125
- const prefix = this.scenarioType.slice(0, 2).toLowerCase();
2126
- const style = SCENARIO_AREA_STYLES[prefix] || SCENARIO_AREA_STYLES["ac"];
2127
- fill = style.fill;
2128
- opacity = style.opacity;
2129
- }
2130
- else {
2131
- const idx = Math.min(this.segmentIndex, GRAYSCALE_AREA_STYLES.length - 1);
2132
- fill = GRAYSCALE_AREA_STYLES[idx].fill;
2133
- opacity = GRAYSCALE_AREA_STYLES[idx].opacity;
2134
- }
2135
- this.group.path(pathStr).fill(fill).opacity(opacity).stroke("none");
2136
- }
2137
- /**
2138
- * Draw the boundary line on top of the area fill.
2139
- */
2140
- drawBoundaryLine() {
2141
- if (this.upperPoints.length < 2) {
2142
- return;
2143
- }
2144
- let lineColor = "#000000";
2145
- let dashArray;
2146
- if (this.isScenarioStack && this.scenarioType) {
2147
- const prefix = this.scenarioType.slice(0, 2).toLowerCase();
2148
- const style = SCENARIO_AREA_STYLES[prefix] || SCENARIO_AREA_STYLES["ac"];
2149
- lineColor = style.lineColor;
2150
- dashArray = style.dashArray;
2151
- }
2152
- const polyline = this.group
2153
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2154
- .polyline(this.upperPoints.map((p) => [p.x, p.y]))
2155
- .fill("none")
2156
- .stroke({ color: lineColor, width: 1.5 });
2157
- if (dashArray) {
2158
- polyline.attr("stroke-dasharray", dashArray);
2159
- }
2160
- }
2161
- }
2162
-
2163
- // import { DataFormatDigits } from "../../../../utils/model/DataFormatDigits";
2164
- // import { SiPrefix } from "../../../../utils/model/SiPrefix";
2165
- /**
2166
- * Renders a line segment connecting two consecutive DataPoints in a time chart.
2167
- *
2168
- * Each Line instance represents the segment from a previous data point to the current one.
2169
- * Dimensions for both endpoints are computed so the SVG line can be drawn between them.
2170
- * The primary line (first scenario) receives the scenario label at the end of the series.
2171
- *
2172
- * Used by the overlay layer (average/median lines), not by the main LineSeries rendering.
2173
- */
2174
- class Line {
2175
- constructor(position, styles, dataPoint, previousDataPoint, index, isPrimaryLine, scenarioGroup, LineLabel) {
2176
- this.ID_DATA_PREFIX = "DATA";
2177
- this.ID_SCENARIO_PREFIX = "SCENARIO";
2178
- this.ID_RECT = "RECT";
2179
- this.FALLBACK_COLOUR = "#000000";
2180
- this.label = null;
2181
- this.scenarioLabel = null;
2182
- this.isVarianceLine = false;
2183
- this.dimensions = {
2184
- columnLength: 0,
2185
- xPos: 0,
2186
- yPos: 0,
2187
- labelYPos: 0,
2188
- scenarioLabelXPos: 0,
2189
- scenarioLabelYPos: 0,
2190
- clipped: false,
2191
- };
2192
- this.previousDimensions = {
2193
- columnLength: 0,
2194
- xPos: 0,
2195
- yPos: 0,
2196
- labelYPos: 0,
2197
- scenarioLabelXPos: 0,
2198
- scenarioLabelYPos: 0,
2199
- clipped: false,
2200
- };
2201
- this.hasData = false;
2202
- this.dataPoint = dataPoint;
2203
- // this.previousDataPoint = previousDataPoint;
2204
- this.index = index;
2205
- this.isPrimaryLine = isPrimaryLine;
2206
- this.position = position;
2207
- this.LineBarStyles = styles.barStyles;
2208
- this.scenarioGroup = scenarioGroup;
2209
- this.styles = styles;
2210
- this.LineGroup = scenarioGroup.group().id(scenarioGroup.toString() + "_" + this.ID_RECT);
2211
- if ((dataPoint === null || dataPoint === void 0 ? void 0 : dataPoint.isEmpty()) !== true) {
2212
- this.hasData = true;
2213
- this.dimensions = this.createDimensions(dataPoint, index, isPrimaryLine);
2214
- this.label = this.getDataLabel(dataPoint);
2215
- this.scenarioLabel = this.getScenarioLabel(LineLabel);
2216
- }
2217
- this.previousDimensions = this.createDimensions(previousDataPoint, index - 1, isPrimaryLine);
2218
- }
2219
- setAsVariance() {
2220
- var _a;
2221
- this.isVarianceLine = true;
2222
- (_a = this.label) === null || _a === void 0 ? void 0 : _a.setToVarianceLabel();
2223
- return this;
2224
- }
2225
- updateLabelGroup(newGroup) {
2226
- var _a;
2227
- if (this.isEmpty()) {
2228
- return this;
2229
- }
2230
- (_a = this.label) === null || _a === void 0 ? void 0 : _a.updateGroup(newGroup);
2231
- return this;
2232
- }
2233
- draw(dataFormatDigits = { percent: 2, decimal: 1 }, measureScale = new SiPrefix()) {
2234
- // TODE: JHE: Remove DataFOrmatDigits Type Duplicates
2235
- if (this.isEmpty()) {
2236
- return this;
2237
- }
2238
- const scenarioStyle = this.getScenarioStyle();
2239
- // let strokeStyle = "#00FF00"; //this.convertToSVGStyle(scenarioStyle, "stroke");
2240
- const fillStyle = this.getFillStyle(scenarioStyle);
2241
- if (this.LineGroup != null) {
2242
- this.LineGroup.line([
2243
- [this.previousDimensions.xPos, this.previousDimensions.yPos],
2244
- [this.dimensions.xPos, this.dimensions.yPos],
2245
- ])
2246
- .fill(fillStyle)
2247
- .stroke({ color: "#f06", width: 3, linecap: "round" });
2248
- }
2249
- this.drawLineDataLabel(dataFormatDigits, measureScale);
2250
- this.drawScenarioLabel();
2251
- }
2252
- createDimensions(dataPoint, index, isPrimaryBar) {
2253
- return {
2254
- clipped: false,
2255
- columnLength: dataPoint.getScaledUnit(),
2256
- xPos: this.position.getColumnPositionX(index, isPrimaryBar),
2257
- yPos: this.position.getColumnPositionY() - dataPoint.getScaledUnit(),
2258
- labelYPos: this.position.getColumnDataLabelPositionY(dataPoint.getScaledUnit()),
2259
- scenarioLabelXPos: this.position.getColumnPositionX(index, isPrimaryBar) +
2260
- this.position.getScenarioLabelPositionOffsetX(isPrimaryBar),
2261
- scenarioLabelYPos: this.position.getColumnPositionY() - dataPoint.getScaledUnit(),
2262
- };
2263
- }
2264
- getDataLabel(dataPoint) {
2265
- let labelHook = HookLocation.Bottom;
2266
- if (dataPoint.value != null && dataPoint.value < 0) {
2267
- labelHook = HookLocation.Top;
2268
- }
2269
- return new Label(this.scenarioGroup, this.position.getColumnCenterPositionX(this.index), this.position.getColumnDataLabelPositionY(this.dataPoint.getScaledUnit()), this.ID_DATA_PREFIX, dataPoint.value, this.styles, labelHook, HookLocation.Center);
2270
- }
2271
- getScenarioLabel(LineLabel) {
2272
- return new Label(this.scenarioGroup, 0, 0, this.ID_SCENARIO_PREFIX, LineLabel, this.styles, HookLocation.Bottom, HookLocation.Left);
2273
- }
2274
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2275
- convertToSVGStyle(style, mode) {
2276
- if (style == null) {
2277
- style = [];
2278
- }
2279
- style["color"] = style[mode] || this.FALLBACK_COLOUR;
2280
- return Object.assign({}, style);
2281
- }
2282
- drawScenarioLabel() {
2283
- if (this.scenarioLabel != null && !this.scenarioLabel.isEmpty() && !this.isVarianceLine) {
2284
- this.scenarioLabel.setPos(this.dimensions.scenarioLabelXPos, this.dimensions.scenarioLabelYPos).draw(true);
2285
- }
2286
- }
2287
- drawLineDataLabel(dataFormatDigits, measureScale = new SiPrefix()) {
2288
- var _a;
2289
- (_a = this.label) === null || _a === void 0 ? void 0 : _a.draw(this.isPrimaryLine, dataFormatDigits, measureScale);
2290
- }
2291
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2292
- getFillStyle(scenarioStyle) {
2293
- var _a, _b, _c, _d;
2294
- const pattern = this.LineBarStyles[this.dataPoint.getScenario()];
2295
- if ((pattern === null || pattern === void 0 ? void 0 : pattern.fillpattern) && ((_a = this.styles.pattern.get(pattern.fillpattern)) === null || _a === void 0 ? void 0 : _a.pattern)) {
2296
- return (_d = (_c = (_b = this.styles) === null || _b === void 0 ? void 0 : _b.pattern) === null || _c === void 0 ? void 0 : _c.get(pattern.fillpattern)) === null || _d === void 0 ? void 0 : _d.pattern;
2297
- }
2298
- return this.convertToSVGStyle(scenarioStyle, "fill");
2299
- }
2300
- getScenarioStyle() {
2301
- var _a;
2302
- if (this.isVarianceLine) {
2303
- return (_a = this.styles) === null || _a === void 0 ? void 0 : _a.varianceStyles.getSVGStyle(this.dataPoint.getVarianceStyle());
2304
- }
2305
- return this.LineBarStyles[this.dataPoint.getScenario()];
2306
- }
2307
- isEmpty() {
2308
- return false === this.hasData || Number.isNaN(this.dataPoint.value);
2309
- }
2310
- }
2311
-
2312
- /**
2313
- * Factory for creating chart element instances (Column, Needle, Marker, Line, LineSeries)
2314
- * within the correct SVG group hierarchy.
2315
- *
2316
- * Manages 4 SVG group layers for z-ordering (back-to-front):
2317
- * - scenario2: secondary bars (PP) -- inserted before scenario1 so they render behind
2318
- * - scenario1: primary bars (AC) -- foreground
2319
- * - scenario3: primary markers (e.g. FC diamonds)
2320
- * - scenario4: secondary markers (e.g. PL triangles)
2321
- * - scenario1Label: label group, always rendered on top of all geometry
2322
- *
2323
- * createPrimaryBar() produces a foreground Column (AC) with data + scenario labels.
2324
- * createSecondaryBar() produces a background Column (PP) without data labels.
2325
- * createPrimaryMarker() / createSecondaryMarker() produce Marker instances on opposite sides.
2326
- * createVarianceBar() wraps a Column with variance styling.
2327
- * createRelativeVarianceBar() creates a Needle for percentage variance display.
2328
- * createLineSeries() creates a LineSeries for line chart mode.
2329
- */
2330
- class ScenarioFactory {
2331
- constructor(position, scenariosGroupParent, styles, elementCnt, i18n) {
2332
- this.pixelPerUnit = 1;
2333
- this.collisionManager = null;
2334
- this.overflowConfig = null;
2335
- this.i18n = i18n;
2336
- const primScenario = scenariosGroupParent.group().id("Scenario1");
2337
- const secondScenario = scenariosGroupParent.group().id("Scenario2").insertBefore(primScenario);
2338
- this.svgGroups = {
2339
- parent: scenariosGroupParent,
2340
- scenario1: primScenario,
2341
- scenario2: secondScenario,
2342
- scenario3: scenariosGroupParent.group().id("Scenario3"),
2343
- scenario4: scenariosGroupParent.group().id("Scenario4"),
2344
- scenario1Label: scenariosGroupParent.group().id("label"),
2345
- };
2346
- this.styles = styles;
2347
- this.position = position;
2348
- this.elementCnt = elementCnt;
2349
- }
2350
- setOverflowConfig(config) {
2351
- this.overflowConfig = config;
2352
- }
2353
- createLine(name, dataPoint, previousDataPoint, index) {
2354
- const isPrimaryColumn = false;
2355
- const columnGroup = this.svgGroups.scenario1.group().id("" + index);
2356
- const labelGroup = this.svgGroups.scenario1Label.group().id("" + index);
2357
- let lineLabel = null;
2358
- if (this.isLastDataPoint(index - 1)) {
2359
- lineLabel = name; ///`${this.i18n.get(dataPoint.scenario as string) || dataPoint.scenario}`;
2360
- }
2361
- return new Line(this.position, this.styles, dataPoint, previousDataPoint, index, isPrimaryColumn, columnGroup, lineLabel).updateLabelGroup(labelGroup);
2362
- }
2363
- createPrimaryBar(dataPoint, index) {
2364
- const isPrimaryColumn = true;
2365
- const columnGroup = this.svgGroups.scenario1.group().id("" + index);
2366
- const labelGroup = this.svgGroups.scenario1Label.group().id("" + index);
2367
- let columnLabel = null;
2368
- if (this.isLastDataPoint(index)) {
2369
- columnLabel = `${this.i18n.get(dataPoint.scenario) || dataPoint.scenario}`;
2370
- }
2371
- return new Column(this.position, this.styles, dataPoint, index, isPrimaryColumn, columnGroup, columnLabel, this.overflowConfig).updateLabelGroup(labelGroup);
2372
- }
2373
- createVarianceBar(dataPoint, index) {
2374
- const isPrimaryColumn = true;
2375
- const columnGroup = this.svgGroups.scenario1.group().id("" + index);
2376
- const labelGroup = this.svgGroups.scenario1Label.group().id("" + index);
2377
- let columnLabel = null;
2378
- if (this.isLastDataPoint(index)) {
2379
- columnLabel = `${this.i18n.get(dataPoint.scenario) || dataPoint.scenario}`;
2380
- }
2381
- return new Column(this.position, this.styles, dataPoint, index, isPrimaryColumn, columnGroup, columnLabel, this.overflowConfig)
2382
- .updateLabelGroup(labelGroup)
2383
- .setAsVariance();
2384
- }
2385
- createRelativeVarianceBar(dataPoint, index) {
2386
- const needleGroup = this.svgGroups.scenario1.group().id("" + index);
2387
- const labelGroup = this.svgGroups.scenario1Label.group().id("" + index);
2388
- return new Needle(this.position, this.styles, dataPoint, index, needleGroup).updateLabelGroup(labelGroup);
2389
- }
2390
- createSecondaryBar(dataPoint, index) {
2391
- const isPrimaryBar = false;
2392
- const barGroup = this.svgGroups.scenario2.group().id("" + index);
2393
- let columnLabel = null;
2394
- if (this.isFirstDataPoint(index)) {
2395
- columnLabel = `${this.i18n.get(dataPoint.scenario) || dataPoint.scenario}`;
2396
- }
2397
- return new Column(this.position, this.styles, dataPoint, index, isPrimaryBar, barGroup, columnLabel, this.overflowConfig);
2398
- }
2399
- createPrimaryMarker(dataPoint, index) {
2400
- const markerGroup = this.svgGroups.scenario3.group().id("" + index);
2401
- const markerPattern = this.styles.pattern.get("marker-right") || {
2402
- foreground: "#000000",
2403
- background: "#ffffff",
2404
- bgOffset: 0,
2405
- };
2406
- const isPrimaryMarker = true;
2407
- let columnLabel = null;
2408
- if (this.isFirstDataPoint(index)) {
2409
- columnLabel = `${this.i18n.get(dataPoint.scenario) || dataPoint.scenario}`;
2410
- }
2411
- return new Marker(this.position, markerGroup, markerPattern, dataPoint.scenario, this.styles, dataPoint, index, columnLabel, isPrimaryMarker);
2412
- }
2413
- createSecondaryMarker(dataPoint, index) {
2414
- const markerGroup = this.svgGroups.scenario4.group().id("" + index);
2415
- const markerPattern = this.styles.pattern.get("marker-left") || {
2416
- foreground: "#000000",
2417
- background: "#ffffff",
2418
- bgOffset: 0,
2419
- };
2420
- const isPrimaryMarker = false;
2421
- let columnLabel = null;
2422
- if (this.isLastDataPoint(index)) {
2423
- columnLabel = `${this.i18n.get(dataPoint.scenario) || dataPoint.scenario}`;
2424
- }
2425
- return new Marker(this.position, markerGroup, markerPattern, dataPoint.scenario, this.styles, dataPoint, index, columnLabel, isPrimaryMarker);
2426
- }
2427
- isLastDataPoint(index) {
2428
- return this.elementCnt - 1 === index;
2429
- }
2430
- isFirstDataPoint(index) {
2431
- return 0 === index;
2432
- }
2433
- /**
2434
- * Sets the collision manager for line series label collision detection.
2435
- * Should be called before creating line series to enable collision detection across all series.
2436
- */
2437
- setCollisionManager(manager) {
2438
- this.collisionManager = manager;
2439
- }
2440
- /**
2441
- * Moves the label group to the front of the SVG tree so labels render on top of all geometry.
2442
- */
2443
- moveLabelsToFront() {
2444
- this.svgGroups.scenario1Label.front();
2445
- }
2446
- createLineSeries(dataPoints, scenarioName) {
2447
- const lineSeriesGroup = this.svgGroups.parent.group().id("LineSeries_" + scenarioName);
2448
- const labelGroup = this.svgGroups.scenario1Label.group().id("LineSeries_Label_" + scenarioName);
2449
- // Scenario label for the line (to be shown at the right of the last data point)
2450
- const scenarioLabel = `${this.i18n.get(scenarioName) || scenarioName}`;
2451
- return new LineSeries(this.position, this.styles, dataPoints, lineSeriesGroup, labelGroup, scenarioName, scenarioLabel, this.i18n, this.collisionManager);
2452
- }
2453
- }
2454
-
2455
- /** Tracks whether the internal data model needs to be regenerated. */
2456
- var FactoryState;
2457
- (function (FactoryState) {
2458
- FactoryState[FactoryState["UP_TO_DATE"] = 0] = "UP_TO_DATE";
2459
- FactoryState[FactoryState["DIRTY"] = 1] = "DIRTY";
2460
- })(FactoryState || (FactoryState = {}));
2461
- /** Classifies how a data model entry should be rendered: as an absolute or relative variance, or as a regular scenario. */
2462
- var VarianceType;
2463
- (function (VarianceType) {
2464
- VarianceType["RELATIVE"] = "dr";
2465
- VarianceType["ABSOLUTE"] = "d";
2466
- VarianceType["NONE"] = "";
2467
- })(VarianceType || (VarianceType = {}));
2468
- /**
2469
- * Orchestrates the full rendering pipeline for an IBCS time series chart.
2470
- *
2471
- * Rendering pipeline (in draw()):
2472
- * 1. Clears the SVG container
2473
- * 2. Routes to the appropriate drawing method based on chart type:
2474
- * - Variance chart: drawVarianceScenario() for absolute/relative variance bars
2475
- * - Stacked chart: drawStackedScenarios() or drawStackedAreaScenarios() (line mode)
2476
- * - Standard chart: drawScenarios() (bar mode) or drawLineScenarios() (line mode)
2477
- * 3. Draws axis baseline + date labels via drawAxisAndLabels()
2478
- *
2479
- * Data pipeline (in setConfig()):
2480
- * 1. Raw data is filtered via AlaSQL (optional WHERE clause)
2481
- * 2. Dates are normalized to the configured interval (day/week/month/quarter/year)
2482
- * 3. Scenarios are aggregated per date bucket (SUM with operation sign)
2483
- * 4. Missing date buckets are filled via leftOuterJoinDates()
2484
- * 5. Variance model is computed from base/delta scenario pairs
2485
- * 6. Min/max DataPoints are found for coordinate system sizing
2486
- *
2487
- * Auto chart mode: when dataModel.length exceeds maxBars, switches from bar to line.
2488
- */
2489
- class TimeChart {
2490
- constructor(ruleSet, config, styles, availableWidth = 0) {
2491
- this.CSS_CATEGORIES = "categories";
2492
- this.dataModel = [];
2493
- this.variancesDataModel = [];
2494
- this.title = "";
2495
- this.smallestDataPointValue = new DataPoint(0, Scenario.AC1, 1, Scenario.NEU);
2496
- this.highestDataPointValue = new DataPoint(0, Scenario.AC1, 1, Scenario.NEU);
2497
- this.smallestVarianceDataPointValue = new DataPoint(0, Scenario.AC1, 1, Scenario.NEU);
2498
- this.highestVarianceDataPointValue = new DataPoint(0, Scenario.AC1, 1, Scenario.NEU);
2499
- this.pixelPerUnit = 1;
2500
- this.pixelPerPercentage = 1;
2501
- this.hideAxisLabels = false;
2502
- this.axisScenario = Scenario.AC1;
2503
- this.preparedDataSet = [];
2504
- this.axisCategoryArea = { width: 0, height: 0 };
2505
- this.scenariosArea = { width: 0, height: 0 };
2506
- this.state = FactoryState.DIRTY;
2507
- this.i18n = new Map();
2508
- this.leftSideOffsetForHorizontalSync = -1;
2509
- this.dateInterval = DateDistance.DAY;
2510
- this.locale = "de";
2511
- this.axisLabelsMode = AxisLabelsMode.SMART;
2512
- this.intervalSpanLimit = 32;
2513
- this.measureScale = new SiPrefix();
2514
- this.measureUnit = "";
2515
- this.dataFormatDigits = { percent: 2, decimal: 1 };
2516
- this.showOverlayMedian = false;
2517
- this.showOverlayAvg = false;
2518
- this.chartMode = ChartMode.BAR;
2519
- this.maxBars = 28;
2520
- this.stackConfig = null;
2521
- this.lineFullWidth = true;
2522
- this.availableWidth = 0;
2523
- this.overflowConfig = null;
2524
- this.lastScenarios = [];
2525
- this.initSQLFunctions();
2526
- this.ruleSet = ruleSet || new IBCSRuleSet();
2527
- this.i18n = this.createI18n(new Map());
2528
- this.styles = styles;
2529
- this.availableWidth = availableWidth;
2530
- this.setConfig(config);
2531
- this.position = this.createElementPosition(config.scenarios);
2532
- }
2533
- updatePosition(scenarios) {
2534
- this.position = this.createElementPosition(scenarios);
2535
- }
2536
- initSQLFunctions() {
2537
- alasql.fn.transformOperator = function (a) {
2538
- return a === "-" ? -1 : 1;
2539
- };
2540
- // @ts-ignore
2541
- alasql.fn.normalizeDate = function (date, normalizationLevel, _locale) {
2542
- if (date === undefined || !date.isValid) {
2543
- return undefined;
2544
- }
2545
- return date.startOf(normalizationLevel);
2546
- };
2547
- }
2548
- setStyles(newStyle) {
2549
- this.styles = newStyle;
2550
- }
2551
- setAvailableWidth(w) {
2552
- this.availableWidth = w;
2553
- }
2554
- setAvailableHeight(availableHeight) {
2555
- // Only apply overdrive for manual scaling in bar mode
2556
- if (this.pixelPerUnit <= 0 || availableHeight <= 0) {
2557
- this.overflowConfig = null;
2558
- return;
2559
- }
2560
- if (this.stackConfig != null) {
2561
- this.overflowConfig = null;
2562
- return;
2563
- }
2564
- const effectiveMode = this.determineEffectiveChartMode();
2565
- if (effectiveMode !== ChartMode.BAR) {
2566
- this.overflowConfig = null;
2567
- return;
2568
- }
2569
- this.overflowConfig = this.calculateOverflowConfig(availableHeight);
2570
- // Rebuild position with virtual max so the coordinate system fits the container
2571
- if (this.overflowConfig) {
2572
- this.updatePosition(this.lastScenarios);
2573
- }
2574
- }
2575
- calculateOverflowConfig(availableHeight) {
2576
- const highest = this.isVarianceChart() ? this.highestVarianceDataPointValue : this.highestDataPointValue;
2577
- const highestScaledUnit = highest.getScaledUnit();
2578
- if (highestScaledUnit <= 0)
2579
- return null;
2580
- const fontSize = this.styles.fontStyles.size;
2581
- // Non-bar overhead: everything except the bars themselves (labels, axis, padding)
2582
- const nonBarOverhead = this.position.dataLabelHeight +
2583
- this.position.spacings.labelToColumn +
2584
- this.position.padding.top +
2585
- this.position.padding.bottom +
2586
- this.position.spacings.labelToAxis +
2587
- fontSize; // axis labels approximate height
2588
- const overdriveZoneHeight = fontSize * 1.5;
2589
- const breakGap = fontSize * 0.3;
2590
- const cutHeight = availableHeight - nonBarOverhead - overdriveZoneHeight - breakGap;
2591
- // Non-AC scenarios break lower than AC by this offset
2592
- const scenarioCutOffset = fontSize * 0.8;
2593
- if (cutHeight <= scenarioCutOffset)
2594
- return null;
2595
- // Use the lower (non-AC) cut height for overflow detection threshold
2596
- const lowestCutHeight = cutHeight - scenarioCutOffset;
2597
- // No bar exceeds even the lowest cut height → no overflow needed
2598
- if (highestScaledUnit <= lowestCutHeight)
2599
- return null;
2600
- // maxOverflow based on lowest cut height so no bar exceeds overdriveZoneHeight
2601
- const maxOverflow = highestScaledUnit - lowestCutHeight;
2602
- return {
2603
- cutHeight,
2604
- overdriveZoneHeight,
2605
- breakGap,
2606
- maxOverflow,
2607
- scenarioCutOffset,
2608
- };
2609
- }
2610
- setConfig(config) {
2611
- var _a;
2612
- this.state = FactoryState.DIRTY;
2613
- this.sortScenariosbyVisualisationRules(config);
2614
- this.setData([...config.data], config.filter);
2615
- this.hideAxisLabels = config.hideAxisLabels || false;
2616
- this.pixelPerUnit = config.pixelPerUnit;
2617
- this.pixelPerPercentage = config.pixelPerPercentage;
2618
- this.axisLabelsMode = config.axisLabelsMode;
2619
- this.intervalSpanLimit = config.intervalSpanLimit;
2620
- this.dateInterval = this.findDateInterval(config.dateInterval);
2621
- this.dataModel = this.populateModel(config.scenarios, this.dateInterval, config.level, config.sortOrder);
2622
- this.variancesDataModel = this.populateVarianceModel(config.variances, this.dataModel);
2623
- this.title = config.title || Formatter.translateScenarioLabel((_a = config === null || config === void 0 ? void 0 : config.variances) === null || _a === void 0 ? void 0 : _a.toString(), this.i18n);
2624
- this.smallestDataPointValue = this.findSmallestDataPointValue(this.dataModel);
2625
- this.smallestVarianceDataPointValue = this.findSmallestDataPointValue(this.variancesDataModel);
2626
- this.highestDataPointValue = this.findHighestDataPointValue(this.dataModel);
2627
- this.highestVarianceDataPointValue = this.findHighestDataPointValue(this.variancesDataModel);
2628
- this.axisScenario = this.setAxisScenario(config.variances);
2629
- this.leftSideOffsetForHorizontalSync = config.leftSideOffsetForHorizontalSync;
2630
- this.measureScale = config.measureScale;
2631
- this.measureUnit = config.measureUnit;
2632
- this.dataFormatDigits = config.dataFormatDigits;
2633
- this.showOverlayMedian = config.showOverlayMedian;
2634
- this.showOverlayAvg = config.showOverlayAvg;
2635
- this.chartMode = config.chartMode;
2636
- this.maxBars = config.maxBars;
2637
- this.stackConfig = config.stackConfig;
2638
- this.lineFullWidth = config.lineFullWidth;
2639
- this.lastScenarios = config.scenarios;
2640
- this.updatePosition(config.scenarios);
2641
- }
2642
- getFooter() {
2643
- if (this.measureScale.value === 1 && this.measureUnit === "") {
2644
- return " ";
2645
- }
2646
- return Formatter.translateScenarioLabel("in", this.i18n) + " " + this.measureScale.prefix + this.measureUnit;
2647
- }
2648
- sortScenariosbyVisualisationRules(config) {
2649
- const self = this;
2650
- config.scenarios
2651
- .sort((n1, n2) => {
2652
- return self.ruleSet.getScenarioSorIndex(n1) - self.ruleSet.getScenarioSorIndex(n2);
2653
- })
2654
- .reverse();
2655
- }
2656
- /**
2657
- * Init load of translation dictionary map
2658
- * map is used to translate lables in the table
2659
- *
2660
- * example:
2661
- * ```
2662
- * let i18n: Map<string, string> = new Map();
2663
- * [{key: 'ac',value: 'AC'}].forEach(function(entry){
2664
- * i18n.set(entry.key, entry.value);
2665
- * })
2666
- * ```
2667
- * @param i18n
2668
- */
2669
- setI18n(i18n) {
2670
- this.i18n = this.createI18n(i18n);
2671
- }
2672
- /**
2673
- * Init load raw datasets the loaded dataset is
2674
- * the base on which the filters defined in the config
2675
- * are apllied on internaly it is called prepared DataSet
2676
- *
2677
- * @param data
2678
- * @param filter - data filter
2679
- * @param customColumnNameMap Custon ColumnNameMap can be used if data uses non standard columnames
2680
- */
2681
- setData(data, filter) {
2682
- if (data == null) {
2683
- return;
2684
- }
2685
- this.state = FactoryState.DIRTY; // mark dataSet for update
2686
- this.preparedDataSet.length = 0; // cleans formerly loaded and prepared dataset
2687
- if (filter != null && filter.length > 0) {
2688
- try {
2689
- this.preparedDataSet = alasql(`SELECT * FROM ? WHERE ${filter}`, [data]);
2690
- }
2691
- catch (e) {
2692
- console.error("TimeChart: filter query failed, using unfiltered data", filter, e);
2693
- this.preparedDataSet = data;
2694
- }
2695
- }
2696
- else {
2697
- this.preparedDataSet = data;
2698
- }
2699
- }
2700
- getAllocatedCanvasWidth() {
2701
- // Analytical calculation — doesn't rely on text bbox (unreliable in detached SVGs)
2702
- const axisEnd = this.position.getAxisEndPositionX();
2703
- // Buffer for the last date label extending beyond axis end
2704
- const labelBuffer = this.styles.fontStyles.size * 3;
2705
- // Also consider bbox-based measurement as a fallback (works for rects)
2706
- const bboxWidth = Math.max(this.axisCategoryArea.width, this.scenariosArea.width);
2707
- const bboxTotal = bboxWidth > 0 ? bboxWidth + this.position.leftSideLabelLength : 0;
2708
- return Math.max(axisEnd + labelBuffer, bboxTotal);
2709
- }
2710
- getAllocatedCanvasHeight() {
2711
- if (this.smallestVarianceDataPointValue.value == null ||
2712
- this.highestVarianceDataPointValue.value == null ||
2713
- this.smallestDataPointValue.value == null ||
2714
- this.highestDataPointValue.value == null) {
2715
- return 0;
2716
- }
2717
- // Analytical calculation — doesn't rely on text bbox
2718
- const isRelative = this.isVarianceChart() &&
2719
- this.variancesDataModel.some((e) => e.type === VarianceType.RELATIVE);
2720
- const axisY = this.position.getAxisPositionY(isRelative);
2721
- // Space below axis: gap to date labels + date label height + bottom padding
2722
- const belowAxis = this.position.spacings.labelToAxis + this.position.dataLabelHeight + this.styles.padding.bottom;
2723
- let analyticalHeight;
2724
- if (!this.isOnSameAxisSide()) {
2725
- // Bars extend below axis — account for negative bar + its data label
2726
- const min = this.isVarianceChart() ? this.smallestVarianceDataPointValue : this.smallestDataPointValue;
2727
- const minScaled = Math.abs(min.getScaledUnit());
2728
- analyticalHeight =
2729
- axisY + minScaled + this.position.spacings.labelToColumn + this.position.dataLabelHeight + belowAxis;
2730
- }
2731
- else {
2732
- analyticalHeight = axisY + belowAxis;
2733
- }
2734
- // Also consider bbox-based measurement as a fallback
2735
- const isOnSameAxisSide = this.isOnSameAxisSide();
2736
- const bboxHeight = isOnSameAxisSide
2737
- ? this.axisCategoryArea.height + this.scenariosArea.height
2738
- : this.scenariosArea.height;
2739
- return Math.max(analyticalHeight, bboxHeight);
2740
- }
2741
- toString() {
2742
- const container = new Svg();
2743
- this.draw(container);
2744
- container.id("drawCanvas");
2745
- container.width(this.getAllocatedCanvasWidth());
2746
- container.height(this.getAllocatedCanvasHeight());
2747
- container.attr("overflow", "visible");
2748
- return container.svg();
2749
- }
2750
- draw(svgContainer) {
2751
- this.cleanSVGforRedraw(svgContainer);
2752
- if (this.state === FactoryState.DIRTY) {
2753
- this.state = FactoryState.UP_TO_DATE;
2754
- }
2755
- if (this.isVarianceChart()) {
2756
- this.drawVarianceScenario(this.variancesDataModel, svgContainer);
2757
- this.drawAxisAndLabels(this.variancesDataModel, svgContainer);
2758
- }
2759
- else if (this.stackConfig != null) {
2760
- const effectiveChartMode = this.determineEffectiveChartMode();
2761
- if (effectiveChartMode === ChartMode.LINE) {
2762
- this.drawStackedAreaScenarios(this.dataModel, svgContainer);
2763
- this.drawAxisAndLabelsForLineChart(this.dataModel, svgContainer);
2764
- }
2765
- else {
2766
- this.drawStackedScenarios(this.dataModel, svgContainer);
2767
- this.drawStackedHeaders(this.dataModel, svgContainer);
2768
- this.drawAxisAndLabels(this.dataModel, svgContainer);
2769
- }
2770
- }
2771
- else {
2772
- const effectiveChartMode = this.determineEffectiveChartMode();
2773
- if (effectiveChartMode === ChartMode.LINE) {
2774
- this.drawLineScenarios(this.dataModel, svgContainer);
2775
- this.drawAxisAndLabelsForLineChart(this.dataModel, svgContainer);
2776
- }
2777
- else {
2778
- this.drawScenarios(this.dataModel, svgContainer);
2779
- this.drawOverlayLayer(this.dataModel, svgContainer);
2780
- this.drawAxisAndLabels(this.dataModel, svgContainer);
2781
- }
2782
- }
2783
- }
2784
- determineEffectiveChartMode() {
2785
- if (this.chartMode === ChartMode.LINE) {
2786
- return ChartMode.LINE;
2787
- }
2788
- if (this.chartMode === ChartMode.AUTO) {
2789
- // Auto-switch to line mode when data points exceed maxBars threshold
2790
- if (this.dataModel.length > this.maxBars) {
2791
- return ChartMode.LINE;
2792
- }
2793
- }
2794
- return ChartMode.BAR;
2795
- }
2796
- setPattern(fc, fcPolygonPattern) {
2797
- this.styles.pattern.set(fc, fcPolygonPattern);
2798
- }
2799
- hasNoData() {
2800
- return this.dataModel.length === 0;
2801
- }
2802
- isOnSameAxisSide() {
2803
- if (this.smallestVarianceDataPointValue.value == null ||
2804
- this.highestVarianceDataPointValue.value == null ||
2805
- this.smallestDataPointValue.value == null ||
2806
- this.highestDataPointValue.value == null) {
2807
- return false;
2808
- }
2809
- if (this.isVarianceChart()) {
2810
- return (Math.sign(this.smallestVarianceDataPointValue.value) === Math.sign(this.highestVarianceDataPointValue.value) ||
2811
- (this.smallestDataPointValue.value === 0 && Math.sign(this.highestDataPointValue.value) === 1));
2812
- }
2813
- else {
2814
- return (Math.sign(this.smallestDataPointValue.value) === Math.sign(this.highestDataPointValue.value) ||
2815
- (this.smallestDataPointValue.value === 0 && Math.sign(this.highestDataPointValue.value) === 1));
2816
- }
2817
- }
2818
- createI18n(i18n) {
2819
- this.state = FactoryState.DIRTY;
2820
- const defaultI18n = new Map([
2821
- ["SEPERATOR_WS", ", "],
2822
- ["in", "in"],
2823
- ["ORDER_asc", "↑"],
2824
- ["ORDER_desc", "↓"],
2825
- ["ac1", "AC"],
2826
- ["pp1", "PY"],
2827
- ["fc1", "FC"],
2828
- ["pl1", "PL"],
2829
- ["ac2", "AC2"],
2830
- ["pp2", "PY2"],
2831
- ["fc2", "FC2"],
2832
- ["pl2", "PL2"],
2833
- ["ac3", "AC3"],
2834
- ["pp3", "PY3"],
2835
- ["fc3", "FC3"],
2836
- ["pl3", "PL3"],
2837
- ["ac4", "AC4"],
2838
- ["pp4", "PY4"],
2839
- ["fc4", "FC4"],
2840
- ["pl4", "PL4"],
2841
- ["category", " "],
2842
- ["operation", " "],
2843
- ["there_of", "davon"],
2844
- ["part_of", "in % von"],
2845
- ["ibcssymbol_delta_ac", "Δ{%}"],
2846
- ["ibcssymbol_delta_generic", "Δ({%})"],
2847
- ["ibcssymbol_delta_ac_relative", "Δ{%}%"],
2848
- ["ibcssymbol_delta_generic_relative", "Δ({%})%"],
2849
- ["SUM_TOTAL", "❖"],
2850
- ]);
2851
- return new Map([...defaultI18n, ...i18n]);
2852
- }
2853
- createElementPosition(scenarios) {
2854
- let maxLabelLengthLeft;
2855
- // only need scenarios written on the leftside of bar/ marker
2856
- const scenarioLabelLeft = CalculateSize(scenarios
2857
- .filter((_value, index) => index === 1 || index === 2)
2858
- .map((scenario) => Formatter.translateScenarioLabel(scenario, this.i18n))
2859
- .reduce((a, b) => (a.length < b.length ? b : a), ""), {
2860
- font: this.styles.fontStyles.font,
2861
- fontSize: this.styles.fontStyles.size + "px",
2862
- }).width;
2863
- const titleLength = this.calculateTitleLength(this.leftSideOffsetForHorizontalSync);
2864
- if (scenarioLabelLeft > titleLength) {
2865
- maxLabelLengthLeft = scenarioLabelLeft;
2866
- }
2867
- else {
2868
- maxLabelLengthLeft = titleLength;
2869
- }
2870
- if (this.position != null) {
2871
- maxLabelLengthLeft = maxLabelLengthLeft + this.position.spacings.labelToColumn;
2872
- }
2873
- //if (maxLabelLengthLeft < this.leftSideOffsetForHorizontalSync) {
2874
- // maxLabelLengthLeft = this.leftSideOffsetForHorizontalSync;
2875
- //}
2876
- if (this.leftSideOffsetForHorizontalSync > -1) {
2877
- maxLabelLengthLeft = this.leftSideOffsetForHorizontalSync;
2878
- }
2879
- let min;
2880
- let max;
2881
- if (this.isVarianceChart()) {
2882
- min = this.smallestVarianceDataPointValue;
2883
- max = this.highestVarianceDataPointValue;
2884
- }
2885
- else {
2886
- min = this.smallestDataPointValue;
2887
- max = this.highestDataPointValue;
2888
- }
2889
- // When overflow config is active, create a virtual max so the coordinate system
2890
- // allocates exactly cutHeight + breakGap + overdriveZoneHeight instead of the
2891
- // full (clipped) bar height.
2892
- if (this.overflowConfig) {
2893
- const { cutHeight, overdriveZoneHeight, breakGap } = this.overflowConfig;
2894
- const virtualHeight = cutHeight + overdriveZoneHeight + breakGap;
2895
- // Create a virtual DataPoint with pixelPerUnit=1 so getScaledUnit() returns virtualHeight directly
2896
- max = new DataPoint(virtualHeight, max.scenario, 1, max.variance);
2897
- }
2898
- // In line mode with lineFullWidth enabled, override categoryWidth so data points
2899
- // are evenly distributed across the available container width.
2900
- let effectiveScaleFactors = this.styles.scaleFactors;
2901
- const effectiveMode = this.determineEffectiveChartMode();
2902
- if (this.lineFullWidth &&
2903
- this.availableWidth > 0 &&
2904
- this.dataModel.length > 0 &&
2905
- !this.isVarianceChart() &&
2906
- effectiveMode === ChartMode.LINE) {
2907
- const fontSize = this.styles.fontStyles.size;
2908
- const padding = this.styles.padding;
2909
- const sf = this.styles.scaleFactors;
2910
- // Fixed overhead: padding + scenarioOffset + leftSideLabels + half columnWidth (right margin)
2911
- const fixedOverhead = padding.left + padding.right + fontSize * sf.scenarioOffset + maxLabelLengthLeft + fontSize * sf.columnWidth;
2912
- const availableDataWidth = this.availableWidth - fixedOverhead;
2913
- if (availableDataWidth > 0) {
2914
- const customCategoryWidthFactor = availableDataWidth / this.dataModel.length / fontSize;
2915
- // Enforce minimum to prevent label overlap
2916
- const minFactor = sf.columnWidth * 1.2;
2917
- const finalFactor = Math.max(customCategoryWidthFactor, minFactor);
2918
- // Clone scaleFactors with overridden categoryWidth
2919
- const cloned = new ScaleFactorsTimeChart();
2920
- Object.assign(cloned, sf);
2921
- cloned.categoryWidth = finalFactor;
2922
- effectiveScaleFactors = cloned;
2923
- }
2924
- }
2925
- return new ElementPositions(new Padding(this.styles.padding), effectiveScaleFactors, this.styles.fontStyles, min, max, this.dataModel.length, maxLabelLengthLeft);
2926
- }
2927
- calculateTitleLength(minWidth) {
2928
- let tmpTitle = "_______"; // default width if this.title is sorther
2929
- if (tmpTitle.length < this.title.length) {
2930
- tmpTitle = this.title;
2931
- }
2932
- const width = CalculateSize(tmpTitle, {
2933
- font: this.styles.fontStyles.font,
2934
- fontSize: this.styles.fontStyles.size + "px",
2935
- }).width;
2936
- if (width < minWidth) {
2937
- return minWidth;
2938
- }
2939
- return width;
2940
- }
2941
- setAxisScenario(scenarios) {
2942
- let result = Scenario.AC1;
2943
- if (scenarios != null && scenarios.length > 0) {
2944
- const axis = new VarianceScenario(scenarios.toString());
2945
- if (axis.isValid) {
2946
- result = axis.delta;
2947
- }
2948
- }
2949
- if (result === null) {
2950
- // arrays with invalid scenarios are set to Senario.AC Fallback
2951
- result = Scenario.AC1;
2952
- }
2953
- return result;
2954
- }
2955
- populateModel(selectedScenarios, dateInterval, _level, _sortOrder) {
2956
- var _a;
2957
- if (((_a = this.preparedDataSet) === null || _a === void 0 ? void 0 : _a.length) === 0) {
2958
- return [];
2959
- }
2960
- const select = ``;
2961
- const order = "";
2962
- let result = this.queryDataSet(dateInterval, select, order);
2963
- this.detectNaNCells(selectedScenarios, result);
2964
- result = this.leftOuterJoinDates(result, dateInterval);
2965
- const dataModel = this.createDataRows(result, selectedScenarios);
2966
- return dataModel;
2967
- }
2968
- detectNaNCells(scenarios, res) {
2969
- res.forEach((row) => {
2970
- scenarios.forEach((scenario) => {
2971
- const varianceScenario = new VarianceScenario(scenario);
2972
- if (varianceScenario.isValid === true) {
2973
- if (row[varianceScenario.base + "_cnt"] === 0 || row[varianceScenario.delta + "_cnt"] === 0) {
2974
- row[scenario] = Number.NaN;
2975
- }
2976
- }
2977
- else {
2978
- if (row[scenario + "_cnt"] === 0) {
2979
- row[scenario] = Number.NaN;
2980
- }
2981
- }
2982
- });
2983
- return row;
2984
- });
2985
- }
2986
- findDateInterval(dateInterval) {
2987
- var _a, _b, _c;
2988
- if (dateInterval !== DateDistance.AUTO) {
2989
- return dateInterval;
2990
- }
2991
- const resultMinMax = this.queryMinMaxDates();
2992
- let localDateInterval = DateDistance.DAY;
2993
- if (((_a = resultMinMax[0]) === null || _a === void 0 ? void 0 : _a.mindate) != null) {
2994
- localDateInterval = new DateStringFactory().calculateDistanceType((_b = resultMinMax[0]) === null || _b === void 0 ? void 0 : _b.mindate, (_c = resultMinMax[0]) === null || _c === void 0 ? void 0 : _c.maxdate, this.intervalSpanLimit);
2995
- }
2996
- return localDateInterval;
2997
- }
2998
- queryMinMaxDates() {
2999
- var _a, _b, _c, _d;
3000
- //let result: any[] = [];
3001
- const result = alasql(`SELECT MAX(${"date"}) as maxdate, MIN(${"date"}) as mindate FROM ?`, [this.preparedDataSet]);
3002
- if (((_a = result[0]) === null || _a === void 0 ? void 0 : _a.mindate) != null) {
3003
- result[0].mindate = DateTime.fromMillis((_b = result[0]) === null || _b === void 0 ? void 0 : _b.mindate);
3004
- }
3005
- if (((_c = result[0]) === null || _c === void 0 ? void 0 : _c.maxdate) != null) {
3006
- result[0].maxdate = DateTime.fromMillis((_d = result[0]) === null || _d === void 0 ? void 0 : _d.maxdate);
3007
- }
3008
- return result;
3009
- }
3010
- queryDataSet(dateInterval, select, order) {
3011
- const scenarios = [
3012
- "ac1",
3013
- "ac2",
3014
- "ac3",
3015
- "ac4",
3016
- "pp1",
3017
- "pp2",
3018
- "pp3",
3019
- "pp4",
3020
- "fc1",
3021
- "fc2",
3022
- "fc3",
3023
- "fc4",
3024
- "pl1",
3025
- "pl2",
3026
- "pl3",
3027
- "pl4",
3028
- ];
3029
- const dateSelect = `normalizeDate([date], '${dateInterval}' , '${this.locale}') as calcdate`;
3030
- const result = alasql(`SELECT ${"p.calcdate"} ${select},
3031
- ${scenarios
3032
- .map((scenario) => {
3033
- return `SUM(${scenario} * transformOperator(operation)) as ${scenario}, COUNT(ISNULL(${scenario})) as ${scenario}_cnt`;
3034
- })
3035
- .join(",")}
3036
-
3037
- FROM (SELECT ${dateSelect} ${select},
3038
- ac1,
3039
- ac2,
3040
- ac3,
3041
- ac4,
3042
- pp1,
3043
- pp2,
3044
- pp3,
3045
- pp4,
3046
- fc1,
3047
- fc2,
3048
- fc3,
3049
- fc4,
3050
- pl1,
3051
- pl2,
3052
- pl3,
3053
- pl4
3054
- FROM ?) as p
3055
- GROUP BY ${"calcdate"} ${order}
3056
- ORDER BY ${"calcdate asc"}`, [this.preparedDataSet]);
3057
- return result;
3058
- }
3059
- createDataRows(result, selectedScenarios) {
3060
- const dataModel = [];
3061
- result.forEach((element, index) => {
3062
- dataModel.push({
3063
- id: index,
3064
- category: element.category,
3065
- type: VarianceType.NONE,
3066
- date: element["calcdate"],
3067
- scenario1: new DataPoint(element[selectedScenarios[0]], selectedScenarios[0], this.pixelPerUnit, Scenario.NEU),
3068
- scenario2: new DataPoint(element[selectedScenarios[1]], selectedScenarios[1], this.pixelPerUnit, Scenario.NEU),
3069
- scenario3: new DataPoint(element[selectedScenarios[2]], selectedScenarios[2], this.pixelPerUnit, Scenario.NEU),
3070
- scenario4: new DataPoint(element[selectedScenarios[3]], selectedScenarios[3], this.pixelPerUnit, Scenario.NEU),
3071
- });
3072
- //}
3073
- });
3074
- return dataModel;
3075
- }
3076
- findSmallestDataPointValue(dataModel) {
3077
- const pixel = this.isVarianceChart() ? this.pixelPerPercentage : this.pixelPerUnit;
3078
- let smallestDataPoint = new DataPoint(0, "default", pixel, Scenario.NEU);
3079
- for (const entry of dataModel) {
3080
- for (const current of [entry.scenario1, entry.scenario2, entry.scenario3, entry.scenario4]) {
3081
- if (current && current.value != null) {
3082
- if (current.value < Number(smallestDataPoint.value)) {
3083
- smallestDataPoint = current;
3084
- }
3085
- }
3086
- }
3087
- }
3088
- return smallestDataPoint;
3089
- }
3090
- findHighestDataPointValue(dataModel) {
3091
- const pixel = this.isVarianceChart() ? this.pixelPerPercentage : this.pixelPerUnit;
3092
- let highestDataPoint = new DataPoint(0, "default", pixel, Scenario.NEU);
3093
- for (const entry of dataModel) {
3094
- for (const current of [entry.scenario1, entry.scenario2, entry.scenario3, entry.scenario4]) {
3095
- if (current != null) {
3096
- if (current.value > Number(highestDataPoint.value)) {
3097
- highestDataPoint = current;
3098
- }
3099
- }
3100
- }
3101
- }
3102
- return highestDataPoint;
3103
- }
3104
- populateVarianceModel(variancesConfig, dataModel) {
3105
- const varianceModel = [];
3106
- if (variancesConfig == null || variancesConfig.length === 0) {
3107
- return varianceModel;
3108
- }
3109
- let firstRow = null;
3110
- if (dataModel != null && dataModel.length > 0) {
3111
- firstRow = dataModel[0];
3112
- }
3113
- for (const varianceScenario in variancesConfig) {
3114
- const scenarios = new VarianceScenario(variancesConfig[varianceScenario]);
3115
- if (scenarios.isValid) {
3116
- const scenariomap = this.mapScenarios(scenarios, firstRow);
3117
- const directon = scenarios.direction;
3118
- const pixelPerUnit = scenarios.type === "dr" ? this.pixelPerPercentage : this.pixelPerUnit;
3119
- for (const index in dataModel) {
3120
- varianceModel.push({
3121
- id: Number(index),
3122
- category: dataModel[index].category,
3123
- type: scenarios.type === "dr" ? VarianceType.RELATIVE : VarianceType.ABSOLUTE,
3124
- date: dataModel[index].date,
3125
- scenario1: new DataPoint(this.calculateVariance(scenarios, dataModel[index], scenariomap), scenarios.delta, pixelPerUnit, directon),
3126
- scenario2: new DataPoint(null, null, null, null),
3127
- scenario3: new DataPoint(null, null, null, null),
3128
- scenario4: new DataPoint(null, null, null, null),
3129
- });
3130
- }
3131
- }
3132
- }
3133
- return varianceModel;
3134
- }
3135
- calculateVariance(scenarios, element, scenarioMap) {
3136
- const scenarioBase = scenarioMap.get(scenarios.base);
3137
- const scenarioDelta = scenarioMap.get(scenarios.delta);
3138
- if (scenarioBase == null || scenarioDelta == null) {
3139
- return null;
3140
- }
3141
- if (element[scenarioBase].value == null || element[scenarioDelta].value == null) {
3142
- return null;
3143
- }
3144
- const isRelativeVariance = scenarios.type === VarianceType.RELATIVE;
3145
- if (isRelativeVariance) {
3146
- return (element[scenarioBase].value - element[scenarioDelta].value) / element[scenarioDelta].value;
3147
- }
3148
- else {
3149
- return element[scenarioBase].value - element[scenarioDelta].value;
3150
- }
3151
- }
3152
- mapScenarios(scenarios, firstRow) {
3153
- const varianceMap = new Map();
3154
- if (firstRow == null) {
3155
- return varianceMap;
3156
- }
3157
- ["scenario1", "scenario2", "scenario3", "scenario4"].forEach((scenarioKey) => {
3158
- if (firstRow[scenarioKey].scenario === scenarios.delta) {
3159
- varianceMap.set(scenarios.delta, scenarioKey);
3160
- }
3161
- else if (firstRow[scenarioKey].scenario === scenarios.base) {
3162
- varianceMap.set(scenarios.base, scenarioKey);
3163
- }
3164
- });
3165
- return varianceMap;
3166
- }
3167
- cleanSVGforRedraw(svgContainer) {
3168
- svgContainer.clear();
3169
- }
3170
- isVarianceChart() {
3171
- return this.variancesDataModel && this.variancesDataModel.length > 0;
3172
- }
3173
- createDateFactory() {
3174
- const factory = new DateStringFactory();
3175
- return factory;
3176
- }
3177
- drawAxisAndLabels(dataModel, svgContainer) {
3178
- const dateStringFactory = this.createDateFactory();
3179
- const axisLabelGroup = svgContainer.group().id("AxisAndDateLables");
3180
- let isRelative = false;
3181
- if (this.hideAxisLabels === false) {
3182
- dataModel.forEach((elements, index) => {
3183
- let hookLocation = HookLocation.Top;
3184
- let offset = this.position.spacings.labelToAxis;
3185
- if (elements["scenario1"]["value"] < 0) {
3186
- hookLocation = HookLocation.Bottom;
3187
- offset *= -1;
3188
- }
3189
- if (elements["type"] === VarianceType.RELATIVE) {
3190
- isRelative = true;
3191
- }
3192
- let datelabel = dateStringFactory.getDateString(elements.date, this.dateInterval);
3193
- if (this.axisLabelsMode === AxisLabelsMode.SMART) {
3194
- datelabel = dateStringFactory.getSmartDateString(elements.date, this.dateInterval);
3195
- if (index === 0 && this.dateInterval !== DateDistance.YEAR) {
3196
- datelabel = dateStringFactory.getShortDateString(elements.date, this.dateInterval);
3197
- }
3198
- }
3199
- else if (this.axisLabelsMode === AxisLabelsMode.SHORT) {
3200
- datelabel = dateStringFactory.getShortDateString(elements.date, this.dateInterval);
3201
- }
3202
- new Label(axisLabelGroup, this.position.getColumnCenterPositionX(index), this.position.getAxisPositionY(isRelative) + offset, "", datelabel, this.styles, hookLocation, HookLocation.Center).forceStringTypeDraw();
3203
- });
3204
- }
3205
- else {
3206
- const element = dataModel === null || dataModel === void 0 ? void 0 : dataModel[0];
3207
- if (element && element["type"] === VarianceType.RELATIVE) {
3208
- isRelative = true;
3209
- }
3210
- }
3211
- new Axis({
3212
- scenarioType: this.axisScenario,
3213
- labelText: this.title,
3214
- isRelative: isRelative,
3215
- }, this.position, axisLabelGroup).draw();
3216
- this.axisCategoryArea = {
3217
- height: axisLabelGroup.height(),
3218
- width: axisLabelGroup.width(),
3219
- };
3220
- }
3221
- drawScenarios(dataModel, svgContainer) {
3222
- const columnGroup = svgContainer.group().id("Scenarios");
3223
- const scenarioFactory = new ScenarioFactory(this.position, columnGroup, this.styles, dataModel.length, this.i18n);
3224
- scenarioFactory.setOverflowConfig(this.overflowConfig);
3225
- let hasValidPrim = false;
3226
- dataModel.forEach((elements, index) => {
3227
- scenarioFactory.createPrimaryBar(elements["scenario1"], index).draw(this.dataFormatDigits, this.measureScale);
3228
- scenarioFactory.createSecondaryBar(elements["scenario2"], index).draw();
3229
- scenarioFactory.createPrimaryMarker(elements["scenario3"], index).draw();
3230
- scenarioFactory.createSecondaryMarker(elements["scenario4"], index).draw();
3231
- if (elements["scenario1"].isEmpty() === false) {
3232
- hasValidPrim = true;
3233
- }
3234
- });
3235
- let heightOffset = 0;
3236
- if (hasValidPrim === false) {
3237
- if (this.isOnSameAxisSide()) {
3238
- heightOffset = this.position.dataLabelHeight;
3239
- }
3240
- else {
3241
- heightOffset = this.position.dataLabelHeight * 2;
3242
- }
3243
- }
3244
- this.scenariosArea = {
3245
- height: columnGroup.height() + this.styles.padding.top + this.styles.padding.bottom + heightOffset,
3246
- width: columnGroup.width() + this.position.spacings.columnWidth,
3247
- };
3248
- }
3249
- drawLineScenarios(dataModel, svgContainer) {
3250
- var _a, _b;
3251
- const lineGroup = svgContainer.group().id("LineScenarios");
3252
- // Create collision manager for label overlap detection across all line series
3253
- const collisionManager = new LabelCollisionManager();
3254
- const scenarioFactory = new ScenarioFactory(this.position, lineGroup, this.styles, dataModel.length, this.i18n);
3255
- scenarioFactory.setCollisionManager(collisionManager);
3256
- // Collect data points for each scenario
3257
- const slotDefaults = ["ac1", "pp1", "fc1", "pl1"];
3258
- const slotPoints = [[], [], [], []];
3259
- dataModel.forEach((elements, index) => {
3260
- const keys = ["scenario1", "scenario2", "scenario3", "scenario4"];
3261
- keys.forEach((key, slotIdx) => {
3262
- if (elements[key]) {
3263
- slotPoints[slotIdx].push({ dataPoint: elements[key], index });
3264
- }
3265
- });
3266
- });
3267
- // Build scenario info (only non-empty scenarios)
3268
- const scenarios = [];
3269
- for (let i = 0; i < slotPoints.length; i++) {
3270
- const points = slotPoints[i];
3271
- if (points.length > 0 && points.some((p) => !p.dataPoint.isEmpty())) {
3272
- const scenarioName = ((_b = (_a = points[0]) === null || _a === void 0 ? void 0 : _a.dataPoint) === null || _b === void 0 ? void 0 : _b.scenario) || slotDefaults[i];
3273
- const scenarioType = scenarioName.slice(0, 2).toLowerCase();
3274
- scenarios.push({ points, scenarioName, scenarioType });
3275
- }
3276
- }
3277
- // Sort by z-order: lowest priority first so SVG groups are created in correct render order
3278
- // PL(4) → FC(3) → PP(2) → AC(1) — AC geometry on top of PP geometry
3279
- scenarios.sort((a, b) => {
3280
- const pa = SCENARIO_PRIORITY[a.scenarioType] || 99;
3281
- const pb = SCENARIO_PRIORITY[b.scenarioType] || 99;
3282
- return pb - pa;
3283
- });
3284
- // Create LineSeries in z-order (SVG group creation order = render order)
3285
- const seriesList = [];
3286
- for (const scenario of scenarios) {
3287
- const series = scenarioFactory.createLineSeries(scenario.points, scenario.scenarioName);
3288
- seriesList.push({ series, scenarioType: scenario.scenarioType });
3289
- }
3290
- // Phase 1: Draw geometry (groups already in correct z-order from creation)
3291
- for (const entry of seriesList) {
3292
- entry.series.drawGeometry();
3293
- }
3294
- // Move label group to front so labels render on top of all lines/markers
3295
- scenarioFactory.moveLabelsToFront();
3296
- // Phase 2: Draw labels in priority order (highest priority first)
3297
- // AC(1) → PP(2) → FC(3) → PL(4) so AC claims best label positions first
3298
- const labelOrder = [...seriesList].sort((a, b) => {
3299
- const pa = SCENARIO_PRIORITY[a.scenarioType] || 99;
3300
- const pb = SCENARIO_PRIORITY[b.scenarioType] || 99;
3301
- return pa - pb; // lowest priority number first (AC first)
3302
- });
3303
- for (const entry of labelOrder) {
3304
- entry.series.drawLabels(this.dataFormatDigits, this.measureScale);
3305
- }
3306
- // In line mode the lines only span between data points (all above the axis),
3307
- // so lineGroup.height() does not extend to the axis like bar rects do.
3308
- // Use getColumnPositionY() (the axis baseline) as the minimum height
3309
- // so that axis date labels drawn below are not cut off.
3310
- const axisY = this.position.getColumnPositionY();
3311
- this.scenariosArea = {
3312
- height: Math.max(lineGroup.height() + this.styles.padding.top, axisY) + this.styles.padding.bottom,
3313
- width: lineGroup.width() + this.position.spacings.columnWidth,
3314
- };
3315
- }
3316
- drawAxisAndLabelsForLineChart(dataModel, svgContainer) {
3317
- const dateStringFactory = this.createDateFactory();
3318
- const axisLabelGroup = svgContainer.group().id("AxisAndDateLabelsLine");
3319
- const isRelative = false;
3320
- const lastIndex = dataModel.length - 1;
3321
- if (this.hideAxisLabels === false) {
3322
- dataModel.forEach((elements, index) => {
3323
- // Only show labels for first, last, and year change points
3324
- if (!this.shouldShowLineChartAxisLabel(dataModel, index)) {
3325
- return;
3326
- }
3327
- let hookLocation = HookLocation.Top;
3328
- let offset = this.position.spacings.labelToAxis;
3329
- if (elements["scenario1"]["value"] < 0) {
3330
- hookLocation = HookLocation.Bottom;
3331
- offset *= -1;
3332
- }
3333
- // Get the date label — use smart/short logic when full-width shows all labels
3334
- let datelabel;
3335
- if (this.lineFullWidth && this.availableWidth > 0) {
3336
- if (this.axisLabelsMode === AxisLabelsMode.SMART) {
3337
- datelabel = dateStringFactory.getSmartDateString(elements.date, this.dateInterval);
3338
- if (index === 0 && this.dateInterval !== DateDistance.YEAR) {
3339
- datelabel = dateStringFactory.getShortDateString(elements.date, this.dateInterval);
3340
- }
3341
- }
3342
- else if (this.axisLabelsMode === AxisLabelsMode.SHORT) {
3343
- datelabel = dateStringFactory.getShortDateString(elements.date, this.dateInterval);
3344
- }
3345
- else {
3346
- datelabel = dateStringFactory.getDateString(elements.date, this.dateInterval);
3347
- }
3348
- }
3349
- else {
3350
- datelabel = dateStringFactory.getShortDateString(elements.date, this.dateInterval);
3351
- }
3352
- new Label(axisLabelGroup, this.position.getColumnCenterPositionX(index), this.position.getAxisPositionY(isRelative) + offset, "", datelabel, this.styles, hookLocation, HookLocation.Center).forceStringTypeDraw();
3353
- // Draw vertical dashed separator line at year transitions (except for first and last)
3354
- if (index > 0 && index < lastIndex && this.isYearChange(dataModel, index)) {
3355
- this.drawYearSeparatorLine(axisLabelGroup, index, isRelative);
3356
- }
3357
- });
3358
- }
3359
- new Axis({
3360
- scenarioType: this.axisScenario,
3361
- labelText: this.title,
3362
- isRelative: isRelative,
3363
- }, this.position, axisLabelGroup).draw();
3364
- this.axisCategoryArea = {
3365
- height: axisLabelGroup.height(),
3366
- width: axisLabelGroup.width(),
3367
- };
3368
- }
3369
- shouldShowLineChartAxisLabel(dataModel, index) {
3370
- // In full-width mode, every data point gets a label (enough horizontal space)
3371
- if (this.lineFullWidth && this.availableWidth > 0) {
3372
- return true;
3373
- }
3374
- const lastIndex = dataModel.length - 1;
3375
- // Always show first and last labels
3376
- if (index === 0 || index === lastIndex) {
3377
- return true;
3378
- }
3379
- // Show label if year changed from previous data point
3380
- return this.isYearChange(dataModel, index);
3381
- }
3382
- isYearChange(dataModel, index) {
3383
- var _a, _b;
3384
- if (index === 0) {
3385
- return false;
3386
- }
3387
- const currentDate = (_a = dataModel[index]) === null || _a === void 0 ? void 0 : _a.date;
3388
- const previousDate = (_b = dataModel[index - 1]) === null || _b === void 0 ? void 0 : _b.date;
3389
- if (!currentDate || !previousDate) {
3390
- return false;
3391
- }
3392
- return currentDate.year !== previousDate.year;
3393
- }
3394
- drawYearSeparatorLine(group, index, isRelative) {
3395
- const xPos = this.position.getColumnCenterPositionX(index) - this.position.spacings.columnWidth / 2;
3396
- // Calculate chart height from the max data point
3397
- const chartHeight = this.position.columnValue.max.getScaledUnit() + this.position.dataLabelHeight;
3398
- const topY = this.position.getAxisPositionY(isRelative) - chartHeight;
3399
- const bottomY = this.position.getAxisPositionY(isRelative);
3400
- group
3401
- .line([
3402
- [xPos, topY],
3403
- [xPos, bottomY],
3404
- ])
3405
- .stroke({
3406
- color: "#999999",
3407
- width: 1,
3408
- dasharray: "4,4",
3409
- })
3410
- .attr("stroke-dasharray", "4,4");
3411
- }
3412
- drawVarianceScenario(dataModel, svgContainer) {
3413
- const columnGroup = svgContainer.group().id("Scenarios");
3414
- const scenarioFactory = new ScenarioFactory(this.position, columnGroup, this.styles, dataModel.length, this.i18n);
3415
- scenarioFactory.setOverflowConfig(this.overflowConfig);
3416
- dataModel.forEach((elements, index) => {
3417
- if (elements["type"] === VarianceType.RELATIVE) {
3418
- scenarioFactory.createRelativeVarianceBar(elements["scenario1"], index).draw();
3419
- }
3420
- else {
3421
- scenarioFactory.createVarianceBar(elements["scenario1"], index).draw(this.dataFormatDigits, this.measureScale);
3422
- }
3423
- });
3424
- this.scenariosArea = {
3425
- height: columnGroup.height() + this.styles.padding.top + this.styles.padding.bottom,
3426
- width: columnGroup.width() + this.position.spacings.columnWidth,
3427
- };
3428
- return columnGroup;
3429
- }
3430
- /**
3431
- * Draw stacked bar columns. Supports stacking by scenario or by data dimension.
3432
- * When stacking by scenario with multiple scenario types (e.g. ac+pl),
3433
- * uses overlay mode: each type group is drawn from the same baseline,
3434
- * back-to-front per IBCS convention (PL behind, AC on top).
3435
- */
3436
- drawStackedScenarios(dataModel, svgContainer) {
3437
- if (!this.stackConfig)
3438
- return;
3439
- const stackGroup = svgContainer.group().id("StackedScenarios");
3440
- const isScenarioStack = this.stackConfig.by === StackBy.SCENARIOS;
3441
- dataModel.forEach((elements, index) => {
3442
- const scenarioKeys = ["scenario1", "scenario2", "scenario3", "scenario4"];
3443
- const segments = [];
3444
- if (isScenarioStack) {
3445
- for (const key of scenarioKeys) {
3446
- const dp = elements[key];
3447
- if (dp && !dp.isEmpty() && dp.value != null) {
3448
- segments.push({ value: dp.value, scenario: dp.scenario, dataPoint: dp });
3449
- }
3450
- }
3451
- }
3452
- else {
3453
- const dp = elements["scenario1"];
3454
- if (dp && !dp.isEmpty() && dp.value != null) {
3455
- segments.push({ value: dp.value, scenario: dp.scenario, dataPoint: dp });
3456
- }
3457
- }
3458
- if (segments.length === 0)
3459
- return;
3460
- // Check if we have multiple scenario type groups for overlay mode
3461
- const prefixes = isScenarioStack
3462
- ? new Set(segments.map((s) => getScenarioPrefix(s.scenario)))
3463
- : new Set();
3464
- if (prefixes.size > 1) {
3465
- // Overlay mode: group by scenario prefix, draw each group from same baseline
3466
- const groupMap = new Map();
3467
- for (const seg of segments) {
3468
- const prefix = getScenarioPrefix(seg.scenario);
3469
- if (!groupMap.has(prefix))
3470
- groupMap.set(prefix, []);
3471
- groupMap.get(prefix).push(seg);
3472
- }
3473
- const groups = [];
3474
- for (const prefix of IBCS_LAYER_ORDER) {
3475
- if (groupMap.has(prefix)) {
3476
- groups.push({ prefix, segments: groupMap.get(prefix) });
3477
- groupMap.delete(prefix);
3478
- }
3479
- }
3480
- for (const [prefix, segs] of groupMap) {
3481
- groups.push({ prefix, segments: segs });
3482
- }
3483
- // Draw each group from baseline=0 (overlapping)
3484
- groups.forEach((group, groupIdx) => {
3485
- const groupTotal = group.segments.reduce((sum, s) => sum + Math.abs(s.value), 0);
3486
- const colorIndex = groups.length - 1 - groupIdx;
3487
- let cumulativeValue = 0;
3488
- let lastColumn = null;
3489
- group.segments.forEach((seg) => {
3490
- const column = new StackedColumn(this.position, this.styles, seg.dataPoint, index, cumulativeValue, seg.scenario, colorIndex, this.stackConfig.mode, groupTotal, true, stackGroup);
3491
- column.draw(this.dataFormatDigits, this.measureScale);
3492
- cumulativeValue += Math.abs(seg.value);
3493
- lastColumn = column;
3494
- });
3495
- if (lastColumn) {
3496
- lastColumn.drawTotalLabel(this.dataFormatDigits, this.measureScale);
3497
- }
3498
- });
3499
- }
3500
- else {
3501
- // Single group or non-scenario: additive stacking
3502
- if (this.stackConfig.order === "asc") {
3503
- segments.sort((a, b) => a.value - b.value);
3504
- }
3505
- else if (this.stackConfig.order === "desc") {
3506
- segments.sort((a, b) => b.value - a.value);
3507
- }
3508
- const total = segments.reduce((sum, s) => sum + Math.abs(s.value), 0);
3509
- let cumulativeValue = 0;
3510
- let lastColumn = null;
3511
- segments.forEach((seg, segIdx) => {
3512
- const column = new StackedColumn(this.position, this.styles, seg.dataPoint, index, cumulativeValue, seg.scenario, segIdx, this.stackConfig.mode, total, isScenarioStack, stackGroup);
3513
- column.draw(this.dataFormatDigits, this.measureScale);
3514
- cumulativeValue += Math.abs(seg.value);
3515
- lastColumn = column;
3516
- });
3517
- if (lastColumn) {
3518
- lastColumn.drawTotalLabel(this.dataFormatDigits, this.measureScale);
3519
- }
3520
- }
3521
- });
3522
- this.scenariosArea = {
3523
- height: stackGroup.height() + this.styles.padding.top + this.styles.padding.bottom,
3524
- width: stackGroup.width() + this.position.spacings.columnWidth,
3525
- };
3526
- }
3527
- /**
3528
- * Draw column headers next to stacked columns showing what each group/segment represents.
3529
- * For overlay mode (multiple scenario types): shows one header per group.
3530
- * For single-group: shows individual segment headers.
3531
- */
3532
- drawStackedHeaders(dataModel, svgContainer) {
3533
- if (!this.stackConfig || dataModel.length === 0)
3534
- return;
3535
- const isScenarioStack = this.stackConfig.by === StackBy.SCENARIOS;
3536
- if (!isScenarioStack)
3537
- return;
3538
- const headerGroup = svgContainer.group().id("StackedHeaders");
3539
- const firstRow = dataModel[0];
3540
- const scenarioKeys = ["scenario1", "scenario2", "scenario3", "scenario4"];
3541
- const segments = [];
3542
- for (const key of scenarioKeys) {
3543
- const dp = firstRow[key];
3544
- if (dp && !dp.isEmpty() && dp.value != null) {
3545
- segments.push({ value: dp.value, scenario: dp.scenario, dataPoint: dp });
3546
- }
3547
- }
3548
- if (segments.length === 0)
3549
- return;
3550
- const prefixes = new Set(segments.map((s) => getScenarioPrefix(s.scenario)));
3551
- const axisY = this.position.getColumnPositionY();
3552
- const xBase = this.position.getColumnCenterPositionX(0) - this.position.getColumnWidth() / 2;
3553
- const labelX = xBase - this.position.spacings.labelToColumn;
3554
- if (prefixes.size > 1) {
3555
- // Overlay mode: one header per group, centered vertically on group's column height
3556
- const groupMap = new Map();
3557
- for (const seg of segments) {
3558
- const prefix = getScenarioPrefix(seg.scenario);
3559
- if (!groupMap.has(prefix))
3560
- groupMap.set(prefix, []);
3561
- groupMap.get(prefix).push(seg);
3562
- }
3563
- const groups = [];
3564
- for (const prefix of IBCS_LAYER_ORDER) {
3565
- if (groupMap.has(prefix)) {
3566
- groups.push({ prefix, segments: groupMap.get(prefix) });
3567
- groupMap.delete(prefix);
3568
- }
3569
- }
3570
- for (const [prefix, segs] of groupMap) {
3571
- groups.push({ prefix, segments: segs });
3572
- }
3573
- groups.forEach((group) => {
3574
- const groupTotal = group.segments.reduce((sum, s) => sum + Math.abs(s.value), 0);
3575
- const pixelPerUnit = group.segments[0].dataPoint.pixelPerUnit;
3576
- const groupPixelHeight = this.stackConfig.mode === StackMode.RELATIVE ? pixelPerUnit : groupTotal * pixelPerUnit;
3577
- const centerY = axisY - groupPixelHeight / 2;
3578
- const labelText = this.i18n.get(group.prefix + "1") || group.prefix.toUpperCase();
3579
- new Label(headerGroup, labelX, centerY, "STACK_HEADER", labelText, this.styles, HookLocation.Center, HookLocation.Right).forceStringTypeDraw();
3580
- });
3581
- }
3582
- else {
3583
- // Single group: show individual segment headers
3584
- if (this.stackConfig.order === "asc")
3585
- segments.sort((a, b) => a.value - b.value);
3586
- else if (this.stackConfig.order === "desc")
3587
- segments.sort((a, b) => b.value - a.value);
3588
- const total = segments.reduce((sum, s) => sum + Math.abs(s.value), 0);
3589
- const pixelPerUnit = segments[0].dataPoint.pixelPerUnit;
3590
- let cumulativePixels = 0;
3591
- segments.forEach((seg) => {
3592
- let segmentHeight;
3593
- if (this.stackConfig.mode === StackMode.RELATIVE) {
3594
- const proportion = total !== 0 ? Math.abs(seg.value) / total : 0;
3595
- segmentHeight = proportion * pixelPerUnit;
3596
- }
3597
- else {
3598
- segmentHeight = Math.abs(seg.value * pixelPerUnit);
3599
- }
3600
- const centerY = axisY - cumulativePixels - segmentHeight / 2;
3601
- const labelText = this.i18n.get(seg.scenario) || seg.scenario;
3602
- new Label(headerGroup, labelX, centerY, "STACK_HEADER", labelText, this.styles, HookLocation.Center, HookLocation.Right).forceStringTypeDraw();
3603
- cumulativePixels += segmentHeight;
3604
- });
3605
- }
3606
- }
3607
- /**
3608
- * Draw stacked area chart (line mode with stack).
3609
- * Computes cumulative y-values and draws AreaFill paths between layers.
3610
- */
3611
- drawStackedAreaScenarios(dataModel, svgContainer) {
3612
- if (!this.stackConfig)
3613
- return;
3614
- const areaGroup = svgContainer.group().id("StackedAreaScenarios");
3615
- const isScenarioStack = this.stackConfig.by === StackBy.SCENARIOS;
3616
- const stackMode = this.stackConfig.mode;
3617
- const scenarioKeys = ["scenario1", "scenario2", "scenario3", "scenario4"];
3618
- // Determine how many layers we have
3619
- const layerCount = isScenarioStack
3620
- ? scenarioKeys.filter((key) => dataModel.some((el) => el[key] && !el[key].isEmpty()))
3621
- .length
3622
- : 1;
3623
- if (layerCount === 0)
3624
- return;
3625
- // Build cumulative values per layer
3626
- // cumulativePoints[layerIdx][dataIdx] = cumulative y-value at that point
3627
- const cumulativeValues = [];
3628
- const layerScenarios = [];
3629
- // Identify active layers
3630
- const activeLayers = [];
3631
- for (const key of scenarioKeys) {
3632
- if (dataModel.some((el) => el[key] && !el[key].isEmpty())) {
3633
- activeLayers.push(key);
3634
- }
3635
- }
3636
- // Compute cumulative values
3637
- for (let layerIdx = 0; layerIdx < activeLayers.length; layerIdx++) {
3638
- const key = activeLayers[layerIdx];
3639
- const values = [];
3640
- for (let dataIdx = 0; dataIdx < dataModel.length; dataIdx++) {
3641
- const dp = dataModel[dataIdx][key];
3642
- const value = dp && !dp.isEmpty() && dp.value != null ? dp.value : 0;
3643
- const prevCumulative = layerIdx > 0 ? cumulativeValues[layerIdx - 1][dataIdx] : 0;
3644
- if (stackMode === StackMode.RELATIVE) {
3645
- // For relative: need total at each x position
3646
- const total = activeLayers.reduce((sum, k) => {
3647
- const d = dataModel[dataIdx][k];
3648
- return sum + (d && !d.isEmpty() && d.value != null ? Math.abs(d.value) : 0);
3649
- }, 0);
3650
- const proportion = total !== 0 ? Math.abs(value) / total : 0;
3651
- values.push(prevCumulative + proportion);
3652
- }
3653
- else {
3654
- values.push(prevCumulative + value);
3655
- }
3656
- }
3657
- cumulativeValues.push(values);
3658
- const firstDp = dataModel[0][key];
3659
- layerScenarios.push((firstDp === null || firstDp === void 0 ? void 0 : firstDp.scenario) || "ac1");
3660
- }
3661
- // Convert cumulative values to pixel coordinates
3662
- const axisY = this.position.getColumnPositionY();
3663
- const pixelPerUnit = this.pixelPerUnit;
3664
- const toAreaPoints = (values) => {
3665
- return values.map((val, idx) => ({
3666
- x: this.position.getColumnCenterPositionX(idx),
3667
- y: axisY -
3668
- (stackMode === StackMode.RELATIVE
3669
- ? val * pixelPerUnit // pixelPerUnit acts as "height for 100%"
3670
- : val * pixelPerUnit),
3671
- }));
3672
- };
3673
- // Baseline (y = axis)
3674
- const baselinePoints = dataModel.map((_, idx) => ({
3675
- x: this.position.getColumnCenterPositionX(idx),
3676
- y: axisY,
3677
- }));
3678
- // Draw area fills bottom-to-top
3679
- for (let layerIdx = 0; layerIdx < cumulativeValues.length; layerIdx++) {
3680
- const upperPoints = toAreaPoints(cumulativeValues[layerIdx]);
3681
- const lowerPoints = layerIdx === 0 ? baselinePoints : toAreaPoints(cumulativeValues[layerIdx - 1]);
3682
- const scenarioType = isScenarioStack ? layerScenarios[layerIdx] : null;
3683
- const areaFill = new AreaFill(areaGroup, upperPoints, lowerPoints, scenarioType, layerIdx, isScenarioStack);
3684
- areaFill.draw();
3685
- areaFill.drawBoundaryLine();
3686
- }
3687
- this.scenariosArea = {
3688
- height: areaGroup.height() + this.styles.padding.top + this.styles.padding.bottom,
3689
- width: areaGroup.width() + this.position.spacings.columnWidth,
3690
- };
3691
- }
3692
- drawOverlayLayer(dataModel, svgContainer) {
3693
- const overlayGroup = svgContainer.group().id("Overlay");
3694
- const scenarioFactory = new ScenarioFactory(this.position, overlayGroup, this.styles, dataModel.length, this.i18n);
3695
- if (this.showOverlayAvg === true) {
3696
- let previousDataPoint = null;
3697
- const avgDataModel = tranformToAvgDataModel(dataModel);
3698
- avgDataModel.forEach((elements, index) => {
3699
- if (previousDataPoint != null) {
3700
- scenarioFactory
3701
- .createLine(`Ø ${this.i18n.get(elements["scenario1"].scenario) || elements["scenario1"].scenario}`, elements["scenario1"], previousDataPoint, index - 1)
3702
- .draw(this.dataFormatDigits, this.measureScale);
3703
- }
3704
- previousDataPoint = elements["scenario1"];
3705
- });
3706
- }
3707
- if (this.showOverlayMedian === true) {
3708
- let previousDataPoint = null;
3709
- const medianDataModel = tranformToMedianDataModel(dataModel);
3710
- medianDataModel.forEach((elements, index) => {
3711
- if (previousDataPoint != null) {
3712
- scenarioFactory
3713
- .createLine(`Mdn ${this.i18n.get(elements["scenario1"].scenario) || elements["scenario1"].scenario}`, elements["scenario1"], previousDataPoint, index - 1)
3714
- .draw(this.dataFormatDigits, this.measureScale);
3715
- }
3716
- previousDataPoint = elements["scenario1"];
3717
- });
3718
- }
3719
- }
3720
- leftOuterJoinDates(result, dateInterval) {
3721
- const to = DateTime.max(...result.map(function (e) {
3722
- return e.calcdate;
3723
- }));
3724
- const from = DateTime.min(...result.map(function (e) {
3725
- return e.calcdate;
3726
- }));
3727
- const dateRange = new DateStringFactory().datesBetween(from, to, dateInterval, this.intervalSpanLimit);
3728
- const dateRangeEntries = new Map();
3729
- dateRange.forEach((element, idx) => {
3730
- dateRangeEntries.set(element.toISO(), {
3731
- id: idx,
3732
- calcdate: element,
3733
- category: null,
3734
- ac1: null,
3735
- ac2: null,
3736
- ac3: null,
3737
- ac4: null,
3738
- pp1: null,
3739
- pp2: null,
3740
- pp3: null,
3741
- pp4: null,
3742
- fc1: null,
3743
- fc2: null,
3744
- fc3: null,
3745
- fc4: null,
3746
- pl1: null,
3747
- pl2: null,
3748
- pl3: null,
3749
- pl4: null,
3750
- isEmpty: true,
3751
- });
3752
- });
3753
- result.forEach((element) => {
3754
- const millisecondKey = element.calcdate.toISO();
3755
- const placeholder = dateRangeEntries.get(millisecondKey);
3756
- if (placeholder && placeholder.isEmpty) {
3757
- const newElement = {
3758
- id: placeholder.id,
3759
- calcdate: element.calcdate,
3760
- category: element.category,
3761
- ac1: element.ac1,
3762
- ac2: element.ac2,
3763
- ac3: element.ac3,
3764
- ac4: element.ac4,
3765
- pp1: element.pp1,
3766
- pp2: element.pp2,
3767
- pp3: element.pp3,
3768
- pp4: element.pp4,
3769
- fc1: element.fc1,
3770
- fc2: element.fc2,
3771
- fc3: element.fc3,
3772
- fc4: element.fc4,
3773
- pl1: element.pl1,
3774
- pl2: element.pl2,
3775
- pl3: element.pl3,
3776
- pl4: element.pl4,
3777
- isEmpty: false,
3778
- };
3779
- dateRangeEntries.set(millisecondKey, newElement);
3780
- }
3781
- });
3782
- return Array.from(dateRangeEntries.values());
3783
- }
3784
- }
3785
- function tranformToAvgDataModel(dataModel) {
3786
- const total = dataModel.reduce((sum, elements) => {
3787
- var _a;
3788
- return sum + (((_a = elements["scenario1"]) === null || _a === void 0 ? void 0 : _a.value) || 0); // Sum up the values of scenario1
3789
- }, 0);
3790
- const count = dataModel.filter((elements) => { var _a; return ((_a = elements["scenario1"]) === null || _a === void 0 ? void 0 : _a.value) !== undefined; }).length; // Count valid scenario1 values
3791
- const average = count > 0 ? total / count : 0; // Calculate the average, avoid division by zero
3792
- // Create a new first element
3793
- const firstElement = Object.assign(Object.assign({}, dataModel[0]), { scenario1: new DataPoint(average, dataModel[0]["scenario1"].scenario, dataModel[0]["scenario1"].pixelPerUnit, dataModel[0]["scenario1"].variance) });
3794
- // Create a new last element
3795
- const lastElement = Object.assign(Object.assign({}, dataModel[dataModel.length - 1]), { scenario1: new DataPoint(average, dataModel[dataModel.length - 1]["scenario1"].scenario, dataModel[dataModel.length - 1]["scenario1"].pixelPerUnit, dataModel[dataModel.length - 1]["scenario1"].variance) });
3796
- // Add the new first and last elements to the transformed data model
3797
- return [
3798
- firstElement,
3799
- ...dataModel.map((elements) => {
3800
- return Object.assign(Object.assign({}, elements), { scenario1: new DataPoint(average, elements["scenario1"].scenario, elements["scenario1"].pixelPerUnit, elements["scenario1"].variance) });
3801
- }),
3802
- lastElement,
3803
- ];
3804
- }
3805
- function tranformToMedianDataModel(dataModel) {
3806
- const values = dataModel
3807
- .map((elements) => { var _a; return (_a = elements["scenario1"]) === null || _a === void 0 ? void 0 : _a.value; })
3808
- .filter((value) => value !== undefined)
3809
- .sort((a, b) => a - b);
3810
- const median = values.length % 2 === 0
3811
- ? (values[values.length / 2 - 1] + values[values.length / 2]) / 2
3812
- : values[Math.floor(values.length / 2)];
3813
- // Create a new first element
3814
- const firstElement = Object.assign(Object.assign({}, dataModel[0]), { scenario1: new DataPoint(median, dataModel[0]["scenario1"].scenario, dataModel[0]["scenario1"].pixelPerUnit, dataModel[0]["scenario1"].variance) });
3815
- // Create a new last element
3816
- const lastElement = Object.assign(Object.assign({}, dataModel[dataModel.length - 1]), { scenario1: new DataPoint(median, dataModel[dataModel.length - 1]["scenario1"].scenario, dataModel[dataModel.length - 1]["scenario1"].pixelPerUnit, dataModel[dataModel.length - 1]["scenario1"].variance) });
3817
- // Add the new first and last elements to the transformed data model
3818
- return [
3819
- firstElement,
3820
- ...dataModel.map((elements) => {
3821
- return Object.assign(Object.assign({}, elements), { scenario1: new DataPoint(median, elements["scenario1"].scenario, elements["scenario1"].pixelPerUnit, elements["scenario1"].variance) });
3822
- }),
3823
- lastElement,
3824
- ];
3825
- }
3826
-
3827
- // import { IAdapter } from "../../../../utils/helper/IAdapter";
3828
- // import { CompareUtil } from "../../../../utils/helper/CompareUtil";
3829
- // import { StringAdapter } from "../../../../utils/helper/StringAdapter";
3830
- // import { Order, OrderAdapter } from "../../../../utils/model/Order";
3831
- // import { AdapterUtils } from "../../../../utils/helper/AdapterUtils";
3832
- /**
3833
- * Configuration for an IBCS time-series chart component.
3834
- *
3835
- * Controls the vertical scale, date interval detection, axis labelling,
3836
- * and chart rendering mode (bar, line, etc.).
3837
- */
3838
- class TimeChartComponentConfig {
3839
- constructor(data, scenarios) {
3840
- this.data = data;
3841
- this.scenarios = scenarios;
3842
- /** Variance column identifiers (e.g. `["d_ac1_pl1_pos"]`) for delta visualizations. */
3843
- this.variances = [];
3844
- this.title = "";
3845
- this.hideAxisLabels = false;
3846
- /** Vertical scale factor: pixels per one data unit. Controls bar/line height. */
3847
- this.pixelPerUnit = 10;
3848
- /** Vertical scale factor for percentage variances: pixels per 1.0 (=100%). */
3849
- this.pixelPerPercentage = 50;
3850
- /** Maximum data points to display; 0 means unlimited. */
3851
- this.limit = 0;
3852
- this.sortOrder = new OrderAdapter(new StringAdapter()).default();
3853
- this.level = AggregationLevel.CATEGORY;
3854
- /** Pixel offset from left edge for horizontal alignment across multiple charts. -1 disables sync. */
3855
- this.leftSideOffsetForHorizontalSync = -1;
3856
- /** Date granularity (year, quarter, month, etc.). AUTO auto-detects from data. */
3857
- this.dateInterval = DateDistance.AUTO;
3858
- /** Controls how axis labels are rendered; SMART suppresses overlapping labels. */
3859
- this.axisLabelsMode = AxisLabelsMode.SMART;
3860
- /** Maximum number of date intervals before the chart truncates or scrolls. */
3861
- this.intervalSpanLimit = 28;
3862
- this.filter = "";
3863
- this.measureScale = new SiPrefix();
3864
- this.measureUnit = "";
3865
- this.showMeasureScale = true;
3866
- this.dataFormatDigits = { decimal: 1, percent: 2 };
3867
- this.showOverlayMedian = true;
3868
- this.showOverlayAvg = true;
3869
- this.chartMode = ChartMode.BAR;
3870
- /** Maximum number of bars to render before truncating; prevents visual overload. */
3871
- this.maxBars = 28;
3872
- this.stackConfig = null;
3873
- /** When true, line charts extend to the full width of the chart area. */
3874
- this.lineFullWidth = true;
3875
- }
3876
- }
3877
- /**
3878
- * Converts untyped JSON into a validated {@link TimeChartComponentConfig}.
3879
- *
3880
- * Requires the raw dataset for measure scale auto-calculation.
3881
- */
3882
- class TimeChartComponentConfigAdapter {
3883
- constructor(dataRowAdapter, orderAdapter, stringAdapter, dataFormatDigitsAdapter, dataSet) {
3884
- this.dataRowAdapter = dataRowAdapter;
3885
- this.orderAdapter = orderAdapter;
3886
- this.stringAdapter = stringAdapter;
3887
- this.dataFormatDigitsAdapter = dataFormatDigitsAdapter;
3888
- this.dataSet = dataSet;
3889
- }
3890
- adapt(data) {
3891
- const dataSet = AdapterUtils.adaptArray(data.data, this.dataRowAdapter);
3892
- const scenarios = AdapterUtils.adaptArray(data.scenarios, this.stringAdapter);
3893
- const config = new TimeChartComponentConfig(dataSet, scenarios);
3894
- if (CompareUtil.isArray(data.variances)) {
3895
- config.variances = AdapterUtils.adaptArray(data.variances, this.stringAdapter);
3896
- }
3897
- if (CompareUtil.isString(data.title)) {
3898
- config.title = data.title;
3899
- }
3900
- if (CompareUtil.isBoolean(data.hideAxisLabels)) {
3901
- config.hideAxisLabels = data.hideAxisLabels;
3902
- }
3903
- if (CompareUtil.isNumber(data.pixelPerUnit)) {
3904
- config.pixelPerUnit = data.pixelPerUnit;
3905
- }
3906
- if (CompareUtil.isNumber(data.pixelPerPercentage)) {
3907
- config.pixelPerPercentage = data.pixelPerPercentage;
3908
- }
3909
- if (CompareUtil.isNumber(data.limit)) {
3910
- config.limit = data.limit;
3911
- }
3912
- if (CompareUtil.isExisting(data.sortOrder)) {
3913
- config.sortOrder = this.orderAdapter.adapt(data.sortOrder);
3914
- }
3915
- if (CompareUtil.isExisting(data.level)) {
3916
- config.level = data.level;
3917
- }
3918
- if (CompareUtil.isExisting(data.dateInterval)) {
3919
- config.dateInterval = data.dateInterval;
3920
- }
3921
- if (CompareUtil.isExisting(data.axisLabelsMode)) {
3922
- config.axisLabelsMode = data.axisLabelsMode;
3923
- }
3924
- if (CompareUtil.isNumber(data.leftSideOffsetForHorizontalSync)) {
3925
- config.leftSideOffsetForHorizontalSync = data.leftSideOffsetForHorizontalSync;
3926
- }
3927
- if (CompareUtil.isNumber(data.intervalSpanLimit)) {
3928
- config.intervalSpanLimit = data.intervalSpanLimit;
3929
- }
3930
- if (CompareUtil.isString(data.filter)) {
3931
- config.filter = data.filter;
3932
- }
3933
- if (CompareUtil.isExisting(data.measureScale)) {
3934
- config.measureScale = DataAnalyzer.calculateMeasureScale(this.dataSet, config.scenarios, data.measureScale);
3935
- }
3936
- if (CompareUtil.isString(data.measureUnit)) {
3937
- config.measureUnit = data.measureUnit;
3938
- }
3939
- if (CompareUtil.isBoolean(data.showMeasureScale)) {
3940
- config.showMeasureScale = data.showMeasureScale;
3941
- }
3942
- if (CompareUtil.isExisting(data.dataFormatDigits)) {
3943
- config.dataFormatDigits = this.dataFormatDigitsAdapter.adapt(data.dataFormatDigits);
3944
- }
3945
- if (CompareUtil.isBoolean(data.showOverlayAvg)) {
3946
- config.showOverlayAvg = data.showOverlayAvg;
3947
- }
3948
- if (CompareUtil.isBoolean(data.showOverlayMedian)) {
3949
- config.showOverlayMedian = data.showOverlayMedian;
3950
- }
3951
- if (CompareUtil.isExisting(data.chartMode)) {
3952
- config.chartMode = data.chartMode;
3953
- }
3954
- if (CompareUtil.isNumber(data.maxBars)) {
3955
- config.maxBars = data.maxBars;
3956
- }
3957
- if (CompareUtil.isExisting(data.stackConfig)) {
3958
- config.stackConfig = data.stackConfig;
3959
- }
3960
- if (CompareUtil.isBoolean(data.lineFullWidth)) {
3961
- config.lineFullWidth = data.lineFullWidth;
3962
- }
3963
- return config;
3964
- }
3965
- default() {
3966
- return new TimeChartComponentConfig([], []);
3967
- }
3968
- }
3969
-
3970
- const ibcsChartTimeCss = () => `:host{position:relative;display:inline-block}.categories{text-align:right;font-size:var(--bn-font-size, 1em);font-family:var(--bn-font-family, "Noto Sans", "Helvetica Neue", Helvetica, sans-serif);color:var(--bn-font-color, black)}.label-bg{fill:var(--bn-font-background, white);opacity:0.7}.label-text{text-align:right;font-size:var(--bn-font-size, 1em);font-family:var(--bn-font-family, "Noto Sans", "Helvetica Neue", Helvetica, sans-serif);color:var(--bn-font-color, black)}.axis-title{text-align:center;font-family:var(--bn-font-family, "Noto Sans", "Helvetica Neue", Helvetica, sans-serif);color:var(--bn-font-color, black)}.axis-default{stroke:black;stroke-width:0.1em}.axis-ac{stroke:black;stroke-width:0.1em}.axis-pp{stroke:grey;stroke-width:0.1em}.axis-fc{stroke:black;stroke-dasharray:2;stroke-width:0.1em}.axis-pl{stroke:white;stroke-width:0.1em;outline-offset:0em;outline:0.1em solid black}canvas{image-rendering:-moz-crisp-edges;image-rendering:-webkit-crisp-edges;image-rendering:pixelated;image-rendering:crisp-edges}.measure{font-weight:bold}span{display:inline-block}.hidePatternContainer{height:0;width:0}div{float:left}.hide{opacity:0}.footer{margin:0.2em;font-size:0.6em}.footer-hide{margin:0.2em;font-size:0.6em;opacity:0}`;
3971
-
3972
- const IbcsChartTime = class {
3973
- constructor(hostRef) {
3974
- registerInstance(this, hostRef);
3975
- // @Prop() dimension: { height: number, width: number } = {height: 400, width: 450};
3976
- this.data = [];
3977
- this.scenarios = [];
3978
- this.variances = []; //["dfc_ac_neg"]
3979
- this.hideAxisLabels = false; //false
3980
- this.pixelPerUnit = 2; //2
3981
- this.pixelPerPercentage = 50; //2
3982
- this.limit = 0;
3983
- this.leftSideOffsetForHorizontalSync = -1;
3984
- this.i18n = new Map(); // I18nMode;
3985
- this.order = {
3986
- hierarchy: [],
3987
- direction: OrderDirection.ASC,
3988
- };
3989
- this.level = AggregationLevel.CATEGORY;
3990
- this.dateInterval = DateDistance.AUTO;
3991
- this.intervalSpanLimit = 28;
3992
- this.axisLabelsMode = AxisLabelsMode.SMART;
3993
- this.filter = "";
3994
- this.measureScale = "_";
3995
- this.measureUnit = "";
3996
- this.showMeasureScale = true;
3997
- this.showOverlayMedian = false;
3998
- this.showOverlayAvg = false;
3999
- this.chartMode = ChartMode.BAR;
4000
- this.maxBars = 28;
4001
- this.stackConfig = null;
4002
- this.lineFullWidth = true;
4003
- this.containerWidth = 0;
4004
- this.dataFormatDigits = { percent: 2, decimal: 1 };
4005
- this.parentDimensions = { width: 0, height: 0 };
4006
- }
4007
- render() {
4008
- var _a, _b, _c;
4009
- if (this.chart === undefined) {
4010
- return h(Host, null);
4011
- }
4012
- if (this.chart.hasNoData()) {
4013
- const errorMsg = this.i18n.get("NO_DATA") || "==No Data==";
4014
- return (h(Host, null, h("p", { class: "warning" }, errorMsg)));
4015
- }
4016
- return (h(Host, null, h("div", { innerHTML: (_a = this.pattern) === null || _a === void 0 ? void 0 : _a.toString(), class: "hidePatternContainer" }), h("div", { class: this.showMeasureScale ? "footer" : "footer-hide" }, (_b = this.chart) === null || _b === void 0 ? void 0 : _b.getFooter()), h("div", { innerHTML: (_c = this.chart) === null || _c === void 0 ? void 0 : _c.toString() })));
4017
- }
4018
- async componentWillLoad() {
4019
- var _a;
4020
- const config = this.prepareConfig();
4021
- const styles = this.prepareStyle();
4022
- const availableWidth = this.containerWidth || 0;
4023
- this.chart = new TimeChart(new IBCSRuleSet(), config, styles, availableWidth);
4024
- this.chart.setI18n(this.i18n);
4025
- this.autoFitScaling(config, styles);
4026
- this.chart.setAvailableHeight(((_a = this.parentDimensions) === null || _a === void 0 ? void 0 : _a.height) || 0);
4027
- this.pattern = new CustomPattern(this.chart.styles);
4028
- this.chart.setPattern("fc", this.pattern.getFCPolygonPattern());
4029
- }
4030
- async componentWillUpdate() {
4031
- var _a;
4032
- if (this.chart == null) {
4033
- return;
4034
- }
4035
- const config = this.prepareConfig();
4036
- const styles = this.prepareStyle();
4037
- this.chart.setI18n(this.i18n);
4038
- this.chart.setStyles(styles);
4039
- this.chart.setAvailableWidth(this.containerWidth || 0);
4040
- this.chart.setConfig(config);
4041
- this.autoFitScaling(config, styles);
4042
- this.chart.setAvailableHeight(((_a = this.parentDimensions) === null || _a === void 0 ? void 0 : _a.height) || 0);
4043
- this.pattern = new CustomPattern(this.chart.styles);
4044
- this.chart.setPattern("fc", this.pattern.getFCPolygonPattern());
4045
- }
4046
- /**
4047
- * Two-pass auto-fit: only when pixelPerUnit is 0 (auto mode).
4048
- * Explicit values are never overridden — the outer component warns
4049
- * about overflow via componentDidRender.
4050
- */
4051
- autoFitScaling(config, styles) {
4052
- var _a;
4053
- if (config.pixelPerUnit > 0) {
4054
- return; // Explicit value — respect it, do not override
4055
- }
4056
- const targetHeight = (_a = this.parentDimensions) === null || _a === void 0 ? void 0 : _a.height;
4057
- const availableWidth = this.containerWidth || 0;
4058
- if (!targetHeight || targetHeight <= 0) {
4059
- config.pixelPerUnit = 1; // No parent info — use fallback
4060
- this.chart = new TimeChart(new IBCSRuleSet(), config, styles, availableWidth);
4061
- this.chart.setI18n(this.i18n);
4062
- return;
4063
- }
4064
- // First pass with pixelPerUnit=1 to measure the real SVG height
4065
- config.pixelPerUnit = 1;
4066
- this.chart = new TimeChart(new IBCSRuleSet(), config, styles, availableWidth);
4067
- this.chart.setI18n(this.i18n);
4068
- this.chart.toString();
4069
- const svgHeight = this.chart.getAllocatedCanvasHeight();
4070
- if (svgHeight <= 0) {
4071
- return;
4072
- }
4073
- // Scale so the chart fits in ~90% of the available height
4074
- config.pixelPerUnit = (targetHeight * 0.9) / svgHeight;
4075
- // Second pass with the corrected scaling
4076
- this.chart = new TimeChart(new IBCSRuleSet(), config, styles, availableWidth);
4077
- this.chart.setI18n(this.i18n);
4078
- }
4079
- async componentWillRender() {
4080
- // return await (async () => {
4081
- // // console.log("componentWillRender", this.chart);
4082
- // if (this.chart) {
4083
- // // this.chart.draw(SVG(this.drawElement) as Svg);
4084
- // }
4085
- // })()
4086
- }
4087
- componentDidLoad() {
4088
- // if (this.chart == null) {
4089
- // return;
4090
- // }
4091
- // this.chart.draw(SVG(this.drawElement) as Svg);
4092
- // forceUpdate(getElement(this));
4093
- }
4094
- componentDidUpdate() {
4095
- //if (this.chart) {
4096
- // this.chart.draw(SVG(this.drawElement) as Svg);
4097
- //}
4098
- }
4099
- prepareConfig() {
4100
- return new TimeChartComponentConfigAdapter(new TimeChartDataRowAdapter(), new OrderAdapter(new StringAdapter()), new StringAdapter(), new DataFormatDigitsAdapter(), this.data).adapt({
4101
- data: this.data,
4102
- scenarios: this.scenarios,
4103
- variances: this.variances,
4104
- title: this.chartTitle,
4105
- hideAxisLabels: this.hideAxisLabels,
4106
- pixelPerUnit: this.pixelPerUnit,
4107
- pixelPerPercentage: this.pixelPerPercentage,
4108
- level: this.level,
4109
- dateInterval: this.dateInterval,
4110
- axisLabelsMode: this.axisLabelsMode,
4111
- limit: this.limit,
4112
- sortOrder: this.order,
4113
- leftSideOffsetForHorizontalSync: this.leftSideOffsetForHorizontalSync,
4114
- intervalSpanLimit: this.intervalSpanLimit,
4115
- filter: this.filter,
4116
- measureScale: this.measureScale,
4117
- measureUnit: this.measureUnit,
4118
- showMeasureScale: this.showMeasureScale,
4119
- dataFormatDigits: this.dataFormatDigits,
4120
- showOverlayMedian: this.showOverlayMedian,
4121
- showOverlayAvg: this.showOverlayAvg,
4122
- chartMode: this.chartMode,
4123
- maxBars: this.maxBars,
4124
- stackConfig: this.stackConfig,
4125
- lineFullWidth: this.lineFullWidth,
4126
- });
4127
- }
4128
- prepareStyle() {
4129
- return new TimeChartStylesAdapter(new ScaleFactorsTimeChartAdapter(), new FontStyleAdapter(), new SVGStyleGroupAdapter(new SVGStyleAdapter()), new SVGVariancesStyleGroupAdapter(new SVGStyleAdapter()), new PaddingAdapter()).adapt(this.styles);
4130
- }
4131
- get element() { return getElement(this); }
4132
- };
4133
- IbcsChartTime.style = ibcsChartTimeCss();
4134
-
4135
- export { IbcsChartTime as ibcs_chart_time };