-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathchartLayoutGenerators.ts
More file actions
351 lines (304 loc) · 10.6 KB
/
chartLayoutGenerators.ts
File metadata and controls
351 lines (304 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/*
* Copyright (C) 2020 Graylog, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*/
import zipWith from 'lodash/zipWith';
import sum from 'lodash/sum';
import flattenDeep from 'lodash/flattenDeep';
import type { DefaultTheme } from 'styled-components';
import type { FieldUnitType } from 'views/types';
import type Series from 'views/logic/aggregationbuilder/Series';
import { parseSeries } from 'views/logic/aggregationbuilder/Series';
import type { BarMode } from 'views/logic/aggregationbuilder/visualizations/BarVisualizationConfig';
import type AggregationWidgetConfig from 'views/logic/aggregationbuilder/AggregationWidgetConfig';
import {
getBaseUnit,
getPrettifiedValue,
roundValue,
convertValueToBaseUnit,
} from 'views/components/visualizations/utils/unitConverters';
import type { ChartDefinition } from 'views/components/visualizations/ChartData';
import type FieldUnit from 'views/logic/aggregationbuilder/FieldUnit';
import {
DEFAULT_AXIS_KEY,
TIME_AXIS_LABELS_QUANTITY,
DECIMAL_PLACES,
Y_POSITION_AXIS_STEP,
NO_FIELD_NAME_SERIES,
} from 'views/components/visualizations/Constants';
import type UnitsConfig from 'views/logic/aggregationbuilder/UnitsConfig';
import getFieldNameFromTrace from 'views/components/visualizations/utils/getFieldNameFromTrace';
import type { PieHoverTemplateSettings } from 'views/components/visualizations/hooks/usePieChartDataSettingsWithCustomUnits';
import getDefaultPlotYLayoutSettings from 'views/components/visualizations/utils/getDefaultPlotYLayoutSettings';
import formatValueWithUnitLabel from 'views/components/visualizations/utils/formatValueWithUnitLabel';
type DefaultAxisKey = 'withoutUnit';
const getYAxisPosition = (axisCount: number) => {
const diff = Math.floor(axisCount / 2) * Y_POSITION_AXIS_STEP;
if (axisCount % 2 === 0) {
return 1 - diff + Y_POSITION_AXIS_STEP;
}
return diff;
};
const getYAxisSide = (axisCount: number) => {
if (axisCount % 2 === 0) {
return 'right';
}
return 'left';
};
const getTicklabelPositionSettings = (axisCount: number) => {
switch (axisCount) {
case 4:
return { ticklabelposition: 'inside' };
default:
return {};
}
};
const getYAxisPositioningSettings = (axisCount: number) => ({
position: getYAxisPosition(axisCount),
side: getYAxisSide(axisCount),
overlaying: axisCount > 1 ? 'y' : undefined,
...getTicklabelPositionSettings(axisCount),
});
const defaultSettings = {
autoshift: true,
automargin: true,
fixedrange: true,
rangemode: 'tozero',
};
const getFormatSettingsWithCustomTickVals = (values: Array<any>, fieldType: FieldUnitType) => {
const min = Math.min(0, ...values);
const max = Math.max(...values);
const step = (max - min) / TIME_AXIS_LABELS_QUANTITY;
const valueBaseUnit = getBaseUnit(fieldType);
const prettyRoundedValues = Array(TIME_AXIS_LABELS_QUANTITY)
.fill(null)
.map((_, index) => {
const originalBaseValue = (index + 1) * step;
const prettyValue = getPrettifiedValue(originalBaseValue, {
abbrev: valueBaseUnit.abbrev,
unitType: valueBaseUnit.unitType,
});
return {
value: roundValue(prettyValue.value),
unit: prettyValue.unit,
};
});
const roundedTickValues = prettyRoundedValues.map(
(prettified) => convertValueToBaseUnit(prettified.value, prettified.unit).value,
);
const roundedTickText = prettyRoundedValues.map((prettified) =>
formatValueWithUnitLabel(prettified?.value, prettified.unit.abbrev, 0),
);
return {
tickvals: roundedTickValues,
ticktext: roundedTickText,
range: [0, roundedTickValues[TIME_AXIS_LABELS_QUANTITY - 1]],
};
};
const getFormatSettingsByData = (unitTypeKey: FieldUnitType | DefaultAxisKey, values: Array<any>) => {
switch (unitTypeKey) {
case 'percent':
return {
tickformat: `.${DECIMAL_PLACES}%`,
};
case 'size':
return getFormatSettingsWithCustomTickVals(values, 'size');
case 'time':
return getFormatSettingsWithCustomTickVals(values, 'time');
default:
return {
tickformat: ',~r',
};
}
};
const getUnitLayoutWithData = (
unitTypeKey: FieldUnitType | DefaultAxisKey,
axisCount: number,
values: Array<any>,
theme: DefaultTheme,
) => ({
...getFormatSettingsByData(unitTypeKey, values),
...getYAxisPositioningSettings(axisCount),
...defaultSettings,
...getDefaultPlotYLayoutSettings(theme),
});
type SeriesName = string;
type AxisName = string;
/** Needs to group traces. In case if barmode: 'stack' | 'relative' | 'overlay'
* we are grouping by y-axis to join traces into same trace on chart */
export const getBarChartTraceOffsetGroup = (
barmode: BarMode,
yaxis: string,
traceIndex: number,
): string | number | undefined => {
if (barmode === 'stack' || barmode === 'relative' || barmode === 'overlay') {
return yaxis;
}
if (barmode === 'group') {
return traceIndex;
}
return undefined;
};
export type UnitTypeMapper = {} | Record<FieldUnitType, { axisKeyName: string; axisCount: number }>;
type SeriesUnitMapper = {} | Record<SeriesName, FieldUnitType | DefaultAxisKey>;
type MapperAxisNumber = Record<string, number>;
type YAxisMapper = Record<SeriesName, AxisName>;
type FieldNameToAxisNameMapper = {} | Record<string, string>;
type FieldNameToAxisCountMapper = {} | Record<string, number>;
export type MappersForYAxis = {
seriesUnitMapper: SeriesUnitMapper;
mapperAxisNumber: MapperAxisNumber;
unitTypeMapper: UnitTypeMapper;
yAxisMapper: YAxisMapper;
fieldNameToAxisNameMapper: FieldNameToAxisNameMapper;
fieldNameToAxisCountMapper: FieldNameToAxisCountMapper;
};
export const generateMappersForYAxis = ({
series,
units,
}: {
series: AggregationWidgetConfig['series'];
units: AggregationWidgetConfig['units'];
}): MappersForYAxis => {
let axisCount = 1;
const unitTypeMapper: {} | UnitTypeMapper = {};
const mapper = {};
const mapperAxisNumber = {};
const seriesUnitMapper = {};
const fieldNameToAxisNameMapper = {};
const fieldNameToAxisCountMapper = {};
series.forEach((s: Series) => {
const seriesName = s.config.name || s.function;
const { field } = parseSeries(s.function) ?? {};
const unitType = units?.getFieldUnit(field)?.unitType;
const unitTypeKey = unitType || DEFAULT_AXIS_KEY;
const fieldKey = field ?? NO_FIELD_NAME_SERIES;
if (!unitTypeMapper[unitTypeKey]) {
const axisNameNumberPart = axisCount > 1 ? axisCount : '';
const axisKeyName = `yaxis${axisNameNumberPart}`;
unitTypeMapper[unitTypeKey] = { axisCount, axisKeyName };
mapper[seriesName] = `y${axisNameNumberPart}`;
mapperAxisNumber[seriesName] = axisCount;
fieldNameToAxisNameMapper[fieldKey] = `y${axisNameNumberPart}`;
fieldNameToAxisCountMapper[fieldKey] = axisCount;
axisCount += 1;
} else {
const currentAxisCount = unitTypeMapper[unitTypeKey].axisCount;
const axisNameNumberPart = currentAxisCount > 1 ? currentAxisCount : '';
mapper[seriesName] = `y${axisNameNumberPart}`;
mapperAxisNumber[seriesName] = currentAxisCount;
fieldNameToAxisNameMapper[fieldKey] = `y${axisNameNumberPart}`;
fieldNameToAxisCountMapper[fieldKey] = currentAxisCount;
}
seriesUnitMapper[seriesName] = unitTypeKey;
});
return {
unitTypeMapper,
yAxisMapper: mapper,
mapperAxisNumber,
seriesUnitMapper,
fieldNameToAxisNameMapper,
fieldNameToAxisCountMapper,
};
};
// eslint-disable-next-line default-param-last
const joinValues = (values: Array<Array<number>> = [], barmode: BarMode): Array<number> => {
if (barmode === 'stack' || barmode === 'relative') {
return zipWith(...values, (...iterateValues) => sum(iterateValues));
}
return flattenDeep(values);
};
export type GenerateLayoutsParams = {
unitTypeMapper: UnitTypeMapper;
chartData: Array<ChartDefinition>;
barmode?: BarMode;
widgetUnits: UnitsConfig;
config: AggregationWidgetConfig;
theme: DefaultTheme;
};
export const generateLayouts = ({
unitTypeMapper,
chartData,
barmode,
widgetUnits,
config,
theme,
}: GenerateLayoutsParams) => {
const groupYValuesByUnitTypeKey = chartData.reduce<{} | Record<FieldUnitType | DefaultAxisKey, Array<Array<any>>>>(
(res, value: ChartDefinition) => {
const traceName = value.fullPath;
const fieldName = getFieldNameFromTrace({ series: config.series, fullPath: traceName });
const unit = widgetUnits.getFieldUnit(fieldName);
const unitType = unit?.unitType ?? DEFAULT_AXIS_KEY;
if (!res[unitType]) {
res[unitType] = [value.y];
} else {
res[unitType].push(value.y);
}
return res;
},
{},
);
return Object.fromEntries(
Object.entries(unitTypeMapper).map(([unitTypeKey, { axisKeyName, axisCount }]) => {
const unitValues = joinValues(groupYValuesByUnitTypeKey[unitTypeKey], barmode);
return [axisKeyName, getUnitLayoutWithData(unitTypeKey as FieldUnitType, axisCount, unitValues, theme)];
}),
);
};
const getHoverTexts = ({ convertedValues, unit }: { convertedValues: Array<any>; unit: FieldUnit }) =>
convertedValues.map((value) => {
const prettified =
unit &&
unit.isDefined &&
getPrettifiedValue(value, {
abbrev: unit.abbrev,
unitType: unit.unitType,
});
if (!prettified) return value;
return formatValueWithUnitLabel(prettified?.value, prettified.unit.abbrev);
});
export const getHoverTemplateSettings = ({
convertedValues,
unit,
name,
}: {
convertedValues: Array<any>;
unit: FieldUnit;
name: string;
}): { text: Array<string>; hovertemplate: string; meta: string } | {} => {
if (unit?.unitType === 'time' || unit?.unitType === 'size') {
return {
text: getHoverTexts({ convertedValues, unit }),
hovertemplate: '%{text}<br><extra>%{meta}</extra>',
meta: name,
};
}
return {};
};
export const getPieHoverTemplateSettings = ({
convertedValues,
unit,
name,
}: {
convertedValues: Array<any>;
unit: FieldUnit;
name: string;
}): PieHoverTemplateSettings | {} => ({
text: getHoverTexts({ convertedValues, unit }),
hovertemplate: '<b>%{label}</b><br>%{text}<br>%{percent}',
meta: name,
textinfo: 'percent',
});