Skip to content

Commit

Permalink
adding toAST function
Browse files Browse the repository at this point in the history
  • Loading branch information
ppisljar committed Aug 19, 2020
1 parent 3bef8d1 commit b22e91a
Show file tree
Hide file tree
Showing 15 changed files with 319 additions and 137 deletions.
17 changes: 17 additions & 0 deletions src/plugins/expressions/common/ast/build_function.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ describe('buildExpressionFunction()', () => {
`);
});

test('ignores any args in initial state which value is undefined', () => {
const fn = buildExpressionFunction('hello', { world: undefined });
expect(fn.arguments).not.toHaveProperty('world');
});

test('returns all expected properties', () => {
const fn = buildExpressionFunction('hello', { world: [true] });
expect(Object.keys(fn)).toMatchInlineSnapshot(`
Expand Down Expand Up @@ -264,6 +269,18 @@ describe('buildExpressionFunction()', () => {
`);
});

test('does not add new argument if the value is undefined', () => {
const fn = buildExpressionFunction('hello', { world: [true] });
fn.addArgument('foo', undefined);
expect(fn.toAst().arguments).toMatchInlineSnapshot(`
Object {
"world": Array [
true,
],
}
`);
});

test('mutates a function already associated with an expression', () => {
const fn = buildExpressionFunction('hello', { world: [true] });
const exp = buildExpression([fn]);
Expand Down
12 changes: 8 additions & 4 deletions src/plugins/expressions/common/ast/build_function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,10 @@ export function buildExpressionFunction<
acc[key] = value.map((v) => {
return isExpressionAst(v) ? buildExpression(v) : v;
});
} else {
} else if (value !== undefined) {
acc[key] = isExpressionAst(value) ? [buildExpression(value)] : [value];
} else {
delete acc[key];
}
return acc;
}, initialArgs as FunctionBuilderArguments<FnDef>);
Expand All @@ -195,10 +197,12 @@ export function buildExpressionFunction<
arguments: args,

addArgument(key, value) {
if (!args.hasOwnProperty(key)) {
args[key] = [];
if (value !== undefined) {
if (!args.hasOwnProperty(key)) {
args[key] = [];
}
args[key].push(value);
}
args[key].push(value);
return this;
},

Expand Down
2 changes: 1 addition & 1 deletion src/plugins/vis_type_metric/kibana.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
"kibanaVersion": "kibana",
"server": true,
"ui": true,
"requiredPlugins": ["data", "visualizations", "charts","expressions"],
"requiredPlugins": ["data", "visualizations", "charts", "expressions"],
"requiredBundles": ["kibanaUtils", "kibanaReact"]
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions src/plugins/vis_type_metric/public/metric_vis_fn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,14 @@ interface RenderValue {
params: any;
}

export const createMetricVisFn = (): ExpressionFunctionDefinition<
export type MetricVisExpressionFunctionDefinition = ExpressionFunctionDefinition<
'metricVis',
Input,
Arguments,
Render<RenderValue>
> => ({
>;

export const createMetricVisFn = (): MetricVisExpressionFunctionDefinition => ({
name: 'metricVis',
type: 'render',
inputTypes: ['kibana_datatable'],
Expand Down
3 changes: 2 additions & 1 deletion src/plugins/vis_type_metric/public/metric_vis_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@
*/

import { i18n } from '@kbn/i18n';

import { MetricVisOptions } from './components/metric_vis_options';
import { ColorSchemas, colorSchemas, ColorModes } from '../../charts/public';
import { AggGroupNames } from '../../data/public';
import { Schemas } from '../../vis_default_editor/public';
import { toExpressionAst } from './to_ast';

export const createMetricVisTypeDefinition = () => ({
name: 'metric',
Expand All @@ -31,6 +31,7 @@ export const createMetricVisTypeDefinition = () => ({
description: i18n.translate('visTypeMetric.metricDescription', {
defaultMessage: 'Display a calculation as a single number',
}),
toExpressionAst,
visConfig: {
defaults: {
addTooltip: true,
Expand Down
54 changes: 54 additions & 0 deletions src/plugins/vis_type_metric/public/to_ast.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { toExpressionAst } from './to_ast';
import { Vis } from '../../visualizations/public';

describe('metric vis toExpressionAst function', () => {
let vis: Vis;

beforeEach(() => {
vis = {
isHierarchical: () => false,
type: {},
params: {
percentageMode: false,
},
data: {
indexPattern: { id: '123' } as any,
aggs: {
getResponseAggs: () => [],
aggs: [],
} as any,
},
} as any;
});

it('without params', () => {
vis.params = { metric: {} };
const actual = toExpressionAst(vis, {});
expect(actual).toMatchSnapshot();
});

it('with percentage mode should have percentage format', () => {
vis.params = { metric: { percentageMode: true } };
const actual = toExpressionAst(vis, {});
expect(actual).toMatchSnapshot();
});
});
103 changes: 103 additions & 0 deletions src/plugins/vis_type_metric/public/to_ast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { get } from 'lodash';
import { getVisSchemas, SchemaConfig, Vis } from '../../visualizations/public';
import { buildExpression, buildExpressionFunction } from '../../expressions/public';
import { MetricVisExpressionFunctionDefinition } from './metric_vis_fn';
import { EsaggsExpressionFunctionDefinition } from '../../data/common/search/expressions';

const prepareDimension = (params: SchemaConfig) => {
const visdimension = buildExpressionFunction('visdimension', { accessor: params.accessor });

if (params.format) {
visdimension.addArgument('format', params.format.id);
visdimension.addArgument('formatParams', JSON.stringify(params.format.params));
}

return buildExpression([visdimension]);
};

export const toExpressionAst = (vis: Vis, params: any) => {
// soon this becomes: const esaggs = vis.data.aggs!.toExpressionAst();
const esaggs = buildExpressionFunction<EsaggsExpressionFunctionDefinition>('esaggs', {
index: vis.data.indexPattern!.id!,
metricsAtAllLevels: vis.isHierarchical(),
partialRows: vis.type.requiresPartialRows || vis.params.showPartialRows || false,
aggConfigs: JSON.stringify(vis.data.aggs!.aggs),
includeFormatHints: false,
});

const schemas = getVisSchemas(vis, params);

const {
percentageMode,
useRanges,
colorSchema,
metricColorMode,
colorsRange,
labels,
invertColors,
style,
} = vis.params.metric;

// fix formatter for percentage mode
if (get(vis.params, 'metric.percentageMode') === true) {
schemas.metric.forEach((metric: SchemaConfig) => {
metric.format = { id: 'percent' };
});
}

// @ts-ignore
const metricVis = buildExpressionFunction<MetricVisExpressionFunctionDefinition>('metricVis', {
percentageMode,
colorSchema,
colorMode: metricColorMode,
useRanges,
invertColors,
showLabels: labels && labels.show,
});

if (style) {
metricVis.addArgument('bgFill', style.bgFill);
metricVis.addArgument('font', buildExpression(`font size=${style.fontSize}`));
metricVis.addArgument('subText', style.subText);
}

if (colorsRange) {
colorsRange.forEach((range: any) => {
metricVis.addArgument(
'colorRange',
buildExpression(`range from=${range.from} to=${range.to}`)
);
});
}

if (schemas.group) {
metricVis.addArgument('bucket', prepareDimension(schemas.group[0]));
}

schemas.metric.forEach((metric) => {
metricVis.addArgument('metric', prepareDimension(metric));
});

const ast = buildExpression([esaggs, metricVis]);

return ast.toAst();
};
1 change: 1 addition & 0 deletions src/plugins/visualizations/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export { Vis } from './vis';
export { TypesService } from './vis_types/types_service';
export { VISUALIZE_EMBEDDABLE_TYPE, VIS_EVENT_TO_TRIGGER } from './embeddable';
export { VisualizationContainer, VisualizationNoResults } from './components';
export { getSchemas as getVisSchemas } from './legacy/build_pipeline';

/** @public types */
export { VisualizationsSetup, VisualizationsStart };
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit b22e91a

Please sign in to comment.