-
Notifications
You must be signed in to change notification settings - Fork 8.6k
Expand file tree
/
Copy pathvis.ts
More file actions
232 lines (206 loc) · 7.62 KB
/
vis.ts
File metadata and controls
232 lines (206 loc) · 7.62 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
/*
* 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".
*/
/**
* @name Vis
*
* @description This class consists of aggs, params, listeners, title, and type.
* - Aggs: Instances of IAggConfig.
* - Params: The settings in the Options tab.
*
* Not to be confused with vislib/vis.js.
*/
import { isFunction, defaults, cloneDeep } from 'lodash';
import type { Assign } from '@kbn/utility-types';
import { i18n } from '@kbn/i18n';
import type { IAggConfigs, ISearchSource, AggConfigSerialized } from '@kbn/data-plugin/public';
import { DataView } from '@kbn/data-views-plugin/public';
import type { SavedSearch } from '@kbn/saved-search-plugin/public';
import type { VisParams } from '@kbn/visualizations-common';
import { PersistedState } from './persisted_state';
import { getTypes, getAggs, getSearch, getFieldsFormats, getSavedSearch } from './services';
import type { BaseVisType } from './vis_types';
import type { SerializedVis, SerializedVisData } from '../common/types';
export type { SerializedVis, SerializedVisData };
export interface VisData {
ast?: string;
aggs?: IAggConfigs;
indexPattern?: DataView;
searchSource?: ISearchSource;
savedSearchId?: string;
}
const getSearchSource = async (inputSearchSource: ISearchSource, savedSearchId?: string) => {
if (savedSearchId) {
let savedSearch: SavedSearch;
try {
savedSearch = await getSavedSearch().get(savedSearchId);
} catch (e) {
return inputSearchSource;
}
if (savedSearch?.searchSource) {
inputSearchSource.setParent(savedSearch.searchSource);
}
}
return inputSearchSource;
};
type PartialVisState = Assign<SerializedVis, { data: Partial<SerializedVisData> }>;
export class Vis<TVisParams extends VisParams = VisParams> {
public type: BaseVisType<TVisParams>;
public readonly id?: string;
public title: string = '';
public description: string = '';
public params: TVisParams;
public data: VisData = {};
public readonly uiState: PersistedState;
constructor(visType: BaseVisType<TVisParams>, visState: SerializedVis<TVisParams> = {} as any) {
this.type = visType;
this.params = this.getParams(visState.params);
this.uiState = new PersistedState(visState.uiState);
this.id = visState.id;
}
private getParams(params: VisParams) {
return defaults({}, cloneDeep(params ?? {}), cloneDeep(this.type.visConfig?.defaults ?? {}));
}
async setState(inState: PartialVisState) {
let state = inState;
const { updateVisTypeOnParamsChange } = this.type;
const newType = updateVisTypeOnParamsChange && updateVisTypeOnParamsChange(state.params);
if (newType) {
state = {
...inState,
type: newType,
params: { ...inState.params, type: newType },
};
}
let typeChanged = false;
if (state.type && this.type.name !== state.type) {
const newVisType = await getTypes().get<TVisParams>(state.type);
if (!newVisType) {
throw new Error(
i18n.translate('visualizations.visualizationTypeInvalidMessage', {
defaultMessage: 'Invalid visualization type "{visType}"',
values: {
visType: state.type,
},
})
);
}
this.type = newVisType;
typeChanged = true;
}
if (state.title !== undefined) {
this.title = state.title;
}
if (state.description !== undefined) {
this.description = state.description;
}
if (state.params || typeChanged) {
this.params = this.getParams(state.params);
}
try {
if (state.data && state.data.searchSource) {
this.data.searchSource = await getSearch().searchSource.create(state.data.searchSource!);
this.data.indexPattern = this.data.searchSource.getField('index');
}
} catch (e) {
// nothing to be here
}
try {
if (state.data && state.data.savedSearchId) {
if (this.data.searchSource) {
this.data.searchSource = await getSearchSource(
this.data.searchSource,
state.data.savedSearchId
);
this.data.indexPattern = this.data.searchSource.getField('index');
}
this.data.savedSearchId = state.data.savedSearchId;
}
} catch (e) {
// nothing to be here
}
if (state.data && (state.data.aggs || !this.data.aggs)) {
const aggs = state.data.aggs ? cloneDeep(state.data.aggs) : [];
const configStates = this.initializeDefaultsFromSchemas(aggs, this.type.schemas.all || []);
if (!this.data.indexPattern && aggs.length) {
const dataViewId =
typeof state.data.searchSource?.index === 'string'
? state.data.searchSource?.index
: state.data.searchSource?.index?.id;
this.data.indexPattern = new DataView({
spec: {
id: state.data.savedSearchId ?? dataViewId,
},
fieldFormats: getFieldsFormats(),
});
this.data.searchSource = await getSearch().searchSource.createEmpty();
this.data.searchSource?.setField('index', this.data.indexPattern);
}
if (this.data.indexPattern) {
this.data.aggs = getAggs().createAggConfigs(this.data.indexPattern, configStates);
}
}
}
clone(): Vis<TVisParams> {
const { data, ...restOfSerialized } = this.serialize();
const vis = new Vis<TVisParams>(this.type, restOfSerialized as any);
vis.setState({ ...restOfSerialized, data: {} });
const aggs = this.data.indexPattern
? getAggs().createAggConfigs(this.data.indexPattern, data.aggs)
: undefined;
vis.data = {
...this.data,
aggs,
};
return vis;
}
serialize(): SerializedVis {
const aggs = this.data.aggs ? this.data.aggs.aggs.map((agg) => agg.serialize()) : [];
return {
id: this.id,
title: this.title,
description: this.description,
type: this.type.name,
params: cloneDeep(this.params),
uiState: this.uiState.toJSON(),
data: {
aggs: aggs as any,
searchSource: this.data.searchSource ? this.data.searchSource.getSerializedFields() : {},
...(this.data.savedSearchId ? { savedSearchId: this.data.savedSearchId } : {}),
},
};
}
// deprecated
isHierarchical() {
if (isFunction(this.type.hierarchicalData)) {
return !!this.type.hierarchicalData(this);
} else {
return !!this.type.hierarchicalData;
}
}
private initializeDefaultsFromSchemas(configStates: AggConfigSerialized[], schemas: any) {
// Set the defaults for any schema which has them. If the defaults
// for some reason has more then the max only set the max number
// of defaults (not sure why a someone define more...
// but whatever). Also if a schema.name is already set then don't
// set anything.
const newConfigs = [...configStates];
schemas
.filter((schema: any) => Array.isArray(schema.defaults) && schema.defaults.length > 0)
.filter(
(schema: any) => !configStates.find((agg) => agg.schema && agg.schema === schema.name)
)
.forEach((schema: any) => {
const defaultSchemaConfig = schema.defaults.slice(0, schema.max);
defaultSchemaConfig.forEach((d: any) => newConfigs.push(d));
});
return newConfigs;
}
}
// eslint-disable-next-line import/no-default-export
export default Vis;