-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
gauge_component.tsx
423 lines (366 loc) · 13.3 KB
/
gauge_component.tsx
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import React, { FC, memo, useCallback } from 'react';
import { Chart, Goal, Settings } from '@elastic/charts';
import { FormattedMessage } from '@kbn/i18n-react';
import type { PaletteOutput } from '@kbn/coloring';
import { FieldFormat } from '@kbn/field-formats-plugin/common';
import type { CustomPaletteState } from '@kbn/charts-plugin/public';
import { EmptyPlaceholder } from '@kbn/charts-plugin/public';
import { getOverridesFor } from '@kbn/chart-expressions-common';
import { isVisDimension } from '@kbn/visualizations-plugin/common/utils';
import { i18n } from '@kbn/i18n';
import {
GaugeRenderProps,
GaugeLabelMajorMode,
GaugeLabelMajorModes,
GaugeColorModes,
GaugeShapes,
GaugeTicksPositions,
} from '../../common';
import {
getAccessorsFromArgs,
getMaxValue,
getMinValue,
getValueFromAccessor,
getSubtypeByGaugeType,
getGoalConfig,
computeMinMax,
} from './utils';
import { getIcons } from './utils/icons';
import './index.scss';
import { GaugeCentralMajorMode, GaugeTicksPosition } from '../../common/types';
import { isBulletShape, isRoundShape } from '../../common/utils';
import './gauge.scss';
declare global {
interface Window {
/**
* Flag used to enable debugState on elastic charts
*/
_echDebugStateFlag?: boolean;
}
}
const TRANSPARENT = `rgba(255,255,255,0)`;
function normalizeBands(
{ colors, stops, range, rangeMax, rangeMin }: CustomPaletteState,
{ min, max }: { min: number; max: number }
) {
if (!stops.length) {
const step = (max - min) / colors.length;
return [min, ...colors.map((_, i) => min + (i + 1) * step)];
}
let firstRanges = [min];
let lastRanges = [max];
let correctMin = rangeMin;
let correctMax = rangeMax;
if (range === 'percent') {
correctMin = min + rangeMin * ((max - min) / 100);
correctMax = min + rangeMax * ((max - min) / 100);
}
if (correctMin > min && isFinite(correctMin)) {
firstRanges = [min, correctMin];
}
if (correctMax < max && isFinite(correctMax)) {
lastRanges = [correctMax, max];
}
if (range === 'percent') {
const filteredStops = stops.filter((stop) => stop > 0 && stop < 100);
return [
...firstRanges,
...filteredStops.map((step) => min + step * ((max - min) / 100)),
...lastRanges,
];
}
const orderedStops = stops.filter((stop, i) => stop < max && stop > min);
return [...firstRanges, ...orderedStops, ...lastRanges];
}
const toPercents = (min: number, max: number) => (v: number) => (v - min) / (max - min);
function normalizeBandsLegacy({ colors, stops }: CustomPaletteState, value: number) {
const min = stops[0];
const max = stops[stops.length - 1];
const convertToPercents = toPercents(min, max);
const normalizedStops = stops.map(convertToPercents);
if (max < value) {
normalizedStops.push(convertToPercents(value));
}
return normalizedStops;
}
function actualValueToPercentsLegacy({ stops }: CustomPaletteState, value: number) {
const min = stops[0];
const max = stops[stops.length - 1];
const convertToPercents = toPercents(min, max);
return convertToPercents(value);
}
function getTitle(
majorMode?: GaugeLabelMajorMode | GaugeCentralMajorMode,
major?: string,
fallbackTitle?: string
) {
if (majorMode === GaugeLabelMajorModes.NONE) {
return '';
}
if (majorMode === GaugeLabelMajorModes.AUTO) {
return fallbackTitle || '';
}
return major || fallbackTitle || '';
}
const getPreviousSectionValue = (value: number, bands: number[]) => {
// bands value is equal to the stop. The purpose of this value is coloring the previous section, which is smaller, then the band.
// So, the smaller value should be taken. For the first element -1, for the next - middle value of the previous section.
let prevSectionValue = value - 1;
const valueIndex = bands.indexOf(value);
const prevBand = bands[valueIndex - 1];
const curBand = bands[valueIndex];
if (valueIndex > 0) {
prevSectionValue = value - (curBand - prevBand) / 2;
}
return prevSectionValue;
};
function getTicksLabels(baseStops: number[]) {
const tenPercentRange = (Math.max(...baseStops) - Math.min(...baseStops)) * 0.1;
const lastIndex = baseStops.length - 1;
return baseStops.filter((stop, i) => {
if (i === 0 || i === lastIndex) {
return true;
}
return !(
stop - baseStops[i - 1] < tenPercentRange || baseStops[lastIndex] - stop < tenPercentRange
);
});
}
function getTicks(
ticksPosition: GaugeTicksPosition,
range: [number, number],
colorBands?: number[],
percentageMode?: boolean
) {
if (ticksPosition === GaugeTicksPositions.HIDDEN) {
return [];
}
if (ticksPosition === GaugeTicksPositions.BANDS && colorBands) {
return colorBands && getTicksLabels(colorBands);
}
}
export const GaugeComponent: FC<GaugeRenderProps> = memo(
({
data,
args,
uiState,
formatFactory,
paletteService,
chartsThemeService,
renderComplete,
overrides,
}) => {
const {
shape: gaugeType,
palette,
colorMode,
labelMinor,
labelMajor,
labelMajorMode,
centralMajor,
centralMajorMode,
ticksPosition,
commonLabel,
} = args;
const chartBaseTheme = chartsThemeService.useChartsBaseTheme();
const getColor = useCallback(
(
value,
paletteConfig: PaletteOutput<CustomPaletteState>,
bands: number[],
percentageMode?: boolean
) => {
let stops = paletteConfig.params?.stops ?? [];
if (percentageMode) {
stops = bands.map((v) => v * 100);
}
const { min, max } = computeMinMax(paletteConfig, bands);
return paletteService
.get(paletteConfig?.name ?? 'custom')
.getColorForValue?.(value, { ...paletteConfig.params, stops }, { min, max });
},
[paletteService]
);
// Legacy chart was not formatting numbers, when was forming overrideColors.
// To support the behavior of the color overriding, it is required to skip all the formatting, except percent.
const overrideColor = useCallback(
(value: number, bands: number[], formatter?: FieldFormat) => {
const overrideColors = uiState?.get('vis.colors') ?? {};
const valueIndex = bands.findIndex((band, index, allBands) => {
if (index === allBands.length - 1) {
return false;
}
return value >= band && value < allBands[index + 1];
});
if (valueIndex < 0 || valueIndex === bands.length - 1) {
return undefined;
}
const curValue = bands[valueIndex];
const nextValue = bands[valueIndex + 1];
return overrideColors[
`${formatter?.convert(curValue) ?? curValue} - ${
formatter?.convert(nextValue) ?? nextValue
}`
];
},
[uiState]
);
const onRenderChange = useCallback(
(isRendered: boolean = true) => {
if (isRendered) {
renderComplete();
}
},
[renderComplete]
);
const table = data;
const accessors = getAccessorsFromArgs(args, table.columns);
if (!accessors || !accessors.metric) {
// Chart is not ready
return null;
}
const chartTheme = chartsThemeService.useChartsTheme();
const metricColumn = table.columns.find((col) => col.id === accessors.metric);
const chartData = table.rows.filter(
(v) => typeof v[accessors.metric!] === 'number' || Array.isArray(v[accessors.metric!])
);
const row = chartData?.[0];
const metricValue = args.metric ? getValueFromAccessor(accessors.metric, row) : undefined;
const icon = getIcons(gaugeType);
if (typeof metricValue !== 'number') {
return <EmptyPlaceholder icon={icon} renderComplete={onRenderChange} />;
}
const goal = accessors.goal ? getValueFromAccessor(accessors.goal, row) : undefined;
const min = getMinValue(row, accessors, palette?.params, args.respectRanges);
const max = getMaxValue(row, accessors, palette?.params, args.respectRanges);
if (min === max) {
return (
<EmptyPlaceholder
icon={icon}
message={
<FormattedMessage
id="expressionGauge.renderer.chartCannotRenderEqual"
defaultMessage="Minimum and maximum values may not be equal"
/>
}
renderComplete={onRenderChange}
/>
);
}
if (min > max) {
return (
<EmptyPlaceholder
icon={icon}
message={
<FormattedMessage
id="expressionGauge.renderer.chartCannotRenderMinGreaterMax"
defaultMessage="Minimum value may not be greater than maximum value"
/>
}
renderComplete={onRenderChange}
/>
);
}
const customMetricFormatParams = isVisDimension(args.metric) ? args.metric.format : undefined;
const tableMetricFormatParams = metricColumn?.meta?.params?.params
? metricColumn?.meta?.params
: undefined;
const defaultMetricFormatParams = {
id: 'number',
params: {
pattern: max - min > 5 ? `0,0` : `0,0.0`,
},
};
const tickFormatter = formatFactory(
customMetricFormatParams ?? tableMetricFormatParams ?? defaultMetricFormatParams
);
let bands: number[] = (palette?.params as CustomPaletteState)
? normalizeBands(palette?.params as CustomPaletteState, { min, max })
: [min, max];
// TODO: format in charts
let actualValue = Math.round(Math.min(Math.max(metricValue, min), max) * 1000) / 1000;
if (args.percentageMode && palette?.params && palette?.params.stops?.length) {
bands = normalizeBandsLegacy(palette?.params as CustomPaletteState, actualValue);
actualValue = actualValueToPercentsLegacy(palette?.params as CustomPaletteState, actualValue);
}
const totalTicks = getTicks(ticksPosition, [min, max], bands, args.percentageMode);
const ticks =
totalTicks && gaugeType === GaugeShapes.CIRCLE
? totalTicks.slice(0, totalTicks.length - 1)
: totalTicks;
const goalConfig = getGoalConfig(gaugeType);
const labelMajorTitle = getTitle(labelMajorMode, labelMajor, metricColumn?.name);
// added extra space for nice rendering
const majorExtraSpaces = isBulletShape(gaugeType) ? ' ' : '';
const minorExtraSpaces = isBulletShape(gaugeType) ? ' ' : '';
const extraTitles = isRoundShape(gaugeType)
? {
centralMinor: tickFormatter.convert(actualValue),
centralMajor: getTitle(centralMajorMode, centralMajor, metricColumn?.name),
}
: {};
return (
<div className="gauge__wrapper">
<Chart {...getOverridesFor(overrides, 'chart')}>
<Settings
noResults={<EmptyPlaceholder icon={icon} renderComplete={onRenderChange} />}
debugState={window._echDebugStateFlag ?? false}
theme={[{ background: { color: 'transparent' } }, chartTheme]}
baseTheme={chartBaseTheme}
ariaLabel={args.ariaLabel}
ariaUseDefaultSummary={!args.ariaLabel}
onRenderChange={onRenderChange}
locale={i18n.getLocale()}
{...getOverridesFor(overrides, 'settings')}
/>
<Goal
id="goal"
subtype={getSubtypeByGaugeType(gaugeType)}
base={bands[0]}
target={goal && goal >= bands[0] && goal <= bands[bands.length - 1] ? goal : undefined}
actual={actualValue}
tickValueFormatter={({ value: tickValue }) => tickFormatter.convert(tickValue)}
tooltipValueFormatter={(tooltipValue) => tickFormatter.convert(tooltipValue)}
bands={bands}
ticks={ticks}
domain={{ min, max }}
bandFillColor={
colorMode === GaugeColorModes.PALETTE
? (val) => {
const value = getPreviousSectionValue(val.value, bands);
const overridedColor = overrideColor(
value,
args.percentageMode ? bands : args.palette?.params?.stops ?? [],
args.percentageMode ? tickFormatter : undefined
);
if (overridedColor) {
return overridedColor;
}
return args.palette
? getColor(value, args.palette, bands, args.percentageMode) ?? TRANSPARENT
: TRANSPARENT;
}
: () => TRANSPARENT
}
labelMajor={labelMajorTitle ? `${labelMajorTitle}${majorExtraSpaces}` : labelMajorTitle}
labelMinor={labelMinor ? `${labelMinor}${minorExtraSpaces}` : ''}
{...extraTitles}
{...goalConfig}
{...getOverridesFor(overrides, 'gauge')}
/>
</Chart>
{commonLabel && <div className="gauge__label">{commonLabel}</div>}
</div>
);
}
);
// default export required for React.Lazy
// eslint-disable-next-line import/no-default-export
export { GaugeComponent as default };