-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
histogram.tsx
259 lines (237 loc) · 7.66 KB
/
histogram.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
/*
* 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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { useEuiTheme } from '@elastic/eui';
import { css } from '@emotion/react';
import React, { useState } from 'react';
import type { DataView, DataViewSpec } from '@kbn/data-views-plugin/public';
import type { DefaultInspectorAdapters, Datatable } from '@kbn/expressions-plugin/common';
import type { IKibanaSearchResponse } from '@kbn/search-types';
import type { estypes } from '@elastic/elasticsearch';
import type { TimeRange } from '@kbn/es-query';
import {
EmbeddableComponentProps,
LensEmbeddableInput,
LensEmbeddableOutput,
} from '@kbn/lens-plugin/public';
import { RequestStatus } from '@kbn/inspector-plugin/public';
import type { Observable } from 'rxjs';
import {
UnifiedHistogramBucketInterval,
UnifiedHistogramChartContext,
UnifiedHistogramFetchStatus,
UnifiedHistogramHitsContext,
UnifiedHistogramChartLoadEvent,
UnifiedHistogramRequestContext,
UnifiedHistogramServices,
UnifiedHistogramInputMessage,
UnifiedHistogramVisContext,
} from '../types';
import { buildBucketInterval } from './utils/build_bucket_interval';
import { useTimeRange } from './hooks/use_time_range';
import { useStableCallback } from '../hooks/use_stable_callback';
import { useLensProps } from './hooks/use_lens_props';
export interface HistogramProps {
abortController?: AbortController;
services: UnifiedHistogramServices;
dataView: DataView;
request?: UnifiedHistogramRequestContext;
hits?: UnifiedHistogramHitsContext;
chart: UnifiedHistogramChartContext;
isPlainRecord?: boolean;
hasLensSuggestions: boolean;
getTimeRange: () => TimeRange;
refetch$: Observable<UnifiedHistogramInputMessage>;
visContext: UnifiedHistogramVisContext;
disableTriggers?: LensEmbeddableInput['disableTriggers'];
disabledActions?: LensEmbeddableInput['disabledActions'];
onTotalHitsChange?: (status: UnifiedHistogramFetchStatus, result?: number | Error) => void;
onChartLoad?: (event: UnifiedHistogramChartLoadEvent) => void;
onFilter?: LensEmbeddableInput['onFilter'];
onBrushEnd?: LensEmbeddableInput['onBrushEnd'];
withDefaultActions: EmbeddableComponentProps['withDefaultActions'];
}
/**
* To prevent flakiness in the chart, we need to ensure that the data view config is valid.
* This requires that there are not multiple different data view ids in the given configuration.
* @param dataView
* @param visContext
* @param adHocDataViews
*/
const checkValidDataViewConfig = (
dataView: DataView,
visContext: UnifiedHistogramVisContext,
adHocDataViews: { [key: string]: DataViewSpec } | undefined
) => {
if (!dataView.id) {
return false;
}
if (!dataView.isPersisted() && !adHocDataViews?.[dataView.id]) {
return false;
}
if (dataView.id !== visContext.requestData.dataViewId) {
return false;
}
return true;
};
const computeTotalHits = (
hasLensSuggestions: boolean,
adapterTables:
| {
[key: string]: Datatable;
}
| undefined,
isPlainRecord?: boolean
) => {
if (isPlainRecord && hasLensSuggestions) {
return Object.values(adapterTables ?? {})?.[0]?.rows?.length;
} else if (isPlainRecord && !hasLensSuggestions) {
// ES|QL histogram case
const rows = Object.values(adapterTables ?? {})?.[0]?.rows;
if (!rows) {
return undefined;
}
let rowsCount = 0;
rows.forEach((r) => {
rowsCount += r.results;
});
return rowsCount;
} else {
return adapterTables?.unifiedHistogram?.meta?.statistics?.totalCount;
}
};
export function Histogram({
services: { data, lens, uiSettings },
dataView,
request,
hits,
chart: { timeInterval },
isPlainRecord,
hasLensSuggestions,
getTimeRange,
refetch$,
visContext,
disableTriggers,
disabledActions,
onTotalHitsChange,
onChartLoad,
onFilter,
onBrushEnd,
withDefaultActions,
abortController,
}: HistogramProps) {
const [bucketInterval, setBucketInterval] = useState<UnifiedHistogramBucketInterval>();
const { timeRangeText, timeRangeDisplay } = useTimeRange({
uiSettings,
bucketInterval,
timeRange: getTimeRange(),
timeInterval,
isPlainRecord,
timeField: dataView.timeFieldName,
});
const { attributes } = visContext;
const onLoad = useStableCallback(
(
isLoading: boolean,
adapters: Partial<DefaultInspectorAdapters> | undefined,
lensEmbeddableOutput$?: Observable<LensEmbeddableOutput>
) => {
const lensRequest = adapters?.requests?.getRequests()[0];
const requestFailed = lensRequest?.status === RequestStatus.ERROR;
const json = lensRequest?.response?.json as
| IKibanaSearchResponse<estypes.SearchResponse>
| undefined;
const response = json?.rawResponse;
if (requestFailed) {
onTotalHitsChange?.(UnifiedHistogramFetchStatus.error, undefined);
onChartLoad?.({ adapters: adapters ?? {} });
return;
}
const adapterTables = adapters?.tables?.tables;
const totalHits = computeTotalHits(hasLensSuggestions, adapterTables, isPlainRecord);
if (response?._shards?.failed || response?.timed_out) {
onTotalHitsChange?.(UnifiedHistogramFetchStatus.error, totalHits);
} else {
onTotalHitsChange?.(
isLoading ? UnifiedHistogramFetchStatus.loading : UnifiedHistogramFetchStatus.complete,
totalHits ?? hits?.total
);
}
if (response) {
const newBucketInterval = buildBucketInterval({
data,
dataView,
timeInterval,
timeRange: getTimeRange(),
response,
});
setBucketInterval(newBucketInterval);
}
onChartLoad?.({ adapters: adapters ?? {}, embeddableOutput$: lensEmbeddableOutput$ });
}
);
const { lensProps, requestData } = useLensProps({
request,
getTimeRange,
refetch$,
visContext,
onLoad,
});
const { euiTheme } = useEuiTheme();
const boxShadow = `0 2px 2px -1px ${euiTheme.colors.mediumShade},
0 1px 5px -2px ${euiTheme.colors.mediumShade}`;
const chartCss = css`
position: relative;
flex-grow: 1;
margin-block: ${euiTheme.size.xs};
& > div {
height: 100%;
position: absolute;
width: 100%;
}
& .lnsExpressionRenderer {
width: ${attributes.visualizationType === 'lnsMetric' ? '90%' : '100%'};
margin: auto;
box-shadow: ${attributes.visualizationType === 'lnsMetric' ? boxShadow : 'none'};
}
& .echLegend .echLegendList {
padding-right: ${euiTheme.size.s};
}
& > .euiLoadingChart {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
`;
if (!checkValidDataViewConfig(dataView, visContext, lensProps.attributes.state.adHocDataViews)) {
return <></>;
}
return (
<>
<div
data-test-subj="unifiedHistogramChart"
data-time-range={timeRangeText}
data-request-data={requestData}
data-suggestion-type={visContext.suggestionType}
css={chartCss}
>
<lens.EmbeddableComponent
{...lensProps}
abortController={abortController}
disableTriggers={disableTriggers}
disabledActions={disabledActions}
onFilter={onFilter}
onBrushEnd={onBrushEnd}
withDefaultActions={withDefaultActions}
/>
</div>
{timeRangeDisplay}
</>
);
}