forked from elastic/kibana
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelements.js
More file actions
446 lines (380 loc) · 15.9 KB
/
elements.js
File metadata and controls
446 lines (380 loc) · 15.9 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
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
/*
* 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 { createAction } from 'redux-actions';
import { set, del } from 'object-path-immutable';
import { get, pick, cloneDeep, without, last } from 'lodash';
import { toExpression, safeElementFromExpression } from '@kbn/interpreter';
import { createThunk } from '../../lib/create_thunk';
import { isGroupId } from '../../lib/workpad';
import {
getPages,
getWorkpadVariablesAsObject,
getNodeById,
getNodes,
getSelectedPageIndex,
getElementById,
} from '../selectors/workpad';
import { getValue as getResolvedArgsValue } from '../selectors/resolved_args';
import { getDefaultElement } from '../defaults';
import { ErrorStrings } from '../../../i18n';
import { subMultitree } from '../../lib/aeroelastic/functional';
import { getCanvasExpressionService } from '../../services/canvas_expressions_service';
import { getCanvasNotifyService } from '../../services/canvas_notify_service';
import { selectToplevelNodes } from './transient';
import * as args from './resolved_args';
import { setFilter } from './filters';
const { actionsElements: strings } = ErrorStrings;
export function getSiblingContext(state, elementId, checkIndex, path = ['ast.chain']) {
const prevContextPath = [elementId, 'expressionContext', ...path, checkIndex];
const prevContextValue = getResolvedArgsValue(state, prevContextPath);
// if a value is found, return it, along with the index it was found at
if (prevContextValue != null) {
return {
index: checkIndex,
context: prevContextValue,
};
}
// check previous index while we're still above 0
const prevContextIndex = checkIndex - 1;
if (prevContextIndex < 0) {
return {};
}
// walk back up to find the closest cached context available
return getSiblingContext(state, elementId, prevContextIndex, path);
}
function getBareElement(el, includeId = false) {
const props = ['position', 'expression', 'filter'];
if (includeId) {
return pick(el, props.concat('id'));
}
return cloneDeep(pick(el, props));
}
export const elementLayer = createAction('elementLayer');
export const setMultiplePositions = createAction(
'setMultiplePositions',
(repositionedElements) => ({
repositionedElements,
})
);
export const flushContext = createAction('flushContext');
export const flushContextAfterIndex = createAction('flushContextAfterIndex');
const fetchContextFn = ({ dispatch, getState }, index, element, fullRefresh = false, path) => {
const pathToTarget = [...path.split('.'), 'chain'];
const chain = get(element, pathToTarget);
const invalidIndex = chain ? index >= chain.length : true;
if (!element || !chain || invalidIndex) {
throw new Error(strings.getInvalidArgIndexErrorMessage(index));
}
// cache context as the previous index
const contextIndex = index - 1;
const contextPath = [element.id, 'expressionContext', path, contextIndex];
// set context state to loading
dispatch(args.setLoading({ path: contextPath }));
// function to walk back up to find the closest context available
const getContext = () => getSiblingContext(getState(), element.id, contextIndex - 1, [path]);
const { index: prevContextIndex, context: prevContextValue } =
fullRefresh !== true ? getContext() : {};
// modify the ast chain passed to the interpreter
const astChain = chain.filter((exp, i) => {
if (prevContextValue != null) {
return i > prevContextIndex && i < index;
}
return i < index;
});
const variables = getWorkpadVariablesAsObject(getState());
const expressions = getCanvasExpressionService();
const elementWithNewAst = set(element, pathToTarget, astChain);
// get context data from a partial AST
return expressions
.interpretAst(elementWithNewAst.ast, variables, prevContextValue)
.then((value) => {
dispatch(args.setValue({ path: contextPath, value }));
});
};
export const fetchContext = createThunk('fetchContext', fetchContextFn);
const fetchRenderableWithContextFn = ({ dispatch, getState }, element, ast, context) => {
const argumentPath = [element.id, 'expressionRenderable'];
dispatch(
args.setLoading({
path: argumentPath,
})
);
const getAction = (renderable) =>
args.setValue({
path: argumentPath,
value: renderable,
});
const variables = getWorkpadVariablesAsObject(getState());
const expressions = getCanvasExpressionService();
const notify = getCanvasNotifyService();
return expressions
.runInterpreter(ast, context, variables, { castToRender: true })
.then((renderable) => {
dispatch(getAction(renderable));
})
.catch((err) => {
notify.error(err);
dispatch(getAction(err));
});
};
export const fetchRenderableWithContext = createThunk(
'fetchRenderableWithContext',
fetchRenderableWithContextFn
);
export const fetchRenderable = createThunk('fetchRenderable', ({ dispatch }, element) => {
const ast = element.ast || safeElementFromExpression(element.expression);
dispatch(fetchRenderableWithContext(element, ast, null));
});
export const fetchAllRenderables = createThunk(
'fetchAllRenderables',
({ dispatch, getState }, { onlyActivePage = false } = {}) => {
const workpadPages = getPages(getState());
const currentPageIndex = getSelectedPageIndex(getState());
const currentPage = workpadPages[currentPageIndex];
const otherPages = without(workpadPages, currentPage);
dispatch(args.inFlightActive());
function fetchElementsOnPages(pages) {
const elements = [];
pages.forEach((page) => {
page.elements.forEach((element) => {
elements.push(element);
});
});
const renderablePromises = elements.map((element) => {
const ast = element.ast || safeElementFromExpression(element.expression);
const argumentPath = [element.id, 'expressionRenderable'];
const variables = getWorkpadVariablesAsObject(getState());
const expressions = getCanvasExpressionService();
const notify = getCanvasNotifyService();
return expressions
.runInterpreter(ast, null, variables, { castToRender: true })
.then((renderable) => ({ path: argumentPath, value: renderable }))
.catch((err) => {
notify.error(err);
return { path: argumentPath, value: err };
});
});
return Promise.all(renderablePromises).then((renderables) => {
dispatch(args.setValues(renderables));
});
}
if (onlyActivePage) {
fetchElementsOnPages([currentPage]).then(() => dispatch(args.inFlightComplete()));
} else {
fetchElementsOnPages([currentPage])
.then(() => {
return otherPages.reduce((chain, page) => {
return chain.then(() => fetchElementsOnPages([page]));
}, Promise.resolve());
})
.then(() => dispatch(args.inFlightComplete()));
}
}
);
export const insertNodes = createThunk('insertNodes', ({ dispatch, type }, elements, pageId) => {
const _insertNodes = createAction(type);
const newElements = elements.map(cloneDeep);
// move the root element so users can see that it was added
newElements.forEach((newElement) => {
newElement.position.top = newElement.position.top + 10;
newElement.position.left = newElement.position.left + 10;
});
dispatch(_insertNodes({ pageId, elements: newElements }));
// refresh all elements just once per `insertNodes call` if there's a filter on any, otherwise just render the new element
if (elements.some((element) => element.filter)) {
dispatch(fetchAllRenderables());
} else {
newElements.forEach((newElement) => dispatch(fetchRenderable(newElement)));
}
});
export const removeElements = createThunk(
'removeElements',
({ dispatch, getState }, rootElementIds, pageId) => {
const state = getState();
// todo consider doing the group membership collation in aeroelastic, or the Redux reducer, when adding templates
const allElements = getNodes(state, pageId);
const allRoots = rootElementIds
.map((id) => allElements.find((e) => id === e.id))
.filter((d) => d);
const elementIds = subMultitree(
(e) => e.id,
(e) => e.position.parent,
allElements,
allRoots
).map((e) => e.id);
const shouldRefresh = elementIds.some((elementId) => {
const element = getNodeById(state, elementId, pageId);
const filterIsApplied = element.filter && element.filter.length > 0;
return filterIsApplied;
});
const _removeElements = createAction('removeElements', (elementIds, pageId) => ({
elementIds,
pageId,
}));
dispatch(_removeElements(elementIds, pageId));
if (shouldRefresh) {
dispatch(fetchAllRenderables());
}
}
);
export const setExpression = createThunk('setExpression', setExpressionFn);
function setExpressionFn({ dispatch, getState }, expression, elementId, pageId, doRender = true) {
// dispatch action to update the element in state
const _setExpression = createAction('setExpression');
dispatch(_setExpression({ expression, elementId, pageId }));
// read updated element from state and fetch renderable
const updatedElement = getNodeById(getState(), elementId, pageId);
// reset element.filter if element is no longer a filter
// TODO: find a way to extract a list of filter renderers from the functions registry
if (
updatedElement.filter &&
!['dropdownControl', 'timefilterControl', 'exactly'].some((filter) =>
updatedElement.expression.includes(filter)
)
) {
const filter = '';
dispatch(setFilter(filter, elementId, pageId));
if (doRender) {
dispatch(fetchAllRenderables(updatedElement));
}
// setFilter will trigger a re-render so we can skip the fetch here
} else if (doRender === true) {
dispatch(fetchRenderable(updatedElement));
}
}
const setAst = createThunk('setAst', ({ dispatch }, ast, element, pageId, doRender = true) => {
try {
const expression = toExpression(ast);
dispatch(setExpression(expression, element.id, pageId, doRender));
} catch (err) {
const notifyService = getCanvasNotifyService();
notifyService.error(err);
// TODO: remove this, may have been added just to cause a re-render, but why?
dispatch(setExpression(element.expression, element.id, pageId, doRender));
}
});
// index here is the top-level argument in the expression. for example in the expression
// demodata().pointseries().plot(), demodata is 0, pointseries is 1, and plot is 2
export const setAstAtIndex = createThunk(
'setAstAtIndex',
({ dispatch, getState }, index, ast, element, pageId) => {
// invalidate cached context for elements after this index
dispatch(flushContextAfterIndex({ elementId: element.id, index }));
const newElement = set(element, `ast.chain.${index}`, ast);
const newAst = get(newElement, 'ast');
// fetch renderable using existing context, if available (value is null if not cached)
const { index: contextIndex, context: contextValue } = getSiblingContext(
getState(),
element.id,
index - 1
);
// if we have a cached context, update the expression, but use cache when updating the renderable
if (contextValue) {
// set the expression, but skip the fetchRenderable step
dispatch(setAst(newAst, element, pageId, false));
// use context when updating the expression, it will be passed to the intepreter
const partialAst = {
...newAst,
chain: newAst.chain.filter((exp, i) => {
if (contextValue) {
return i > contextIndex;
}
return i >= index;
}),
};
return dispatch(fetchRenderableWithContext(newElement, partialAst, contextValue));
}
// if no cached context, update the ast like normal
dispatch(setAst(newAst, element, pageId));
}
);
/**
* Updating the value of the given argument of the element's expression.
* @param {string} args.path - the path to the argument at the AST. Example: "ast.chain.0.arguments.some_arg.chain.1.arguments".
* @param {string} args.argName - the argument name at the AST.
* @param {number} args.valueIndex - the index of the value in the array of argument's values.
* @param {any} args.value - the value to be set to the AST.
* @param {any} args.element - the element, which contains the expression.
* @param {any} args.pageId - the workpad's page, where element is located.
*/
export const setArgument = createThunk('setArgument', ({ dispatch, getState }, args) => {
const { argName, value, valueIndex, elementId, pageId, path } = args;
let selector = `${path}.${argName}`;
if (valueIndex != null) {
selector += '.' + valueIndex;
}
const element = getElementById(getState(), elementId);
const newElement = set(element, selector, value);
const pathTerms = path.split('.');
const argumentChainPath = pathTerms.slice(0, 3);
const argumnentChainIndex = last(argumentChainPath);
const newAst = get(newElement, argumentChainPath);
dispatch(setAstAtIndex(argumnentChainIndex, newAst, element, pageId));
});
/**
* Adding the value to the given argument of the element's expression.
* @param {string} args.path - the path to the argument at the AST. Example: "ast.chain.0.arguments.some_arg.chain.1.arguments".
* @param {string} args.argName - the argument name at the given path of the AST.
* @param {any} args.value - the value to be added to the array of argument's values at the AST.
* @param {any} args.element - the element, which contains the expression.
* @param {any} args.pageId - the workpad's page, where element is located.
*/
export const addArgumentValue = createThunk('addArgumentValue', ({ dispatch, getState }, args) => {
const { argName, value, elementId, path } = args;
const element = getElementById(getState(), elementId);
const values = get(element, [...path.split('.'), argName], []);
const newValue = values.concat(value);
dispatch(
setArgument({
...args,
elementId,
value: newValue,
})
);
});
export const deleteArgumentAtIndex = createThunk('deleteArgumentAtIndex', ({ dispatch }, args) => {
const { element, pageId, argName, argIndex, path } = args;
const pathTerms = path.split('.');
const argumentChainPath = pathTerms.slice(0, 3);
const argumnentChainIndex = last(argumentChainPath);
const curVal = get(element, [...pathTerms, argName]);
let newElement =
argIndex != null && curVal.length > 1
? // if more than one val, remove the specified val
del(element, `${path}.${argName}.${argIndex}`)
: // otherwise, remove the entire key
del(element, argName ? `${path}.${argName}` : path);
const parentPath = pathTerms.slice(0, pathTerms.length - 1);
const updatedArgument = get(newElement, parentPath);
if (Array.isArray(updatedArgument) && !updatedArgument.length) {
newElement = del(element, parentPath);
}
dispatch(setAstAtIndex(argumnentChainIndex, get(newElement, argumentChainPath), element, pageId));
});
/*
payload: element defaults. Eg {expression: 'foo'}
*/
export const addElement = createThunk('addElement', ({ dispatch }, pageId, element) => {
const newElement = { ...getDefaultElement(), ...getBareElement(element, true) };
if (element.width) {
newElement.position.width = element.width;
}
if (element.height) {
newElement.position.height = element.height;
}
const _addElement = createAction('addElement');
dispatch(_addElement({ pageId, element: newElement }));
// refresh all elements if there's a filter, otherwise just render the new element
if (element.filter) {
dispatch(fetchAllRenderables());
// element, which represents the group, should not be rendered. Its elements are rendered separately.
} else if (!isGroupId(newElement.id)) {
dispatch(fetchRenderable(newElement));
}
// select the new element
dispatch(selectToplevelNodes([newElement.id]));
});