-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
expression.tsx
895 lines (826 loc) · 29 KB
/
expression.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
/*
* 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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import './expression.scss';
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import {
Chart,
Settings,
Axis,
LineSeries,
AreaSeries,
BarSeries,
Position,
GeometryValue,
XYChartSeriesIdentifier,
StackMode,
VerticalAlignment,
HorizontalAlignment,
ElementClickListener,
BrushEndListener,
CurveType,
} from '@elastic/charts';
import { I18nProvider } from '@kbn/i18n/react';
import {
ExpressionFunctionDefinition,
ExpressionRenderDefinition,
Datatable,
DatatableRow,
} from 'src/plugins/expressions/public';
import { IconType } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { RenderMode } from 'src/plugins/expressions';
import {
LensMultiTable,
FormatFactory,
ILensInterpreterRenderHandlers,
LensFilterEvent,
LensBrushEvent,
} from '../types';
import { XYArgs, SeriesType, visualizationTypes, LayerArgs } from './types';
import { VisualizationContainer } from '../visualization_container';
import { isHorizontalChart, getSeriesColor } from './state_helpers';
import { ExpressionValueSearchContext, search } from '../../../../../src/plugins/data/public';
import {
ChartsPluginSetup,
PaletteRegistry,
SeriesLayer,
} from '../../../../../src/plugins/charts/public';
import { EmptyPlaceholder } from '../shared_components';
import { desanitizeFilterContext } from '../utils';
import { fittingFunctionDefinitions, getFitOptions } from './fitting_functions';
import { getAxesConfiguration } from './axes_configuration';
import { getColorAssignments } from './color_assignment';
import { getXDomain, XyEndzones } from './x_domain';
declare global {
interface Window {
/**
* Flag used to enable debugState on elastic charts
*/
_echDebugStateFlag?: boolean;
}
}
type InferPropType<T> = T extends React.FunctionComponent<infer P> ? P : T;
type SeriesSpec = InferPropType<typeof LineSeries> &
InferPropType<typeof BarSeries> &
InferPropType<typeof AreaSeries>;
export interface XYChartProps {
data: LensMultiTable;
args: XYArgs;
}
export interface XYRender {
type: 'render';
as: 'lens_xy_chart_renderer';
value: XYChartProps;
}
export type XYChartRenderProps = XYChartProps & {
chartsThemeService: ChartsPluginSetup['theme'];
paletteService: PaletteRegistry;
formatFactory: FormatFactory;
timeZone: string;
minInterval: number | undefined;
onClickValue: (data: LensFilterEvent['data']) => void;
onSelectRange: (data: LensBrushEvent['data']) => void;
renderMode: RenderMode;
syncColors: boolean;
};
export const xyChart: ExpressionFunctionDefinition<
'lens_xy_chart',
LensMultiTable | ExpressionValueSearchContext | null,
XYArgs,
XYRender
> = {
name: 'lens_xy_chart',
type: 'render',
inputTypes: ['lens_multitable', 'kibana_context', 'null'],
help: i18n.translate('xpack.lens.xyChart.help', {
defaultMessage: 'An X/Y chart',
}),
args: {
title: {
types: ['string'],
help: 'The chart title.',
},
description: {
types: ['string'],
help: '',
},
xTitle: {
types: ['string'],
help: i18n.translate('xpack.lens.xyChart.xTitle.help', {
defaultMessage: 'X axis title',
}),
},
yTitle: {
types: ['string'],
help: i18n.translate('xpack.lens.xyChart.yLeftTitle.help', {
defaultMessage: 'Y left axis title',
}),
},
yRightTitle: {
types: ['string'],
help: i18n.translate('xpack.lens.xyChart.yRightTitle.help', {
defaultMessage: 'Y right axis title',
}),
},
legend: {
types: ['lens_xy_legendConfig'],
help: i18n.translate('xpack.lens.xyChart.legend.help', {
defaultMessage: 'Configure the chart legend.',
}),
},
fittingFunction: {
types: ['string'],
options: [...fittingFunctionDefinitions.map(({ id }) => id)],
help: i18n.translate('xpack.lens.xyChart.fittingFunction.help', {
defaultMessage: 'Define how missing values are treated',
}),
},
valueLabels: {
types: ['string'],
options: ['hide', 'inside'],
help: '',
},
tickLabelsVisibilitySettings: {
types: ['lens_xy_tickLabelsConfig'],
help: i18n.translate('xpack.lens.xyChart.tickLabelsSettings.help', {
defaultMessage: 'Show x and y axes tick labels',
}),
},
gridlinesVisibilitySettings: {
types: ['lens_xy_gridlinesConfig'],
help: i18n.translate('xpack.lens.xyChart.gridlinesSettings.help', {
defaultMessage: 'Show x and y axes gridlines',
}),
},
axisTitlesVisibilitySettings: {
types: ['lens_xy_axisTitlesVisibilityConfig'],
help: i18n.translate('xpack.lens.xyChart.axisTitlesSettings.help', {
defaultMessage: 'Show x and y axes titles',
}),
},
layers: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
types: ['lens_xy_layer'] as any,
help: 'Layers of visual series',
multi: true,
},
curveType: {
types: ['string'],
options: ['LINEAR', 'CURVE_MONOTONE_X'],
help: i18n.translate('xpack.lens.xyChart.curveType.help', {
defaultMessage: 'Define how curve type is rendered for a line chart',
}),
},
hideEndzones: {
types: ['boolean'],
default: false,
help: i18n.translate('xpack.lens.xyChart.hideEndzones.help', {
defaultMessage: 'Hide endzone markers for partial data',
}),
},
},
fn(data: LensMultiTable, args: XYArgs) {
return {
type: 'render',
as: 'lens_xy_chart_renderer',
value: {
data,
args,
},
};
},
};
export async function calculateMinInterval({ args: { layers }, data }: XYChartProps) {
const filteredLayers = getFilteredLayers(layers, data);
if (filteredLayers.length === 0) return;
const isTimeViz = data.dateRange && filteredLayers.every((l) => l.xScaleType === 'time');
const xColumn = data.tables[filteredLayers[0].layerId].columns.find(
(column) => column.id === filteredLayers[0].xAccessor
);
if (!xColumn) return;
if (!isTimeViz) {
const histogramInterval = search.aggs.getNumberHistogramIntervalByDatatableColumn(xColumn);
if (typeof histogramInterval === 'number') {
return histogramInterval;
} else {
return undefined;
}
}
const dateInterval = search.aggs.getDateHistogramMetaDataByDatatableColumn(xColumn)?.interval;
if (!dateInterval) return;
const intervalDuration = search.aggs.parseInterval(dateInterval);
if (!intervalDuration) return;
return intervalDuration.as('milliseconds');
}
export const getXyChartRenderer = (dependencies: {
formatFactory: Promise<FormatFactory>;
chartsThemeService: ChartsPluginSetup['theme'];
paletteService: PaletteRegistry;
timeZone: string;
}): ExpressionRenderDefinition<XYChartProps> => ({
name: 'lens_xy_chart_renderer',
displayName: 'XY chart',
help: i18n.translate('xpack.lens.xyChart.renderer.help', {
defaultMessage: 'X/Y chart renderer',
}),
validate: () => undefined,
reuseDomNode: true,
render: async (
domNode: Element,
config: XYChartProps,
handlers: ILensInterpreterRenderHandlers
) => {
handlers.onDestroy(() => ReactDOM.unmountComponentAtNode(domNode));
const onClickValue = (data: LensFilterEvent['data']) => {
handlers.event({ name: 'filter', data });
};
const onSelectRange = (data: LensBrushEvent['data']) => {
handlers.event({ name: 'brush', data });
};
const formatFactory = await dependencies.formatFactory;
ReactDOM.render(
<I18nProvider>
<XYChartReportable
{...config}
formatFactory={formatFactory}
chartsThemeService={dependencies.chartsThemeService}
paletteService={dependencies.paletteService}
timeZone={dependencies.timeZone}
minInterval={await calculateMinInterval(config)}
onClickValue={onClickValue}
onSelectRange={onSelectRange}
renderMode={handlers.getRenderMode()}
syncColors={handlers.isSyncColorsEnabled()}
/>
</I18nProvider>,
domNode,
() => handlers.done()
);
},
});
function getValueLabelsStyling(isHorizontal: boolean) {
const VALUE_LABELS_MAX_FONTSIZE = 15;
const VALUE_LABELS_MIN_FONTSIZE = 10;
const VALUE_LABELS_VERTICAL_OFFSET = -10;
const VALUE_LABELS_HORIZONTAL_OFFSET = 10;
return {
displayValue: {
fontSize: { min: VALUE_LABELS_MIN_FONTSIZE, max: VALUE_LABELS_MAX_FONTSIZE },
fill: { textInverted: true, textBorder: 2 },
alignment: isHorizontal
? {
vertical: VerticalAlignment.Middle,
}
: { horizontal: HorizontalAlignment.Center },
offsetX: isHorizontal ? VALUE_LABELS_HORIZONTAL_OFFSET : 0,
offsetY: isHorizontal ? 0 : VALUE_LABELS_VERTICAL_OFFSET,
},
};
}
function getIconForSeriesType(seriesType: SeriesType): IconType {
return visualizationTypes.find((c) => c.id === seriesType)!.icon || 'empty';
}
const MemoizedChart = React.memo(XYChart);
export function XYChartReportable(props: XYChartRenderProps) {
const [state, setState] = useState({
isReady: false,
});
// It takes a cycle for the XY chart to render. This prevents
// reporting from printing a blank chart placeholder.
useEffect(() => {
setState({ isReady: true });
}, [setState]);
return (
<VisualizationContainer
className="lnsXyExpression__container"
isReady={state.isReady}
reportTitle={props.args.title}
reportDescription={props.args.description}
>
<MemoizedChart {...props} />
</VisualizationContainer>
);
}
export function XYChart({
data,
args,
formatFactory,
timeZone,
chartsThemeService,
paletteService,
minInterval,
onClickValue,
onSelectRange,
renderMode,
syncColors,
}: XYChartRenderProps) {
const {
legend,
layers,
fittingFunction,
gridlinesVisibilitySettings,
valueLabels,
hideEndzones,
} = args;
const chartTheme = chartsThemeService.useChartsTheme();
const chartBaseTheme = chartsThemeService.useChartsBaseTheme();
const darkMode = chartsThemeService.useDarkMode();
const filteredLayers = getFilteredLayers(layers, data);
if (filteredLayers.length === 0) {
const icon: IconType = layers.length > 0 ? getIconForSeriesType(layers[0].seriesType) : 'bar';
return <EmptyPlaceholder icon={icon} />;
}
// use formatting hint of first x axis column to format ticks
const xAxisColumn = data.tables[filteredLayers[0].layerId].columns.find(
({ id }) => id === filteredLayers[0].xAccessor
);
const xAxisFormatter = formatFactory(xAxisColumn && xAxisColumn.meta?.params);
const layersAlreadyFormatted: Record<string, boolean> = {};
// This is a safe formatter for the xAccessor that abstracts the knowledge of already formatted layers
const safeXAccessorLabelRenderer = (value: unknown): string =>
xAxisColumn && layersAlreadyFormatted[xAxisColumn.id]
? (value as string)
: xAxisFormatter.convert(value);
const chartHasMoreThanOneSeries =
filteredLayers.length > 1 ||
filteredLayers.some((layer) => layer.accessors.length > 1) ||
filteredLayers.some((layer) => layer.splitAccessor);
const shouldRotate = isHorizontalChart(filteredLayers);
const yAxesConfiguration = getAxesConfiguration(
filteredLayers,
shouldRotate,
data.tables,
formatFactory
);
const xTitle = args.xTitle || (xAxisColumn && xAxisColumn.name);
const axisTitlesVisibilitySettings = args.axisTitlesVisibilitySettings || {
x: true,
yLeft: true,
yRight: true,
};
const tickLabelsVisibilitySettings = args.tickLabelsVisibilitySettings || {
x: true,
yLeft: true,
yRight: true,
};
const filteredBarLayers = filteredLayers.filter((layer) => layer.seriesType.includes('bar'));
const chartHasMoreThanOneBarSeries =
filteredBarLayers.length > 1 ||
filteredBarLayers.some((layer) => layer.accessors.length > 1) ||
filteredBarLayers.some((layer) => layer.splitAccessor);
const isTimeViz = data.dateRange && filteredLayers.every((l) => l.xScaleType === 'time');
const isHistogramViz = filteredLayers.every((l) => l.isHistogram);
const { baseDomain: rawXDomain, extendedDomain: xDomain } = getXDomain(
layers,
data,
minInterval,
Boolean(isTimeViz),
Boolean(isHistogramViz)
);
const getYAxesTitles = (
axisSeries: Array<{ layer: string; accessor: string }>,
groupId: string
) => {
const yTitle = groupId === 'right' ? args.yRightTitle : args.yTitle;
return (
yTitle ||
axisSeries
.map(
(series) =>
data.tables[series.layer].columns.find((column) => column.id === series.accessor)?.name
)
.filter((name) => Boolean(name))[0]
);
};
const getYAxesStyle = (groupId: string) => {
const style = {
tickLabel: {
visible:
groupId === 'right'
? tickLabelsVisibilitySettings?.yRight
: tickLabelsVisibilitySettings?.yLeft,
},
axisTitle: {
visible:
groupId === 'right'
? axisTitlesVisibilitySettings?.yRight
: axisTitlesVisibilitySettings?.yLeft,
},
};
return style;
};
const shouldShowValueLabels =
// No stacked bar charts
filteredLayers.every((layer) => !layer.seriesType.includes('stacked')) &&
// No histogram charts
!isHistogramViz;
const valueLabelsStyling =
shouldShowValueLabels && valueLabels !== 'hide' && getValueLabelsStyling(shouldRotate);
const colorAssignments = getColorAssignments(args.layers, data, formatFactory);
const clickHandler: ElementClickListener = ([[geometry, series]]) => {
// for xyChart series is always XYChartSeriesIdentifier and geometry is always type of GeometryValue
const xySeries = series as XYChartSeriesIdentifier;
const xyGeometry = geometry as GeometryValue;
const layer = filteredLayers.find((l) =>
xySeries.seriesKeys.some((key: string | number) => l.accessors.includes(key.toString()))
);
if (!layer) {
return;
}
const table = data.tables[layer.layerId];
const xColumn = table.columns.find((col) => col.id === layer.xAccessor);
const currentXFormatter =
layer.xAccessor && layersAlreadyFormatted[layer.xAccessor] && xColumn
? formatFactory(xColumn.meta.params)
: xAxisFormatter;
const rowIndex = table.rows.findIndex((row) => {
if (layer.xAccessor) {
if (layersAlreadyFormatted[layer.xAccessor]) {
// stringify the value to compare with the chart value
return currentXFormatter.convert(row[layer.xAccessor]) === xyGeometry.x;
}
return row[layer.xAccessor] === xyGeometry.x;
}
});
const points = [
{
row: rowIndex,
column: table.columns.findIndex((col) => col.id === layer.xAccessor),
value: layer.xAccessor ? table.rows[rowIndex][layer.xAccessor] : xyGeometry.x,
},
];
if (xySeries.seriesKeys.length > 1) {
const pointValue = xySeries.seriesKeys[0];
points.push({
row: table.rows.findIndex(
(row) => layer.splitAccessor && row[layer.splitAccessor] === pointValue
),
column: table.columns.findIndex((col) => col.id === layer.splitAccessor),
value: pointValue,
});
}
const xAxisFieldName = table.columns.find((el) => el.id === layer.xAccessor)?.meta?.field;
const timeFieldName = xDomain && xAxisFieldName;
const context: LensFilterEvent['data'] = {
data: points.map((point) => ({
row: point.row,
column: point.column,
value: point.value,
table,
})),
timeFieldName,
};
onClickValue(desanitizeFilterContext(context));
};
const brushHandler: BrushEndListener = ({ x }) => {
if (!x) {
return;
}
const [min, max] = x;
if (!xAxisColumn || !isHistogramViz) {
return;
}
const table = data.tables[filteredLayers[0].layerId];
const xAxisColumnIndex = table.columns.findIndex((el) => el.id === filteredLayers[0].xAccessor);
const timeFieldName = isTimeViz ? table.columns[xAxisColumnIndex]?.meta?.field : undefined;
const context: LensBrushEvent['data'] = {
range: [min, max],
table,
column: xAxisColumnIndex,
timeFieldName,
};
onSelectRange(context);
};
return (
<Chart>
<Settings
debugState={window._echDebugStateFlag ?? false}
showLegend={
legend.isVisible && !legend.showSingleSeries
? chartHasMoreThanOneSeries
: legend.isVisible
}
legendPosition={legend.position}
showLegendExtra={false}
theme={{
...chartTheme,
barSeriesStyle: {
...chartTheme.barSeriesStyle,
...valueLabelsStyling,
},
background: {
color: undefined, // removes background for embeddables
},
}}
baseTheme={chartBaseTheme}
tooltip={{
boundary: document.getElementById('app-fixed-viewport') ?? undefined,
headerFormatter: (d) => safeXAccessorLabelRenderer(d.value),
}}
rotation={shouldRotate ? 90 : 0}
xDomain={xDomain}
onBrushEnd={renderMode !== 'noInteractivity' ? brushHandler : undefined}
onElementClick={renderMode !== 'noInteractivity' ? clickHandler : undefined}
/>
<Axis
id="x"
position={shouldRotate ? Position.Left : Position.Bottom}
title={xTitle}
gridLine={{
visible: gridlinesVisibilitySettings?.x,
strokeWidth: 2,
}}
hide={filteredLayers[0].hide || !filteredLayers[0].xAccessor}
tickFormat={(d) => safeXAccessorLabelRenderer(d)}
style={{
tickLabel: {
visible: tickLabelsVisibilitySettings?.x,
},
axisTitle: {
visible: axisTitlesVisibilitySettings.x,
},
}}
/>
{yAxesConfiguration.map((axis) => (
<Axis
key={axis.groupId}
id={axis.groupId}
groupId={axis.groupId}
position={axis.position}
title={getYAxesTitles(axis.series, axis.groupId)}
gridLine={{
visible:
axis.groupId === 'right'
? gridlinesVisibilitySettings?.yRight
: gridlinesVisibilitySettings?.yLeft,
}}
hide={filteredLayers[0].hide}
tickFormat={(d) => axis.formatter?.convert(d) || ''}
style={getYAxesStyle(axis.groupId)}
/>
))}
{!hideEndzones && (
<XyEndzones
baseDomain={rawXDomain}
extendedDomain={xDomain}
darkMode={darkMode}
histogramMode={filteredLayers.every(
(layer) =>
layer.isHistogram &&
(layer.seriesType.includes('stacked') || !layer.splitAccessor) &&
(layer.seriesType.includes('stacked') ||
!layer.seriesType.includes('bar') ||
!chartHasMoreThanOneBarSeries)
)}
/>
)}
{filteredLayers.flatMap((layer, layerIndex) =>
layer.accessors.map((accessor, accessorIndex) => {
const {
splitAccessor,
seriesType,
accessors,
xAccessor,
layerId,
columnToLabel,
yScaleType,
xScaleType,
isHistogram,
palette,
} = layer;
const columnToLabelMap: Record<string, string> = columnToLabel
? JSON.parse(columnToLabel)
: {};
const table = data.tables[layerId];
const isPrimitive = (value: unknown): boolean =>
value != null && typeof value !== 'object';
// what if row values are not primitive? That is the case of, for instance, Ranges
// remaps them to their serialized version with the formatHint metadata
// In order to do it we need to make a copy of the table as the raw one is required for more features (filters, etc...) later on
const tableConverted: Datatable = {
...table,
rows: table.rows.map((row: DatatableRow) => {
const newRow = { ...row };
for (const column of table.columns) {
const record = newRow[column.id];
if (
record &&
// pre-format values for ordinal x axes because there can only be a single x axis formatter on chart level
(!isPrimitive(record) || (column.id === xAccessor && xScaleType === 'ordinal'))
) {
newRow[column.id] = formatFactory(column.meta.params).convert(record);
}
}
return newRow;
}),
};
// save the id of the layer with the custom table
table.columns.reduce<Record<string, boolean>>(
(alreadyFormatted: Record<string, boolean>, { id }) => {
if (alreadyFormatted[id]) {
return alreadyFormatted;
}
alreadyFormatted[id] = table.rows.some(
(row, i) => row[id] !== tableConverted.rows[i][id]
);
return alreadyFormatted;
},
layersAlreadyFormatted
);
const isStacked = seriesType.includes('stacked');
const isPercentage = seriesType.includes('percentage');
const isBarChart = seriesType.includes('bar');
const enableHistogramMode =
isHistogram &&
(isStacked || !splitAccessor) &&
(isStacked || !isBarChart || !chartHasMoreThanOneBarSeries);
// For date histogram chart type, we're getting the rows that represent intervals without data.
// To not display them in the legend, they need to be filtered out.
const rows = tableConverted.rows.filter(
(row) =>
!(xAccessor && typeof row[xAccessor] === 'undefined') &&
!(
splitAccessor &&
typeof row[splitAccessor] === 'undefined' &&
typeof row[accessor] === 'undefined'
)
);
if (!xAccessor) {
rows.forEach((row) => {
row.unifiedX = i18n.translate('xpack.lens.xyChart.emptyXLabel', {
defaultMessage: '(empty)',
});
});
}
const yAxis = yAxesConfiguration.find((axisConfiguration) =>
axisConfiguration.series.find((currentSeries) => currentSeries.accessor === accessor)
);
const seriesProps: SeriesSpec = {
splitSeriesAccessors: splitAccessor ? [splitAccessor] : [],
stackAccessors: isStacked ? [xAccessor as string] : [],
id: `${splitAccessor}-${accessor}`,
xAccessor: xAccessor || 'unifiedX',
yAccessors: [accessor],
data: rows,
xScaleType: xAccessor ? xScaleType : 'ordinal',
yScaleType,
color: ({ yAccessor, seriesKeys }) => {
const overwriteColor = getSeriesColor(layer, accessor);
if (overwriteColor !== null) {
return overwriteColor;
}
const colorAssignment = colorAssignments[palette.name];
const seriesLayers: SeriesLayer[] = [
{
name: splitAccessor ? String(seriesKeys[0]) : columnToLabelMap[seriesKeys[0]],
totalSeriesAtDepth: colorAssignment.totalSeriesCount,
rankAtDepth: colorAssignment.getRank(
layer,
String(seriesKeys[0]),
String(yAccessor)
),
},
];
return paletteService.get(palette.name).getColor(
seriesLayers,
{
maxDepth: 1,
behindText: false,
totalSeries: colorAssignment.totalSeriesCount,
syncColors,
},
palette.params
);
},
groupId: yAxis?.groupId,
enableHistogramMode,
stackMode: isPercentage ? StackMode.Percentage : undefined,
timeZone,
areaSeriesStyle: {
point: {
visible: !xAccessor,
radius: 5,
},
},
lineSeriesStyle: {
point: {
visible: !xAccessor,
radius: 5,
},
},
name(d) {
const splitHint = table.columns.find((col) => col.id === splitAccessor)?.meta?.params;
// For multiple y series, the name of the operation is used on each, either:
// * Key - Y name
// * Formatted value - Y name
if (accessors.length > 1) {
const result = d.seriesKeys
.map((key: string | number, i) => {
if (
i === 0 &&
splitHint &&
splitAccessor &&
!layersAlreadyFormatted[splitAccessor]
) {
return formatFactory(splitHint).convert(key);
}
return splitAccessor && i === 0 ? key : columnToLabelMap[key] ?? '';
})
.join(' - ');
return result;
}
// For formatted split series, format the key
// This handles splitting by dates, for example
if (splitHint) {
if (splitAccessor && layersAlreadyFormatted[splitAccessor]) {
return d.seriesKeys[0];
}
return formatFactory(splitHint).convert(d.seriesKeys[0]);
}
// This handles both split and single-y cases:
// * If split series without formatting, show the value literally
// * If single Y, the seriesKey will be the accessor, so we show the human-readable name
return splitAccessor ? d.seriesKeys[0] : columnToLabelMap[d.seriesKeys[0]] ?? '';
},
};
const index = `${layerIndex}-${accessorIndex}`;
const curveType = args.curveType ? CurveType[args.curveType] : undefined;
switch (seriesType) {
case 'line':
return (
<LineSeries
key={index}
{...seriesProps}
fit={getFitOptions(fittingFunction)}
curve={curveType}
/>
);
case 'bar':
case 'bar_stacked':
case 'bar_percentage_stacked':
case 'bar_horizontal':
case 'bar_horizontal_stacked':
case 'bar_horizontal_percentage_stacked':
const valueLabelsSettings = {
displayValueSettings: {
// This format double fixes two issues in elastic-chart
// * when rotating the chart, the formatter is not correctly picked
// * in some scenarios value labels are not strings, and this breaks the elastic-chart lib
valueFormatter: (d: unknown) => yAxis?.formatter?.convert(d) || '',
showValueLabel: shouldShowValueLabels && valueLabels !== 'hide',
isAlternatingValueLabel: false,
isValueContainedInElement: true,
hideClippedValue: true,
},
};
return <BarSeries key={index} {...seriesProps} {...valueLabelsSettings} />;
case 'area_stacked':
case 'area_percentage_stacked':
return (
<AreaSeries
key={index}
{...seriesProps}
fit={isPercentage ? 'zero' : getFitOptions(fittingFunction)}
curve={curveType}
/>
);
case 'area':
return (
<AreaSeries
key={index}
{...seriesProps}
fit={getFitOptions(fittingFunction)}
curve={curveType}
/>
);
default:
return assertNever(seriesType);
}
})
)}
</Chart>
);
}
function getFilteredLayers(layers: LayerArgs[], data: LensMultiTable) {
return layers.filter(({ layerId, xAccessor, accessors, splitAccessor }) => {
return !(
!accessors.length ||
!data.tables[layerId] ||
data.tables[layerId].rows.length === 0 ||
(xAccessor &&
data.tables[layerId].rows.every((row) => typeof row[xAccessor] === 'undefined')) ||
// stacked percentage bars have no xAccessors but splitAccessor with undefined values in them when empty
(!xAccessor &&
splitAccessor &&
data.tables[layerId].rows.every((row) => typeof row[splitAccessor] === 'undefined'))
);
});
}
function assertNever(x: never): never {
throw new Error('Unexpected series type: ' + x);
}