forked from opensearch-project/OpenSearch-Dashboards
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvis_builder_embeddable.tsx
More file actions
310 lines (268 loc) · 9.14 KB
/
vis_builder_embeddable.tsx
File metadata and controls
310 lines (268 loc) · 9.14 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
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
import { cloneDeep, isEqual } from 'lodash';
import ReactDOM from 'react-dom';
import { merge, Subscription } from 'rxjs';
import { PLUGIN_ID, VisBuilderSavedObjectAttributes, VISBUILDER_SAVED_OBJECT } from '../../common';
import {
Embeddable,
EmbeddableOutput,
ErrorEmbeddable,
IContainer,
SavedObjectEmbeddableInput,
} from '../../../embeddable/public';
import {
ExpressionRenderError,
ExpressionsStart,
IExpressionLoaderParams,
} from '../../../expressions/public';
import {
Filter,
opensearchFilters,
Query,
TimefilterContract,
TimeRange,
} from '../../../data/public';
import { validateSchemaState } from '../application/utils/validate_schema_state';
import { getExpressionLoader, getTypeService } from '../plugin_services';
import { PersistedState } from '../../../visualizations/public';
import { RenderState, VisualizationState } from '../application/utils/state_management';
// Apparently this needs to match the saved object type for the clone and replace panel actions to work
export const VISBUILDER_EMBEDDABLE = VISBUILDER_SAVED_OBJECT;
export interface VisBuilderEmbeddableConfiguration {
savedVisBuilder: VisBuilderSavedObjectAttributes;
// TODO: add indexPatterns as part of configuration
// indexPatterns?: IIndexPattern[];
editPath: string;
editUrl: string;
editable: boolean;
}
export interface VisBuilderOutput extends EmbeddableOutput {
/**
* Will contain the saved object attributes of the VisBuilder Saved Object that matches
* `input.savedObjectId`. If the id is invalid, this may be undefined.
*/
savedVisBuilder?: VisBuilderSavedObjectAttributes;
}
type ExpressionLoader = InstanceType<ExpressionsStart['ExpressionLoader']>;
export class VisBuilderEmbeddable extends Embeddable<SavedObjectEmbeddableInput, VisBuilderOutput> {
public readonly type = VISBUILDER_EMBEDDABLE;
private handler?: ExpressionLoader;
private timeRange?: TimeRange;
private query?: Query;
private filters?: Filter[];
private abortController?: AbortController;
public expression: string = '';
private autoRefreshFetchSubscription: Subscription;
private subscriptions: Subscription[] = [];
private node?: HTMLElement;
private savedVisBuilder?: VisBuilderSavedObjectAttributes;
private serializedState?: { visualization: string; style: string };
private uiState?: PersistedState;
constructor(
timefilter: TimefilterContract,
{ savedVisBuilder, editPath, editUrl, editable }: VisBuilderEmbeddableConfiguration,
initialInput: SavedObjectEmbeddableInput,
{
parent,
}: {
parent?: IContainer;
}
) {
super(
initialInput,
{
defaultTitle: savedVisBuilder.title,
editPath,
editApp: PLUGIN_ID,
editUrl,
editable,
savedVisBuilder,
},
parent
);
this.savedVisBuilder = savedVisBuilder;
this.uiState = new PersistedState();
this.autoRefreshFetchSubscription = timefilter
.getAutoRefreshFetch$()
.subscribe(this.updateHandler.bind(this));
this.subscriptions.push(
merge(this.getOutput$(), this.getInput$()).subscribe(() => {
this.handleChanges();
})
);
}
private getSerializedState = () => {
const { visualizationState: visualization = '{}', styleState: style = '{}' } =
this.savedVisBuilder || {};
return {
visualization,
style,
};
};
private getExpression = async () => {
if (!this.serializedState) {
return;
}
const { visualization, style } = this.serializedState;
const vizStateWithoutIndex = JSON.parse(visualization);
const visualizationState: VisualizationState = {
searchField: vizStateWithoutIndex.searchField,
activeVisualization: vizStateWithoutIndex.activeVisualization,
indexPattern: this.savedVisBuilder?.searchSourceFields?.index,
};
const renderState: RenderState = {
visualization: visualizationState,
style: JSON.parse(style),
};
const visualizationName = renderState.visualization?.activeVisualization?.name ?? '';
const visualizationType = getTypeService().get(visualizationName);
if (!visualizationType) {
this.onContainerError(new Error(`Invalid visualization type ${visualizationName}`));
return;
}
const { toExpression, ui } = visualizationType;
const schemas = ui.containerConfig.data.schemas;
const [valid, errorMsg] = validateSchemaState(schemas, visualizationState);
if (!valid) {
if (errorMsg) {
this.onContainerError(new Error(errorMsg));
return;
}
} else {
// TODO: handle error in Expression creation
const exp = await toExpression(renderState, {
filters: this.filters,
query: this.query,
timeRange: this.timeRange,
});
return exp;
}
};
// Needed to enable inspection panel option
public getInspectorAdapters = () => {
if (!this.handler) {
return undefined;
}
return this.handler.inspect();
};
// Needed to add informational tooltip
public getDescription() {
return this.savedVisBuilder?.description;
}
public render(node: HTMLElement) {
if (this.output.error) {
// TODO: Can we find a more elegant way to throw, propagate, and render errors?
const errorEmbeddable = new ErrorEmbeddable(
this.output.error as Error,
this.input,
this.parent
);
return errorEmbeddable.render(node);
}
this.timeRange = cloneDeep(this.input.timeRange);
const div = document.createElement('div');
div.className = `visBuilder visualize panel-content panel-content--fullWidth`;
node.appendChild(div);
this.node = div;
super.render(this.node);
// TODO: Investigate migrating to using `./wizard_component` for React rendering instead
const ExpressionLoader = getExpressionLoader();
this.handler = new ExpressionLoader(this.node, undefined, {
onRenderError: (_element: HTMLElement, error: ExpressionRenderError) => {
this.onContainerError(error);
},
});
if (this.savedVisBuilder?.description) {
div.setAttribute('data-description', this.savedVisBuilder.description);
}
div.setAttribute('data-test-subj', 'visBuilderLoader');
this.subscriptions.push(this.handler.loading$.subscribe(this.onContainerLoading));
this.subscriptions.push(this.handler.render$.subscribe(this.onContainerRender));
this.updateHandler();
}
public async reload() {
this.updateHandler();
}
public destroy() {
super.destroy();
this.subscriptions.forEach((s) => s.unsubscribe());
if (this.node) {
ReactDOM.unmountComponentAtNode(this.node);
}
if (this.handler) {
this.handler.destroy();
this.handler.getElement().remove();
}
this.autoRefreshFetchSubscription.unsubscribe();
}
private async updateHandler() {
const expressionParams: IExpressionLoaderParams = {
searchContext: {
timeRange: this.timeRange,
query: this.input.query,
filters: this.input.filters,
},
uiState: this.uiState,
};
if (this.abortController) {
this.abortController.abort();
}
this.abortController = new AbortController();
const abortController = this.abortController;
if (this.handler && !abortController.signal.aborted) {
this.handler.update(this.expression, expressionParams);
}
}
public async handleChanges() {
// TODO: refactor (here and in visualize) to remove lodash dependency - immer probably a better choice
let dirty = false;
// Check if timerange has changed
if (!isEqual(this.input.timeRange, this.timeRange)) {
this.timeRange = cloneDeep(this.input.timeRange);
dirty = true;
}
// Check if filters has changed
if (!opensearchFilters.onlyDisabledFiltersChanged(this.input.filters, this.filters)) {
this.filters = this.input.filters;
dirty = true;
}
// Check if query has changed
if (!isEqual(this.input.query, this.query)) {
this.query = this.input.query;
dirty = true;
}
// Check if rootState has changed
if (!isEqual(this.getSerializedState(), this.serializedState)) {
this.serializedState = this.getSerializedState();
dirty = true;
}
if (dirty) {
this.expression = (await this.getExpression()) ?? '';
if (this.handler) {
this.updateHandler();
}
}
}
onContainerLoading = () => {
this.renderComplete.dispatchInProgress();
this.updateOutput({ loading: true, error: undefined });
};
onContainerRender = () => {
this.renderComplete.dispatchComplete();
this.updateOutput({ loading: false, error: undefined });
};
onContainerError = (error: ExpressionRenderError) => {
if (this.abortController) {
this.abortController.abort();
}
this.renderComplete.dispatchError();
this.updateOutput({ loading: false, error });
};
// TODO: we may eventually need to add support for visualizations that use triggers like filter or brush, but current VisBuilder vis types don't support triggers
// public supportedTriggers(): TriggerId[] {
// return this.visType.getSupportedTriggers?.() ?? [];
// }
}