From ecefd44f052a3c5dc076f55370c05133a13dd36f Mon Sep 17 00:00:00 2001 From: nickofthyme Date: Mon, 6 Jan 2020 13:12:47 -0600 Subject: [PATCH 1/8] Add fixtures/* alias to tsconfig and jest config --- src/dev/jest/config.js | 1 + tsconfig.json | 3 ++- x-pack/dev-tools/jest/create_jest_config.js | 1 + x-pack/tsconfig.json | 3 ++- 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/dev/jest/config.js b/src/dev/jest/config.js index 9321336f0f55e..19251ffb0e566 100644 --- a/src/dev/jest/config.js +++ b/src/dev/jest/config.js @@ -58,6 +58,7 @@ export default { '^ui/(.*)': '/src/legacy/ui/public/$1', '^uiExports/(.*)': '/src/dev/jest/mocks/file_mock.js', '^test_utils/(.*)': '/src/test_utils/public/$1', + '^fixtures/(.*)': '/src/fixtures/$1', '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '/src/dev/jest/mocks/file_mock.js', '\\.(css|less|scss)$': '/src/dev/jest/mocks/style_mock.js', diff --git a/tsconfig.json b/tsconfig.json index a2da9c127e7ba..73b177fe637ee 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,7 +12,8 @@ ], "test_utils/*": [ "src/test_utils/public/*" - ] + ], + "fixtures/*": ["src/fixtures/*"] }, // Support .tsx files and transform JSX into calls to React.createElement "jsx": "react", diff --git a/x-pack/dev-tools/jest/create_jest_config.js b/x-pack/dev-tools/jest/create_jest_config.js index cd4414b5fdebe..55fc0460971df 100644 --- a/x-pack/dev-tools/jest/create_jest_config.js +++ b/x-pack/dev-tools/jest/create_jest_config.js @@ -17,6 +17,7 @@ export function createJestConfig({ kibanaDirectory, xPackKibanaDirectory }) { moduleFileExtensions: ['js', 'json', 'ts', 'tsx'], moduleNameMapper: { '^ui/(.*)': `${kibanaDirectory}/src/legacy/ui/public/$1`, + '^fixtures/(.*)': `${kibanaDirectory}/src/fixtures/$1`, 'uiExports/(.*)': fileMockPath, '^src/core/(.*)': `${kibanaDirectory}/src/core/$1`, '^src/legacy/(.*)': `${kibanaDirectory}/src/legacy/$1`, diff --git a/x-pack/tsconfig.json b/x-pack/tsconfig.json index 7070e3f5aa493..7d2933f9d9238 100644 --- a/x-pack/tsconfig.json +++ b/x-pack/tsconfig.json @@ -38,7 +38,8 @@ "monitoring/common/*": [ "x-pack/monitoring/common/*" ], - "plugins/*": ["src/legacy/core_plugins/*/public/"] + "plugins/*": ["src/legacy/core_plugins/*/public/"], + "fixtures/*": ["src/fixtures/*"] }, "types": [ "node", From da5097715c5dc005804abd1712ce66c002de5524 Mon Sep 17 00:00:00 2001 From: nickofthyme Date: Mon, 6 Jan 2020 13:16:30 -0600 Subject: [PATCH 2/8] Convert metric tests to jest --- .../public/__tests__/metric_vis.js | 95 ---------------- .../metric_vis_controller.test.ts} | 28 ++--- .../vis_type_metric/public/metric_vis.test.ts | 106 ++++++++++++++++++ .../vis_type_metric/public/metric_vis_type.ts | 2 +- .../vis_type_metric/public/plugin.ts | 4 +- 5 files changed, 124 insertions(+), 111 deletions(-) delete mode 100644 src/legacy/core_plugins/vis_type_metric/public/__tests__/metric_vis.js rename src/legacy/core_plugins/vis_type_metric/public/{__tests__/metric_vis_controller.js => components/metric_vis_controller.test.ts} (69%) create mode 100644 src/legacy/core_plugins/vis_type_metric/public/metric_vis.test.ts diff --git a/src/legacy/core_plugins/vis_type_metric/public/__tests__/metric_vis.js b/src/legacy/core_plugins/vis_type_metric/public/__tests__/metric_vis.js deleted file mode 100644 index f4786123f7b9d..0000000000000 --- a/src/legacy/core_plugins/vis_type_metric/public/__tests__/metric_vis.js +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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 $ from 'jquery'; -import ngMock from 'ng_mock'; -import expect from '@kbn/expect'; - -import { Vis } from 'ui/vis'; -import LogstashIndexPatternStubProvider from 'fixtures/stubbed_logstash_index_pattern'; - -import { start as visualizations } from '../../../visualizations/public/np_ready/public/legacy'; - -describe('metric_vis - createMetricVisTypeDefinition', () => { - let setup = null; - let vis; - - beforeEach(ngMock.module('kibana')); - beforeEach( - ngMock.inject(Private => { - setup = () => { - const metricVisType = visualizations.types.get('metric'); - const indexPattern = Private(LogstashIndexPatternStubProvider); - - indexPattern.stubSetFieldFormat('ip', 'url', { - urlTemplate: 'http://ip.info?address={{value}}', - labelTemplate: 'ip[{{value}}]', - }); - - vis = new Vis(indexPattern, { - type: 'metric', - aggs: [{ id: '1', type: 'top_hits', schema: 'metric', params: { field: 'ip' } }], - }); - - vis.params.dimensions = { - metrics: [ - { - accessor: 0, - format: { - id: 'url', - params: { - urlTemplate: 'http://ip.info?address={{value}}', - labelTemplate: 'ip[{{value}}]', - }, - }, - }, - ], - }; - - const el = document.createElement('div'); - const Controller = metricVisType.visualization; - const controller = new Controller(el, vis); - const render = esResponse => { - controller.render(esResponse, vis.params); - }; - - return { el, render }; - }; - }) - ); - - it('renders html value from field formatter', () => { - const { el, render } = setup(); - - const ip = '235.195.237.208'; - render({ - columns: [{ id: 'col-0', name: 'ip' }], - rows: [{ 'col-0': ip }], - }); - - const $link = $(el) - .find('a[href]') - .filter(function() { - return this.href.includes('ip.info'); - }); - - expect($link).to.have.length(1); - expect($link.text()).to.be(`ip[${ip}]`); - }); -}); diff --git a/src/legacy/core_plugins/vis_type_metric/public/__tests__/metric_vis_controller.js b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_controller.test.ts similarity index 69% rename from src/legacy/core_plugins/vis_type_metric/public/__tests__/metric_vis_controller.js rename to src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_controller.test.ts index 367c5f4699937..ffb83daa6123d 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/__tests__/metric_vis_controller.js +++ b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_controller.test.ts @@ -17,9 +17,11 @@ * under the License. */ -import expect from '@kbn/expect'; +// @ts-ignore import { MetricVisComponent } from '../components/metric_vis_controller'; +jest.mock('ui/new_platform'); + describe('metric_vis - controller', function() { const vis = { params: { @@ -35,26 +37,26 @@ describe('metric_vis - controller', function() { }, }; - let metricController; + let metricVis: MetricVisComponent; beforeEach(() => { - metricController = new MetricVisComponent({ vis: vis, visParams: vis.params }); + metricVis = new MetricVisComponent({ vis, visParams: vis.params }); }); it('should set the metric label and value', function() { - const metrics = metricController._processTableGroups({ + const metrics = metricVis._processTableGroups({ columns: [{ id: 'col-0', name: 'Count' }], rows: [{ 'col-0': 4301021 }], }); - expect(metrics.length).to.be(1); - expect(metrics[0].label).to.be('Count'); - expect(metrics[0].value).to.be('4301021'); + expect(metrics.length).toBe(1); + expect(metrics[0].label).toBe('Count'); + expect(metrics[0].value).toBe('4301021'); }); it('should support multi-value metrics', function() { vis.params.dimensions.metrics.push({ accessor: 1 }); - const metrics = metricController._processTableGroups({ + const metrics = metricVis._processTableGroups({ columns: [ { id: 'col-0', name: '1st percentile of bytes' }, { id: 'col-1', name: '99th percentile of bytes' }, @@ -62,10 +64,10 @@ describe('metric_vis - controller', function() { rows: [{ 'col-0': 182, 'col-1': 445842.4634666484 }], }); - expect(metrics.length).to.be(2); - expect(metrics[0].label).to.be('1st percentile of bytes'); - expect(metrics[0].value).to.be('182'); - expect(metrics[1].label).to.be('99th percentile of bytes'); - expect(metrics[1].value).to.be('445842.4634666484'); + expect(metrics.length).toBe(2); + expect(metrics[0].label).toBe('1st percentile of bytes'); + expect(metrics[0].value).toBe('182'); + expect(metrics[1].label).toBe('99th percentile of bytes'); + expect(metrics[1].value).toBe('445842.4634666484'); }); }); diff --git a/src/legacy/core_plugins/vis_type_metric/public/metric_vis.test.ts b/src/legacy/core_plugins/vis_type_metric/public/metric_vis.test.ts new file mode 100644 index 0000000000000..649959054416c --- /dev/null +++ b/src/legacy/core_plugins/vis_type_metric/public/metric_vis.test.ts @@ -0,0 +1,106 @@ +/* + * 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 $ from 'jquery'; + +import { npStart } from 'ui/new_platform'; +// @ts-ignore +import getStubIndexPattern from 'fixtures/stubbed_logstash_index_pattern'; + +import { Vis } from '../../visualizations/public'; +import { UrlFormat } from '../../../../plugins/data/public'; +import { + setup as visualizationsSetup, + start as visualizationsStart, +} from '../../visualizations/public/np_ready/public/legacy'; +import { metricVisTypeDefinition } from './metric_vis_type'; + +jest.mock('ui/new_platform'); + +describe('metric_vis - createMetricVisTypeDefinition', () => { + let vis: Vis; + + beforeAll(() => { + visualizationsSetup.types.createReactVisualization(metricVisTypeDefinition); + (npStart.plugins.data.fieldFormats.getType as jest.Mock).mockImplementation(() => { + return UrlFormat; + }); + }); + + const setup = () => { + const stubIndexPattern = getStubIndexPattern(); + + stubIndexPattern.stubSetFieldFormat('ip', 'url', { + urlTemplate: 'http://ip.info?address={{value}}', + labelTemplate: 'ip[{{value}}]', + }); + + // TODO: remove when Vis is converted to typescript. Only importing Vis as type + // @ts-ignore + vis = new Vis(stubIndexPattern, { + type: 'metric', + aggs: [{ id: '1', type: 'top_hits', schema: 'metric', params: { field: 'ip' } }], + }); + + vis.params.dimensions = { + metrics: [ + { + accessor: 0, + format: { + id: 'url', + params: { + urlTemplate: 'http://ip.info?address={{value}}', + labelTemplate: 'ip[{{value}}]', + }, + }, + }, + ], + }; + + const el = document.createElement('div'); + const metricVisType = visualizationsStart.types.get('metric'); + const Controller = metricVisType.visualization; + const controller = new Controller(el, vis); + const render = (esResponse: any) => { + controller.render(esResponse, vis.params); + }; + + return { el, render }; + }; + + it('renders html value from field formatter', () => { + const { el, render } = setup(); + + const ip = '235.195.237.208'; + render({ + columns: [{ id: 'col-0', name: 'ip' }], + rows: [{ 'col-0': ip }], + }); + + const links = $(el) + .find('a[href]') + .filter(function() { + // @ts-ignore + return this.href.includes('ip.info'); + }); + + expect(links.length).toBe(1); + expect(links.text()).toBe(`ip[${ip}]`); + }); +}); diff --git a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.ts b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.ts index ceab5dafe1f06..1638deb3cf227 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.ts @@ -31,7 +31,7 @@ import { MetricVisComponent } from './components/metric_vis_controller'; import { MetricVisOptions } from './components/metric_vis_options'; import { ColorModes } from '../../kbn_vislib_vis_types/public/utils/collections'; -export const metricVisDefinition = { +export const metricVisTypeDefinition = { name: 'metric', title: i18n.translate('visTypeMetric.metricTitle', { defaultMessage: 'Metric' }), icon: 'visMetric', diff --git a/src/legacy/core_plugins/vis_type_metric/public/plugin.ts b/src/legacy/core_plugins/vis_type_metric/public/plugin.ts index f5c152ce888c0..413f846d78991 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/plugin.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/plugin.ts @@ -22,7 +22,7 @@ import { Plugin as ExpressionsPublicPlugin } from '../../../../plugins/expressio import { VisualizationsSetup } from '../../visualizations/public'; import { createMetricVisFn } from './metric_vis_fn'; -import { metricVisDefinition } from './metric_vis_type'; +import { metricVisTypeDefinition } from './metric_vis_type'; /** @internal */ export interface MetricVisPluginSetupDependencies { @@ -40,7 +40,7 @@ export class MetricVisPlugin implements Plugin { public setup(core: CoreSetup, { expressions, visualizations }: MetricVisPluginSetupDependencies) { expressions.registerFunction(createMetricVisFn); - visualizations.types.createReactVisualization(metricVisDefinition); + visualizations.types.createReactVisualization(metricVisTypeDefinition); } public start(core: CoreStart) { From 8c265b62ab2514e79a41636b4af5299f1793b50b Mon Sep 17 00:00:00 2001 From: nickofthyme Date: Mon, 6 Jan 2020 14:27:43 -0600 Subject: [PATCH 3/8] Convert remaining js files to ts --- ...r.test.ts => metric_vis_component.test.ts} | 20 +++- ...controller.js => metric_vis_component.tsx} | 110 ++++++++++-------- .../public/components/metric_vis_options.tsx | 2 +- ...alue.test.js => metric_vis_value.test.tsx} | 2 +- ...tric_vis_value.js => metric_vis_value.tsx} | 33 +++--- .../vis_type_metric/public/legacy_imports.ts | 29 +++++ .../vis_type_metric/public/metric_vis_fn.ts | 4 +- .../vis_type_metric/public/metric_vis_type.ts | 10 +- .../vis_type_metric/public/types.ts | 3 +- 9 files changed, 129 insertions(+), 84 deletions(-) rename src/legacy/core_plugins/vis_type_metric/public/components/{metric_vis_controller.test.ts => metric_vis_component.test.ts} (83%) rename src/legacy/core_plugins/vis_type_metric/public/components/{metric_vis_controller.js => metric_vis_component.tsx} (64%) rename src/legacy/core_plugins/vis_type_metric/public/components/{metric_vis_value.test.js => metric_vis_value.test.tsx} (98%) rename src/legacy/core_plugins/vis_type_metric/public/components/{metric_vis_value.js => metric_vis_value.tsx} (79%) create mode 100644 src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts diff --git a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_controller.test.ts b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.ts similarity index 83% rename from src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_controller.test.ts rename to src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.ts index ffb83daa6123d..93cdd221a46af 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_controller.test.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.ts @@ -18,12 +18,13 @@ */ // @ts-ignore -import { MetricVisComponent } from '../components/metric_vis_controller'; +import { MetricVisComponent } from './metric_vis_component'; +import { Vis } from '../legacy_imports'; jest.mock('ui/new_platform'); describe('metric_vis - controller', function() { - const vis = { + const vis: Vis = { params: { metric: { colorSchema: 'Green to Red', @@ -35,16 +36,22 @@ describe('metric_vis - controller', function() { bucket: null, }, }, - }; + } as any; let metricVis: MetricVisComponent; beforeEach(() => { - metricVis = new MetricVisComponent({ vis, visParams: vis.params }); + metricVis = new MetricVisComponent({ + vis, + visParams: vis.params, + visData: {} as any, + renderComplete: jest.fn(), + }); }); it('should set the metric label and value', function() { - const metrics = metricVis._processTableGroups({ + // @ts-ignore + const metrics = metricVis.processTableGroups({ columns: [{ id: 'col-0', name: 'Count' }], rows: [{ 'col-0': 4301021 }], }); @@ -56,7 +63,8 @@ describe('metric_vis - controller', function() { it('should support multi-value metrics', function() { vis.params.dimensions.metrics.push({ accessor: 1 }); - const metrics = metricVis._processTableGroups({ + // @ts-ignore + const metrics = metricVis.processTableGroups({ columns: [ { id: 'col-0', name: '1st percentile of bytes' }, { id: 'col-1', name: '99th percentile of bytes' }, diff --git a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_controller.js b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.tsx similarity index 64% rename from src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_controller.js rename to src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.tsx index ecaf6b5d70d36..6c5661c4b0256 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_controller.js +++ b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.tsx @@ -19,20 +19,30 @@ import { last, findIndex, isNaN } from 'lodash'; import React, { Component } from 'react'; + import { isColorDark } from '@elastic/eui'; -import { getHeatmapColors } from 'ui/vislib/components/color/heatmap_color'; -import { getFormat } from 'ui/visualize/loader/pipeline_helpers/utilities'; +import { getHeatmapColors, getFormat, VisParams, Vis } from '../legacy_imports'; import { MetricVisValue } from './metric_vis_value'; +import { FieldFormat, ContentType } from '../../../../../plugins/data/public'; +import { Context } from '../metric_vis_fn'; +import { KibanaDatatable } from '../../../../../plugins/expressions/public'; + +interface MetricVisComponentProps { + visParams: VisParams; + visData: Context; + vis: Vis; + renderComplete: () => void; +} -export class MetricVisComponent extends Component { - _getLabels() { +export class MetricVisComponent extends Component { + private getLabels() { const config = this.props.visParams.metric; const isPercentageMode = config.percentageMode; const colorsRange = config.colorsRange; - const max = last(colorsRange).to; - const labels = []; - colorsRange.forEach(range => { + const max = last<{ to: number }>(colorsRange).to; + const labels: string[] = []; + colorsRange.forEach((range: any) => { const from = isPercentageMode ? Math.round((100 * range.from) / max) : range.from; const to = isPercentageMode ? Math.round((100 * range.to) / max) : range.to; labels.push(`${from} - ${to}`); @@ -41,13 +51,13 @@ export class MetricVisComponent extends Component { return labels; } - _getColors() { + private getColors() { const config = this.props.visParams.metric; const invertColors = config.invertColors; const colorSchema = config.colorSchema; const colorsRange = config.colorsRange; - const labels = this._getLabels(); - const colors = {}; + const labels = this.getLabels(); + const colors: any = {}; for (let i = 0; i < labels.length; i += 1) { const divider = Math.max(colorsRange.length - 1, 1); const val = invertColors ? 1 - i / divider : i / divider; @@ -56,9 +66,9 @@ export class MetricVisComponent extends Component { return colors; } - _getBucket(val) { + private getBucket(val: number) { const config = this.props.visParams.metric; - let bucket = findIndex(config.colorsRange, range => { + let bucket = findIndex(config.colorsRange, (range: any) => { return range.from <= val && range.to > val; }); @@ -70,59 +80,65 @@ export class MetricVisComponent extends Component { return bucket; } - _getColor(val, labels, colors) { - const bucket = this._getBucket(val); + private getColor(val: number, labels: string[], colors: any) { + const bucket = this.getBucket(val); const label = labels[bucket]; return colors[label]; } - _needsLightText(bgColor) { - const color = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/.exec(bgColor); - if (!color) { + private needsLightText(bgColor: string) { + const colors = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/.exec(bgColor); + if (!colors) { return false; } - return isColorDark(parseInt(color[1]), parseInt(color[2]), parseInt(color[3])); + + const [red, green, blue] = colors.slice(1).map(parseInt); + return isColorDark(red, green, blue); } - _getFormattedValue = (fieldFormatter, value, format = 'text') => { + private getFormattedValue = ( + fieldFormatter: FieldFormat, + value: any, + format: ContentType = 'text' + ) => { if (isNaN(value)) return '-'; return fieldFormatter.convert(value, format); }; - _processTableGroups(table) { + private processTableGroups(table: KibanaDatatable) { const config = this.props.visParams.metric; const dimensions = this.props.visParams.dimensions; const isPercentageMode = config.percentageMode; const min = config.colorsRange[0].from; - const max = last(config.colorsRange).to; - const colors = this._getColors(); - const labels = this._getLabels(); - const metrics = []; + const max = last<{ to: number }>(config.colorsRange).to; + const colors = this.getColors(); + const labels = this.getLabels(); + const metrics: any[] = []; // not yet typed - let bucketColumnId; - let bucketFormatter; + let bucketColumnId: string; + let bucketFormatter: FieldFormat; if (dimensions.bucket) { bucketColumnId = table.columns[dimensions.bucket.accessor].id; bucketFormatter = getFormat(dimensions.bucket.format); } - dimensions.metrics.forEach(metric => { + dimensions.metrics.forEach((metric: any) => { const columnIndex = metric.accessor; - const column = table.columns[columnIndex]; + const column = table?.columns[columnIndex]; const formatter = getFormat(metric.format); table.rows.forEach((row, rowIndex) => { let title = column.name; - let value = row[column.id]; - const color = this._getColor(value, labels, colors); + let value: any = row[column.id]; + const color = this.getColor(value, labels, colors); if (isPercentageMode) { value = (value - min) / (max - min); } - value = this._getFormattedValue(formatter, value, 'html'); + value = this.getFormattedValue(formatter, value, 'html'); if (bucketColumnId) { - const bucketValue = this._getFormattedValue(bucketFormatter, row[bucketColumnId]); + const bucketValue = this.getFormattedValue(bucketFormatter, row[bucketColumnId]); title = `${bucketValue} - ${title}`; } @@ -130,11 +146,11 @@ export class MetricVisComponent extends Component { metrics.push({ label: title, - value: value, + value, color: shouldColor && config.style.labelColor ? color : null, bgColor: shouldColor && config.style.bgColor ? color : null, - lightText: shouldColor && config.style.bgColor && this._needsLightText(color), - rowIndex: rowIndex, + lightText: shouldColor && config.style.bgColor && this.needsLightText(color), + rowIndex, }); }); }); @@ -142,7 +158,7 @@ export class MetricVisComponent extends Component { return metrics; } - _filterBucket = metric => { + private filterBucket = (metric: any) => { const dimensions = this.props.visParams.dimensions; if (!dimensions.bucket) { return; @@ -155,27 +171,18 @@ export class MetricVisComponent extends Component { }); }; - _renderMetric = (metric, index) => { + private renderMetric = (metric: any, index: number) => { return ( ); }; - render() { - let metricsHtml; - if (this.props.visData) { - const metrics = this._processTableGroups(this.props.visData); - metricsHtml = metrics.map(this._renderMetric); - } - return
{metricsHtml}
; - } - componentDidMount() { this.props.renderComplete(); } @@ -183,4 +190,13 @@ export class MetricVisComponent extends Component { componentDidUpdate() { this.props.renderComplete(); } + + render() { + let metricsHtml; + if (this.props.visData) { + const metrics = this.processTableGroups(this.props.visData); + metricsHtml = metrics.map(this.renderMetric); + } + return
{metricsHtml}
; + } } diff --git a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_options.tsx b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_options.tsx index 9649588976c0d..d03e61ebb43de 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_options.tsx +++ b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_options.tsx @@ -29,7 +29,7 @@ import { import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { VisOptionsProps } from 'ui/vis/editors/default'; +import { VisOptionsProps } from '../legacy_imports'; import { ColorRanges, ColorSchemaOptions, diff --git a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.test.js b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.test.tsx similarity index 98% rename from src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.test.js rename to src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.test.tsx index 2fc436cb829bd..f374b9b0d24f8 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.test.js +++ b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.test.tsx @@ -47,7 +47,7 @@ describe('MetricVisValue', () => { it('should not add -isfilterable class if onFilter is not provided', () => { const component = shallow( - + ); component.simulate('click'); expect(component.find('.mtrVis__container-isfilterable')).toHaveLength(0); diff --git a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.js b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.tsx similarity index 79% rename from src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.js rename to src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.tsx index ca5ab20957281..f0979b08b197e 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.js +++ b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.tsx @@ -18,19 +18,27 @@ */ import React, { Component } from 'react'; -import PropTypes from 'prop-types'; import classNames from 'classnames'; import { EuiKeyboardAccessible } from '@elastic/eui'; -class MetricVisValue extends Component { +interface MetricVisValueProps { + metric: any; // not yet typed + fontSize: number; + onFilter?: (metric: any) => void; + showLabel?: boolean; +} + +export class MetricVisValue extends Component { onClick = () => { - this.props.onFilter(this.props.metric); + if (this.props.onFilter) { + this.props.onFilter(this.props.metric); + } }; render() { const { fontSize, metric, onFilter, showLabel } = this.props; - const hasFilter = !!onFilter; + const hasFilter = Boolean(onFilter); const metricValueStyle = { fontSize: `${fontSize}pt`, @@ -46,9 +54,9 @@ class MetricVisValue extends Component {
{showLabel &&
{metric.label}
}
@@ -74,12 +82,3 @@ class MetricVisValue extends Component { return metricComponent; } } - -MetricVisValue.propTypes = { - fontSize: PropTypes.number.isRequired, - metric: PropTypes.object.isRequired, - onFilter: PropTypes.func, - showLabel: PropTypes.bool, -}; - -export { MetricVisValue }; diff --git a/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts b/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts new file mode 100644 index 0000000000000..3761eee35a2d7 --- /dev/null +++ b/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts @@ -0,0 +1,29 @@ +/* + * 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. + */ + +export { Vis, VisParams } from 'ui/vis'; +export { vislibColorMaps, colorSchemas, ColorSchemas } from 'ui/vislib/components/color/colormaps'; +export { RangeValues } from 'ui/vis/editors/default/controls/ranges'; +// @ts-ignore +export { getHeatmapColors } from 'ui/vislib/components/color/heatmap_color'; +export { getFormat } from 'ui/visualize/loader/pipeline_helpers/utilities'; +export { VisOptionsProps } from 'ui/vis/editors/default'; +// @ts-ignore +export { Schemas } from 'ui/vis/editors/default/schemas'; +export { AggGroupNames } from 'ui/vis/editors/default'; diff --git a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_fn.ts b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_fn.ts index b64361f17c470..7f76e582e7964 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_fn.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; -import { vislibColorMaps, ColorSchemas } from 'ui/vislib/components/color/colormaps'; +import { vislibColorMaps, ColorSchemas } from './legacy_imports'; import { ExpressionFunction, KibanaDatatable, @@ -30,7 +30,7 @@ import { import { ColorModes } from '../../kbn_vislib_vis_types/public/utils/collections'; import { visType, DimensionsVisParam, VisParams } from './types'; -type Context = KibanaDatatable; +export type Context = KibanaDatatable; const name = 'metricVis'; diff --git a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.ts b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.ts index 1638deb3cf227..90110ccbe4bc1 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.ts @@ -20,15 +20,9 @@ import { i18n } from '@kbn/i18n'; // @ts-ignore -import { Schemas } from 'ui/vis/editors/default/schemas'; - -import { AggGroupNames } from 'ui/vis/editors/default'; -import { colorSchemas, ColorSchemas } from 'ui/vislib/components/color/colormaps'; - -// @ts-ignore -import { MetricVisComponent } from './components/metric_vis_controller'; - +import { MetricVisComponent } from './components/metric_vis_component'; import { MetricVisOptions } from './components/metric_vis_options'; +import { Schemas, AggGroupNames, colorSchemas, ColorSchemas } from './legacy_imports'; import { ColorModes } from '../../kbn_vislib_vis_types/public/utils/collections'; export const metricVisTypeDefinition = { diff --git a/src/legacy/core_plugins/vis_type_metric/public/types.ts b/src/legacy/core_plugins/vis_type_metric/public/types.ts index ce0e78140a86a..a291666ebde9d 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/types.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/types.ts @@ -17,8 +17,7 @@ * under the License. */ -import { ColorSchemas } from 'ui/vislib/components/color/colormaps'; -import { RangeValues } from 'ui/vis/editors/default/controls/ranges'; +import { ColorSchemas, RangeValues } from './legacy_imports'; import { SchemaConfig } from '../../visualizations/public'; import { ColorModes } from '../../kbn_vislib_vis_types/public/utils/collections'; import { Labels, Style } from '../../kbn_vislib_vis_types/public/types'; From 0fd87ba717cdf0a44e2c82164455c5445be339ce Mon Sep 17 00:00:00 2001 From: nickofthyme Date: Thu, 9 Jan 2020 14:04:45 -0600 Subject: [PATCH 4/8] Address PR comments --- .../__snapshots__/metric_vis_fn.test.ts.snap | 2 +- .../metric_vis_component.test.tsx.snap | 57 +++++++++++ .../components/metric_vis_component.test.ts | 81 ---------------- .../components/metric_vis_component.test.tsx | 94 +++++++++++++++++++ .../components/metric_vis_component.tsx | 23 +++-- .../components/metric_vis_value.test.tsx | 18 ++-- .../public/components/metric_vis_value.tsx | 6 +- .../vis_type_metric/public/legacy_imports.ts | 1 - .../vis_type_metric/public/metric_vis_fn.ts | 22 ++--- ...ic_vis.test.ts => metric_vis_type.test.ts} | 0 .../vis_type_metric/public/types.ts | 16 +++- .../__snapshots__/build_pipeline.test.ts.snap | 2 +- .../np_ready/public/legacy/build_pipeline.ts | 4 +- .../translations/translations/ja-JP.json | 6 +- .../translations/translations/zh-CN.json | 6 +- 15 files changed, 210 insertions(+), 128 deletions(-) create mode 100644 src/legacy/core_plugins/vis_type_metric/public/components/__snapshots__/metric_vis_component.test.tsx.snap delete mode 100644 src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.ts create mode 100644 src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.tsx rename src/legacy/core_plugins/vis_type_metric/public/{metric_vis.test.ts => metric_vis_type.test.ts} (100%) diff --git a/src/legacy/core_plugins/vis_type_metric/public/__snapshots__/metric_vis_fn.test.ts.snap b/src/legacy/core_plugins/vis_type_metric/public/__snapshots__/metric_vis_fn.test.ts.snap index d0fba4d164dbf..44414cedf966a 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/__snapshots__/metric_vis_fn.test.ts.snap +++ b/src/legacy/core_plugins/vis_type_metric/public/__snapshots__/metric_vis_fn.test.ts.snap @@ -13,7 +13,7 @@ Object { "metrics": undefined, }, "metric": Object { - "colorSchema": "\\"Green to Red\\"", + "colorSchema": "Green to Red", "colorsRange": "{range from=0 to=10000}", "invertColors": false, "labels": Object { diff --git a/src/legacy/core_plugins/vis_type_metric/public/components/__snapshots__/metric_vis_component.test.tsx.snap b/src/legacy/core_plugins/vis_type_metric/public/components/__snapshots__/metric_vis_component.test.tsx.snap new file mode 100644 index 0000000000000..d84424cc6179a --- /dev/null +++ b/src/legacy/core_plugins/vis_type_metric/public/components/__snapshots__/metric_vis_component.test.tsx.snap @@ -0,0 +1,57 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`MetricVisComponent should render correct structure for single metric 1`] = ` +
+ 4301021", + } + } + showLabel={true} + /> +
+`; + +exports[`MetricVisComponent should render correct structure for multi-value metrics 1`] = ` +
+ 182", + } + } + showLabel={true} + /> + 445842.4634666484", + } + } + showLabel={true} + /> +
+`; diff --git a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.ts b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.ts deleted file mode 100644 index 93cdd221a46af..0000000000000 --- a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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. - */ - -// @ts-ignore -import { MetricVisComponent } from './metric_vis_component'; -import { Vis } from '../legacy_imports'; - -jest.mock('ui/new_platform'); - -describe('metric_vis - controller', function() { - const vis: Vis = { - params: { - metric: { - colorSchema: 'Green to Red', - colorsRange: [{ from: 0, to: 1000 }], - style: {}, - }, - dimensions: { - metrics: [{ accessor: 0 }], - bucket: null, - }, - }, - } as any; - - let metricVis: MetricVisComponent; - - beforeEach(() => { - metricVis = new MetricVisComponent({ - vis, - visParams: vis.params, - visData: {} as any, - renderComplete: jest.fn(), - }); - }); - - it('should set the metric label and value', function() { - // @ts-ignore - const metrics = metricVis.processTableGroups({ - columns: [{ id: 'col-0', name: 'Count' }], - rows: [{ 'col-0': 4301021 }], - }); - - expect(metrics.length).toBe(1); - expect(metrics[0].label).toBe('Count'); - expect(metrics[0].value).toBe('4301021'); - }); - - it('should support multi-value metrics', function() { - vis.params.dimensions.metrics.push({ accessor: 1 }); - // @ts-ignore - const metrics = metricVis.processTableGroups({ - columns: [ - { id: 'col-0', name: '1st percentile of bytes' }, - { id: 'col-1', name: '99th percentile of bytes' }, - ], - rows: [{ 'col-0': 182, 'col-1': 445842.4634666484 }], - }); - - expect(metrics.length).toBe(2); - expect(metrics[0].label).toBe('1st percentile of bytes'); - expect(metrics[0].value).toBe('182'); - expect(metrics[1].label).toBe('99th percentile of bytes'); - expect(metrics[1].value).toBe('445842.4634666484'); - }); -}); diff --git a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.tsx b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.tsx new file mode 100644 index 0000000000000..e3cc10ee9c6e5 --- /dev/null +++ b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.tsx @@ -0,0 +1,94 @@ +/* + * 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 React from 'react'; +import { shallow } from 'enzyme'; + +import { MetricVisComponent } from './metric_vis_component'; +import { Vis } from '../legacy_imports'; +import { MetricVisValue } from './metric_vis_value'; + +jest.mock('ui/new_platform'); + +type Props = MetricVisComponent['props']; + +const baseVisData = { + columns: [{ id: 'col-0', name: 'Count' }], + rows: [{ 'col-0': 4301021 }], +} as any; + +describe('MetricVisComponent', function() { + const vis: Vis = { + params: { + metric: { + colorSchema: 'Green to Red', + colorsRange: [{ from: 0, to: 1000 }], + style: {}, + labels: { + show: true, + }, + }, + dimensions: { + metrics: [{ accessor: 0 }], + bucket: null, + }, + }, + } as any; + + const getComponent = (propOverrides: Partial = {} as Partial) => { + const props: Props = { + vis, + visParams: vis.params, + visData: baseVisData, + renderComplete: jest.fn(), + ...propOverrides, + }; + + return shallow(); + }; + + it('should render component', () => { + expect(getComponent().exists()).toBe(true); + }); + + it('should render correct structure for single metric', function() { + expect(getComponent()).toMatchSnapshot(); + }); + + it('should render correct structure for multi-value metrics', function() { + const component = getComponent({ + visData: { + columns: [ + { id: 'col-0', name: '1st percentile of bytes' }, + { id: 'col-1', name: '99th percentile of bytes' }, + ], + rows: [{ 'col-0': 182, 'col-1': 445842.4634666484 }], + }, + visParams: { + ...vis.params, + dimensions: { + ...vis.params.dimensions, + metrics: [{ accessor: 0 }, { accessor: 1 }], + }, + }, + } as any); + + expect(component).toMatchSnapshot(); + }); +}); diff --git a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.tsx b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.tsx index 6c5661c4b0256..f8398f5c83146 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.tsx +++ b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.tsx @@ -22,11 +22,13 @@ import React, { Component } from 'react'; import { isColorDark } from '@elastic/eui'; -import { getHeatmapColors, getFormat, VisParams, Vis } from '../legacy_imports'; +import { getHeatmapColors, getFormat, Vis } from '../legacy_imports'; import { MetricVisValue } from './metric_vis_value'; import { FieldFormat, ContentType } from '../../../../../plugins/data/public'; import { Context } from '../metric_vis_fn'; import { KibanaDatatable } from '../../../../../plugins/expressions/public'; +import { VisParams, MetricVisMetric } from '../types'; +import { SchemaConfig } from '../../../visualizations/public'; interface MetricVisComponentProps { visParams: VisParams; @@ -40,8 +42,9 @@ export class MetricVisComponent extends Component { const config = this.props.visParams.metric; const isPercentageMode = config.percentageMode; const colorsRange = config.colorsRange; - const max = last<{ to: number }>(colorsRange).to; + const max = last(colorsRange).to; const labels: string[] = []; + colorsRange.forEach((range: any) => { const from = isPercentageMode ? Math.round((100 * range.from) / max) : range.from; const to = isPercentageMode ? Math.round((100 * range.to) / max) : range.to; @@ -80,7 +83,7 @@ export class MetricVisComponent extends Component { return bucket; } - private getColor(val: number, labels: string[], colors: any) { + private getColor(val: number, labels: string[], colors: { [label: string]: string }) { const bucket = this.getBucket(val); const label = labels[bucket]; return colors[label]; @@ -110,10 +113,10 @@ export class MetricVisComponent extends Component { const dimensions = this.props.visParams.dimensions; const isPercentageMode = config.percentageMode; const min = config.colorsRange[0].from; - const max = last<{ to: number }>(config.colorsRange).to; + const max = last(config.colorsRange).to; const colors = this.getColors(); const labels = this.getLabels(); - const metrics: any[] = []; // not yet typed + const metrics: MetricVisMetric[] = []; let bucketColumnId: string; let bucketFormatter: FieldFormat; @@ -123,7 +126,7 @@ export class MetricVisComponent extends Component { bucketFormatter = getFormat(dimensions.bucket.format); } - dimensions.metrics.forEach((metric: any) => { + dimensions.metrics.forEach((metric: SchemaConfig) => { const columnIndex = metric.accessor; const column = table?.columns[columnIndex]; const formatter = getFormat(metric.format); @@ -147,8 +150,8 @@ export class MetricVisComponent extends Component { metrics.push({ label: title, value, - color: shouldColor && config.style.labelColor ? color : null, - bgColor: shouldColor && config.style.bgColor ? color : null, + color: shouldColor && config.style.labelColor ? color : undefined, + bgColor: shouldColor && config.style.bgColor ? color : undefined, lightText: shouldColor && config.style.bgColor && this.needsLightText(color), rowIndex, }); @@ -158,7 +161,7 @@ export class MetricVisComponent extends Component { return metrics; } - private filterBucket = (metric: any) => { + private filterBucket = (metric: MetricVisMetric) => { const dimensions = this.props.visParams.dimensions; if (!dimensions.bucket) { return; @@ -171,7 +174,7 @@ export class MetricVisComponent extends Component { }); }; - private renderMetric = (metric: any, index: number) => { + private renderMetric = (metric: MetricVisMetric, index: number) => { return ( { it('should be wrapped in EuiKeyboardAccessible if having a click listener', () => { const component = shallow( - {}} /> + {}} /> ); expect(component.find('EuiKeyboardAccessible').exists()).toBe(true); }); it('should not be wrapped in EuiKeyboardAccessible without having a click listener', () => { - const component = shallow( - - ); + const component = shallow(); expect(component.find('EuiKeyboardAccessible').exists()).toBe(false); }); it('should add -isfilterable class if onFilter is provided', () => { const onFilter = jest.fn(); const component = shallow( - + ); component.simulate('click'); expect(component.find('.mtrVis__container-isfilterable')).toHaveLength(1); }); it('should not add -isfilterable class if onFilter is not provided', () => { - const component = shallow( - - ); + const component = shallow(); component.simulate('click'); expect(component.find('.mtrVis__container-isfilterable')).toHaveLength(0); }); @@ -56,9 +54,9 @@ describe('MetricVisValue', () => { it('should call onFilter callback if provided', () => { const onFilter = jest.fn(); const component = shallow( - + ); component.find('.mtrVis__container-isfilterable').simulate('click'); - expect(onFilter).toHaveBeenCalledWith({ label: 'Foo', value: 'foo' }); + expect(onFilter).toHaveBeenCalledWith(baseMetric); }); }); diff --git a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.tsx b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.tsx index f0979b08b197e..6b291d3dbef61 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.tsx +++ b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_value.tsx @@ -22,10 +22,12 @@ import classNames from 'classnames'; import { EuiKeyboardAccessible } from '@elastic/eui'; +import { MetricVisMetric } from '../types'; + interface MetricVisValueProps { - metric: any; // not yet typed + metric: MetricVisMetric; fontSize: number; - onFilter?: (metric: any) => void; + onFilter?: (metric: MetricVisMetric) => void; showLabel?: boolean; } diff --git a/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts b/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts index 3761eee35a2d7..30e3722a66b41 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts @@ -19,7 +19,6 @@ export { Vis, VisParams } from 'ui/vis'; export { vislibColorMaps, colorSchemas, ColorSchemas } from 'ui/vislib/components/color/colormaps'; -export { RangeValues } from 'ui/vis/editors/default/controls/ranges'; // @ts-ignore export { getHeatmapColors } from 'ui/vislib/components/color/heatmap_color'; export { getFormat } from 'ui/visualize/loader/pipeline_helpers/utilities'; diff --git a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_fn.ts b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_fn.ts index 7f76e582e7964..b53f7bbce7d93 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_fn.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_fn.ts @@ -35,8 +35,8 @@ export type Context = KibanaDatatable; const name = 'metricVis'; interface Arguments { - percentage: boolean; - colorScheme: ColorSchemas; + percentageMode: boolean; + colorSchema: ColorSchemas; colorMode: ColorModes; useRanges: boolean; invertColors: boolean; @@ -73,19 +73,19 @@ export const createMetricVisFn = (): ExpressionFunction< defaultMessage: 'Metric visualization', }), args: { - percentage: { + percentageMode: { types: ['boolean'], default: false, - help: i18n.translate('visTypeMetric.function.percentage.help', { + help: i18n.translate('visTypeMetric.function.percentageMode.help', { defaultMessage: 'Shows metric in percentage mode. Requires colorRange to be set.', }), }, - colorScheme: { + colorSchema: { types: ['string'], default: '"Green to Red"', options: Object.values(vislibColorMaps).map((value: any) => value.id), - help: i18n.translate('visTypeMetric.function.colorScheme.help', { - defaultMessage: 'Color scheme to use', + help: i18n.translate('visTypeMetric.function.colorSchema.help', { + defaultMessage: 'Color schema to use', }), }, colorMode: { @@ -174,8 +174,8 @@ export const createMetricVisFn = (): ExpressionFunction< dimensions.bucket = args.bucket; } - if (args.percentage && (!args.colorRange || args.colorRange.length === 0)) { - throw new Error('colorRange must be provided when using percentage'); + if (args.percentageMode && (!args.colorRange || args.colorRange.length === 0)) { + throw new Error('colorRange must be provided when using percentageMode'); } const fontSize = Number.parseInt(args.font.spec.fontSize || '', 10); @@ -188,9 +188,9 @@ export const createMetricVisFn = (): ExpressionFunction< visType, visConfig: { metric: { - percentageMode: args.percentage, + percentageMode: args.percentageMode, useRanges: args.useRanges, - colorSchema: args.colorScheme, + colorSchema: args.colorSchema, metricColorMode: args.colorMode, colorsRange: args.colorRange, labels: { diff --git a/src/legacy/core_plugins/vis_type_metric/public/metric_vis.test.ts b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.test.ts similarity index 100% rename from src/legacy/core_plugins/vis_type_metric/public/metric_vis.test.ts rename to src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.test.ts diff --git a/src/legacy/core_plugins/vis_type_metric/public/types.ts b/src/legacy/core_plugins/vis_type_metric/public/types.ts index a291666ebde9d..7e0851bf59d80 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/types.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/types.ts @@ -17,7 +17,8 @@ * under the License. */ -import { ColorSchemas, RangeValues } from './legacy_imports'; +import { ColorSchemas } from './legacy_imports'; +import { Range } from '../../../../plugins/expressions/public'; import { SchemaConfig } from '../../visualizations/public'; import { ColorModes } from '../../kbn_vislib_vis_types/public/utils/collections'; import { Labels, Style } from '../../kbn_vislib_vis_types/public/types'; @@ -26,7 +27,7 @@ export const visType = 'metric'; export interface DimensionsVisParam { metrics: SchemaConfig[]; - bucket?: SchemaConfig[]; + bucket?: SchemaConfig; } export interface MetricVisParam { @@ -34,7 +35,7 @@ export interface MetricVisParam { useRanges: boolean; colorSchema: ColorSchemas; metricColorMode: ColorModes; - colorsRange: RangeValues[]; + colorsRange: Range[]; labels: Labels; invertColors: boolean; style: Style; @@ -47,3 +48,12 @@ export interface VisParams { metric: MetricVisParam; type: typeof visType; } + +export interface MetricVisMetric { + value: any; + label: string; + color?: string; + bgColor?: string; + lightText: boolean; + rowIndex: number; +} diff --git a/src/legacy/core_plugins/visualizations/public/np_ready/public/legacy/__snapshots__/build_pipeline.test.ts.snap b/src/legacy/core_plugins/visualizations/public/np_ready/public/legacy/__snapshots__/build_pipeline.test.ts.snap index ddd74628e7940..90c1d4472d5ea 100644 --- a/src/legacy/core_plugins/visualizations/public/np_ready/public/legacy/__snapshots__/build_pipeline.test.ts.snap +++ b/src/legacy/core_plugins/visualizations/public/np_ready/public/legacy/__snapshots__/build_pipeline.test.ts.snap @@ -8,7 +8,7 @@ exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunct exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles metric function with buckets 1`] = `"metricvis metric={visdimension 0 } metric={visdimension 1 } "`; -exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles metric function with percentage mode should have percentage format 1`] = `"metricvis percentage=true metric={visdimension 0 format='percent' } "`; +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles metric function with percentage mode should have percentage format 1`] = `"metricvis percentageMode=true metric={visdimension 0 format='percent' } "`; exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles metric function without buckets 1`] = `"metricvis metric={visdimension 0 } metric={visdimension 1 } "`; diff --git a/src/legacy/core_plugins/visualizations/public/np_ready/public/legacy/build_pipeline.ts b/src/legacy/core_plugins/visualizations/public/np_ready/public/legacy/build_pipeline.ts index 59c6bddb64521..68b63bba3ab98 100644 --- a/src/legacy/core_plugins/visualizations/public/np_ready/public/legacy/build_pipeline.ts +++ b/src/legacy/core_plugins/visualizations/public/np_ready/public/legacy/build_pipeline.ts @@ -298,8 +298,8 @@ export const buildPipelineVisFunction: BuildPipelineVisFunction = { } let expr = `metricvis `; - expr += prepareValue('percentage', percentageMode); - expr += prepareValue('colorScheme', colorSchema); + expr += prepareValue('percentageMode', percentageMode); + expr += prepareValue('colorSchema', colorSchema); expr += prepareValue('colorMode', metricColorMode); expr += prepareValue('useRanges', useRanges); expr += prepareValue('invertColors', invertColors); diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 83ef497e50649..a9f27af937ddf 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -3042,11 +3042,11 @@ "visTypeMetric.function.bucket.help": "バケットディメンションの構成です。", "visTypeMetric.function.colorMode.help": "色を変更するメトリックの部分", "visTypeMetric.function.colorRange.help": "別の色が適用される値のグループを指定する範囲オブジェクト。", - "visTypeMetric.function.colorScheme.help": "使用する配色", + "visTypeMetric.function.colorSchema.help": "使用する配色", "visTypeMetric.function.font.help": "フォント設定です。", "visTypeMetric.function.invertColors.help": "色範囲を反転します", "visTypeMetric.function.metric.help": "メトリックディメンションの構成です。", - "visTypeMetric.function.percentage.help": "パーセンテージモードでメトリックを表示します。colorRange を設定する必要があります。", + "visTypeMetric.function.percentageMode.help": "パーセンテージモードでメトリックを表示します。colorRange を設定する必要があります。", "visTypeMetric.function.showLabels.help": "メトリック値の下にラベルを表示します。", "visTypeMetric.function.subText.help": "メトリックの下に表示するカスタムテキスト", "visTypeMetric.function.useRanges.help": "有効な色範囲です。", @@ -12704,4 +12704,4 @@ "xpack.licensing.welcomeBanner.licenseIsExpiredDescription.updateYourLicenseLinkText": "ライセンスを更新", "xpack.licensing.welcomeBanner.licenseIsExpiredTitle": "ご使用の {licenseType} ライセンスは期限切れです" } -} \ No newline at end of file +} diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 87c11adcb5e77..897e3834d289b 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -3043,11 +3043,11 @@ "visTypeMetric.function.bucket.help": "存储桶维度配置", "visTypeMetric.function.colorMode.help": "指标的哪部分要上色", "visTypeMetric.function.colorRange.help": "指定应将不同颜色应用到的值组的范围对象。", - "visTypeMetric.function.colorScheme.help": "要使用的颜色方案", + "visTypeMetric.function.colorSchema.help": "要使用的颜色方案", "visTypeMetric.function.font.help": "字体设置。", "visTypeMetric.function.invertColors.help": "反转颜色范围", "visTypeMetric.function.metric.help": "指标维度配置", - "visTypeMetric.function.percentage.help": "以百分比模式显示指标。需要设置 colorRange。", + "visTypeMetric.function.percentageMode.help": "以百分比模式显示指标。需要设置 colorRange。", "visTypeMetric.function.showLabels.help": "在指标值下显示标签。", "visTypeMetric.function.subText.help": "要在指标下显示的定制文本", "visTypeMetric.function.useRanges.help": "已启用颜色范围。", @@ -12793,4 +12793,4 @@ "xpack.licensing.welcomeBanner.licenseIsExpiredDescription.updateYourLicenseLinkText": "更新您的许可", "xpack.licensing.welcomeBanner.licenseIsExpiredTitle": "您的{licenseType}许可已过期" } -} \ No newline at end of file +} From deecb22e46bcb4de3ae5b60f523acbeadffdd1df Mon Sep 17 00:00:00 2001 From: nickofthyme Date: Fri, 10 Jan 2020 11:19:34 -0600 Subject: [PATCH 5/8] Fix ci test failures --- .../public/components/common/color_ranges.tsx | 4 +++- .../public/components/metric_vis_component.test.tsx | 1 - .../public/components/metric_vis_options.tsx | 3 ++- ...ic_percentage.png => metric_percentage_mode.png} | Bin ..._percentage.json => metric_percentage_mode.json} | 0 ..._percentage.json => metric_percentage_mode.json} | 0 .../test_suites/run_pipeline/metric.ts | 10 +++++++--- 7 files changed, 12 insertions(+), 6 deletions(-) rename test/interpreter_functional/screenshots/baseline/{metric_percentage.png => metric_percentage_mode.png} (100%) rename test/interpreter_functional/snapshots/baseline/{metric_percentage.json => metric_percentage_mode.json} (100%) rename test/interpreter_functional/snapshots/session/{metric_percentage.json => metric_percentage_mode.json} (100%) diff --git a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/common/color_ranges.tsx b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/common/color_ranges.tsx index 276e765ae7fe6..f5fcc472812b8 100644 --- a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/common/color_ranges.tsx +++ b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/common/color_ranges.tsx @@ -23,10 +23,12 @@ import { i18n } from '@kbn/i18n'; import { RangeValues, RangesParamEditor } from 'ui/vis/editors/default/controls/ranges'; +export type SetColorRangeValue = (paramName: string, value: RangeValues[]) => void; + interface ColorRangesProps { 'data-test-subj'?: string; colorsRange: RangeValues[]; - setValue(paramName: string, value: RangeValues[]): void; + setValue: SetColorRangeValue; setValidity?(isValid: boolean): void; setTouched?(isTouched: boolean): void; } diff --git a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.tsx b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.tsx index e3cc10ee9c6e5..901273ccbeb95 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.tsx +++ b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.test.tsx @@ -22,7 +22,6 @@ import { shallow } from 'enzyme'; import { MetricVisComponent } from './metric_vis_component'; import { Vis } from '../legacy_imports'; -import { MetricVisValue } from './metric_vis_value'; jest.mock('ui/new_platform'); diff --git a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_options.tsx b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_options.tsx index d03e61ebb43de..87166abfe25a0 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_options.tsx +++ b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_options.tsx @@ -39,6 +39,7 @@ import { } from '../../../kbn_vislib_vis_types/public/components'; import { ColorModes } from '../../../kbn_vislib_vis_types/public/utils/collections'; import { MetricVisParam, VisParams } from '../types'; +import { SetColorRangeValue } from '../../../kbn_vislib_vis_types/public/components/common/color_ranges'; function MetricVisOptions({ stateParams, @@ -135,7 +136,7 @@ function MetricVisOptions({ diff --git a/test/interpreter_functional/screenshots/baseline/metric_percentage.png b/test/interpreter_functional/screenshots/baseline/metric_percentage_mode.png similarity index 100% rename from test/interpreter_functional/screenshots/baseline/metric_percentage.png rename to test/interpreter_functional/screenshots/baseline/metric_percentage_mode.png diff --git a/test/interpreter_functional/snapshots/baseline/metric_percentage.json b/test/interpreter_functional/snapshots/baseline/metric_percentage_mode.json similarity index 100% rename from test/interpreter_functional/snapshots/baseline/metric_percentage.json rename to test/interpreter_functional/snapshots/baseline/metric_percentage_mode.json diff --git a/test/interpreter_functional/snapshots/session/metric_percentage.json b/test/interpreter_functional/snapshots/session/metric_percentage_mode.json similarity index 100% rename from test/interpreter_functional/snapshots/session/metric_percentage.json rename to test/interpreter_functional/snapshots/session/metric_percentage_mode.json diff --git a/test/interpreter_functional/test_suites/run_pipeline/metric.ts b/test/interpreter_functional/test_suites/run_pipeline/metric.ts index c238bedfa28ce..5f685037d4fad 100644 --- a/test/interpreter_functional/test_suites/run_pipeline/metric.ts +++ b/test/interpreter_functional/test_suites/run_pipeline/metric.ts @@ -81,11 +81,15 @@ export default function({ ).toMatchScreenshot(); }); - it('with percentage option', async () => { + it('with percentageMode option', async () => { const expression = - 'metricVis metric={visdimension 0} percentage=true colorRange={range from=0 to=1000}'; + 'metricVis metric={visdimension 0} percentageMode=true colorRange={range from=0 to=1000}'; await ( - await expectExpression('metric_percentage', expression, dataContext).toMatchSnapshot() + await expectExpression( + 'metric_percentage_mode', + expression, + dataContext + ).toMatchSnapshot() ).toMatchScreenshot(); }); }); From 6da558556edc24a09242f1b87028db8ffba4856c Mon Sep 17 00:00:00 2001 From: nickofthyme Date: Fri, 10 Jan 2020 14:06:52 -0600 Subject: [PATCH 6/8] Fix type errors --- .../public/components/options/gauge/ranges_panel.tsx | 3 ++- .../public/components/options/heatmap/index.tsx | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/ranges_panel.tsx b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/ranges_panel.tsx index 1045543512c6b..4e366f2b9416e 100644 --- a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/ranges_panel.tsx +++ b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/ranges_panel.tsx @@ -27,6 +27,7 @@ import { ColorRanges, ColorSchemaOptions, SwitchOption } from '../../common'; import { GaugeOptionsInternalProps } from '.'; import { ColorSchemaVislibParams } from '../../../types'; import { Gauge } from '../../../gauge'; +import { SetColorRangeValue } from '../../common/color_ranges'; function RangesPanel({ setGaugeValue, @@ -68,7 +69,7 @@ function RangesPanel({ diff --git a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/heatmap/index.tsx b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/heatmap/index.tsx index 659bcf47f7a0b..5b2226801c966 100644 --- a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/heatmap/index.tsx +++ b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/heatmap/index.tsx @@ -35,6 +35,7 @@ import { SetColorSchemaOptionsValue } from '../../common/color_schema'; import { HeatmapVisParams } from '../../../heatmap'; import { ValueAxis } from '../../../types'; import { LabelsPanel } from './labels_panel'; +import { SetColorRangeValue } from '../../common/color_ranges'; function HeatmapOptions(props: VisOptionsProps) { const { stateParams, vis, uiState, setValue, setValidity, setTouched } = props; @@ -170,7 +171,7 @@ function HeatmapOptions(props: VisOptionsProps) { From 3e8d869ad48498b2539e20e6e28028f586c9c5af Mon Sep 17 00:00:00 2001 From: nickofthyme Date: Thu, 16 Jan 2020 08:37:36 -0600 Subject: [PATCH 7/8] Fix type error --- .../core_plugins/vis_type_metric/public/legacy_imports.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts b/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts index 30e3722a66b41..c5ea4830d3eee 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts @@ -18,7 +18,7 @@ */ export { Vis, VisParams } from 'ui/vis'; -export { vislibColorMaps, colorSchemas, ColorSchemas } from 'ui/vislib/components/color/colormaps'; +export { vislibColorMaps, colorSchemas, ColorSchemas } from 'ui/color_maps'; // @ts-ignore export { getHeatmapColors } from 'ui/vislib/components/color/heatmap_color'; export { getFormat } from 'ui/visualize/loader/pipeline_helpers/utilities'; From cef03ae52c31d598a9e4fc51b13b31c487565bfb Mon Sep 17 00:00:00 2001 From: nickofthyme Date: Thu, 16 Jan 2020 14:43:17 -0600 Subject: [PATCH 8/8] Fix jest test error --- .../core_plugins/vis_type_metric/public/legacy_imports.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts b/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts index c5ea4830d3eee..93dfd76e16b16 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts @@ -19,8 +19,7 @@ export { Vis, VisParams } from 'ui/vis'; export { vislibColorMaps, colorSchemas, ColorSchemas } from 'ui/color_maps'; -// @ts-ignore -export { getHeatmapColors } from 'ui/vislib/components/color/heatmap_color'; +export { getHeatmapColors } from 'ui/color_maps'; export { getFormat } from 'ui/visualize/loader/pipeline_helpers/utilities'; export { VisOptionsProps } from 'ui/vis/editors/default'; // @ts-ignore