Skip to content

Commit

Permalink
[Lens] Lens/xy config panel (#37391)
Browse files Browse the repository at this point in the history
Basic xy chart configuration panel
  • Loading branch information
chrisdavies authored Jun 6, 2019
1 parent bbf80f2 commit 717eaff
Show file tree
Hide file tree
Showing 16 changed files with 902 additions and 324 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -252,9 +252,6 @@ Object {
state: updatedState,
})
);

// don't re-render datasource when visulization changes
expect(mockDatasource.renderDataPanel).toHaveBeenCalledTimes(1);
});

it('should re-render data panel after state update', async () => {
Expand Down
1 change: 1 addition & 0 deletions x-pack/plugins/lens/public/editor_frame_plugin/mocks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export function createMockDatasource(): DatasourceMock {
const publicAPIMock: jest.Mocked<DatasourcePublicAPI> = {
getTableSpec: jest.fn(() => []),
getOperationForColumnId: jest.fn(),
generateColumnId: jest.fn(),
renderDimensionPanel: jest.fn(),
removeColumnInTableSpec: jest.fn(),
moveColumnTo: jest.fn(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { Chrome } from 'ui/chrome';
import { ToastNotifications } from 'ui/notify/toasts/toast_notifications';
import { EuiComboBox } from '@elastic/eui';
import { Datasource, DataType } from '..';
import uuid from 'uuid';
import { DatasourceDimensionPanelProps, DatasourceDataPanelProps } from '../types';
import { getIndexPatterns } from './loader';

Expand Down Expand Up @@ -232,6 +233,10 @@ export function getIndexPatternDatasource(chrome: Chrome, toastNotifications: To
isBucketed,
};
},
generateColumnId: () => {
// TODO: Come up with a more compact form of generating unique column ids
return uuid.v4();
},

renderDimensionPanel: (domElement: Element, props: DatasourceDimensionPanelProps) => {
render(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,59 +39,7 @@ describe('native_renderer', () => {
expect(renderSpy).toHaveBeenCalledWith(containerElement, testProps);
});

it('should not render again if props do not change', () => {
const renderSpy = jest.fn();
const testProps = { a: 'abc' };

renderAndTriggerHooks(
<NativeRenderer render={renderSpy} nativeProps={testProps} />,
mountpoint
);
renderAndTriggerHooks(
<NativeRenderer render={renderSpy} nativeProps={testProps} />,
mountpoint
);
expect(renderSpy).toHaveBeenCalledTimes(1);
});

it('should not render again if props do not change shallowly', () => {
const renderSpy = jest.fn();
const testProps = { a: 'abc' };

renderAndTriggerHooks(
<NativeRenderer render={renderSpy} nativeProps={testProps} />,
mountpoint
);
renderAndTriggerHooks(
<NativeRenderer render={renderSpy} nativeProps={{ ...testProps }} />,
mountpoint
);
expect(renderSpy).toHaveBeenCalledTimes(1);
});

it('should not render again for unchanged callback functions', () => {
const renderSpy = jest.fn();
const testCallback = () => {};
const testState = { a: 'abc' };

render(
<NativeRenderer
render={renderSpy}
nativeProps={{ state: testState, setState: testCallback }}
/>,
mountpoint
);
render(
<NativeRenderer
render={renderSpy}
nativeProps={{ state: testState, setState: testCallback }}
/>,
mountpoint
);
expect(renderSpy).toHaveBeenCalledTimes(1);
});

it('should render again once if props change', () => {
it('should render again if props change', () => {
const renderSpy = jest.fn();
const testProps = { a: 'abc' };

Expand All @@ -107,12 +55,12 @@ describe('native_renderer', () => {
<NativeRenderer render={renderSpy} nativeProps={{ a: 'def' }} />,
mountpoint
);
expect(renderSpy).toHaveBeenCalledTimes(2);
expect(renderSpy).toHaveBeenCalledTimes(3);
const containerElement = mountpoint.firstElementChild;
expect(renderSpy).lastCalledWith(containerElement, { a: 'def' });
});

it('should render again once if props is just a string', () => {
it('should render again if props is just a string', () => {
const renderSpy = jest.fn();
const testProps = 'abc';

Expand All @@ -122,7 +70,7 @@ describe('native_renderer', () => {
);
renderAndTriggerHooks(<NativeRenderer render={renderSpy} nativeProps="def" />, mountpoint);
renderAndTriggerHooks(<NativeRenderer render={renderSpy} nativeProps="def" />, mountpoint);
expect(renderSpy).toHaveBeenCalledTimes(2);
expect(renderSpy).toHaveBeenCalledTimes(3);
const containerElement = mountpoint.firstElementChild;
expect(renderSpy).lastCalledWith(containerElement, 'def');
});
Expand Down
57 changes: 2 additions & 55 deletions x-pack/plugins/lens/public/native_renderer/native_renderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,77 +4,24 @@
* you may not use this file except in compliance with the Elastic License.
*/

import React, { useEffect, useRef } from 'react';
import React from 'react';

export interface NativeRendererProps<T> {
render: (domElement: Element, props: T) => void;
nativeProps: T;
tag?: string;
children?: never;
}

function is(x: unknown, y: unknown) {
return (x === y && (x !== 0 || 1 / (x as number) === 1 / (y as number))) || (x !== x && y !== y);
}

function isShallowDifferent<T>(objA: T, objB: T): boolean {
if (is(objA, objB)) {
return false;
}

if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return true;
}

const keysA = Object.keys(objA) as Array<keyof T>;
const keysB = Object.keys(objB) as Array<keyof T>;

if (keysA.length !== keysB.length) {
return true;
}

for (let i = 0; i < keysA.length; i++) {
if (!window.hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return true;
}
}

return false;
}

/**
* A component which takes care of providing a mountpoint for a generic render
* function which takes an html element and an optional props object.
* It also takes care of calling render again if the props object changes.
* By default the mountpoint element will be a div, this can be changed with the
* `tag` prop.
*
* @param props
*/
export function NativeRenderer<T>({ render, nativeProps, tag }: NativeRendererProps<T>) {
const elementRef = useRef<Element | null>(null);
const propsRef = useRef<T | null>(null);

function renderAndUpdate(element: Element) {
elementRef.current = element;
propsRef.current = nativeProps;
render(element, nativeProps);
}

useEffect(
() => {
if (elementRef.current && isShallowDifferent(propsRef.current, nativeProps)) {
renderAndUpdate(elementRef.current);
}
},
[nativeProps]
);

return React.createElement(tag || 'div', {
ref: element => {
if (element && element !== elementRef.current) {
renderAndUpdate(element);
}
},
ref: el => el && render(el, nativeProps),
});
}
1 change: 1 addition & 0 deletions x-pack/plugins/lens/public/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export interface Datasource<T = unknown, P = unknown> {
export interface DatasourcePublicAPI {
getTableSpec: () => TableSpec;
getOperationForColumnId: (columnId: string) => Operation | null;
generateColumnId: () => string;

// Render can be called many times
renderDimensionPanel: (domElement: Element, props: DatasourceDimensionPanelProps) => void;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import {
// @ts-ignore untyped dependency
} from '../../../../../src/legacy/core_plugins/interpreter/public/registries';
import { ExpressionFunction } from '../../../../../src/legacy/core_plugins/interpreter/public';
import { legendConfig, xConfig, yConfig, xyChart, xyChartRenderer } from './xy_expression';
import { xyChart, xyChartRenderer } from './xy_expression';
import { legendConfig, xConfig, yConfig } from './types';

// TODO these are intermediary types because interpreter is not typed yet
// They can get replaced by references to the real interfaces as soon as they
Expand Down
146 changes: 146 additions & 0 deletions x-pack/plugins/lens/public/xy_visualization_plugin/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { Position } from '@elastic/charts';
import {
ExpressionFunction,
ArgumentType,
} from '../../../../../src/legacy/core_plugins/interpreter/public';

export interface LegendConfig {
isVisible: boolean;
position: Position;
}

type LegendConfigResult = LegendConfig & { type: 'lens_xy_legendConfig' };

export const legendConfig: ExpressionFunction<
'lens_xy_legendConfig',
null,
LegendConfig,
LegendConfigResult
> = {
name: 'lens_xy_legendConfig',
aliases: [],
type: 'lens_xy_legendConfig',
help: `Configure the xy chart's legend`,
context: {
types: ['null'],
},
args: {
isVisible: {
types: ['boolean'],
help: 'Specifies whether or not the legend is visible.',
},
position: {
types: ['string'],
options: [Position.Top, Position.Right, Position.Bottom, Position.Left],
help: 'Specifies the legend position.',
},
},
fn: function fn(_context: unknown, args: LegendConfig) {
return {
type: 'lens_xy_legendConfig',
...args,
};
},
};

interface AxisConfig {
title: string;
showGridlines: boolean;
position: Position;
}

const axisConfig: { [key in keyof AxisConfig]: ArgumentType<AxisConfig[key]> } = {
title: {
types: ['string'],
help: 'The axis title',
},
showGridlines: {
types: ['boolean'],
help: 'Show / hide axis grid lines.',
},
position: {
types: ['string'],
options: [Position.Top, Position.Right, Position.Bottom, Position.Left],
help: 'The position of the axis',
},
};

export interface YConfig extends AxisConfig {
accessors: string[];
}

type YConfigResult = YConfig & { type: 'lens_xy_yConfig' };

export const yConfig: ExpressionFunction<'lens_xy_yConfig', null, YConfig, YConfigResult> = {
name: 'lens_xy_yConfig',
aliases: [],
type: 'lens_xy_yConfig',
help: `Configure the xy chart's y axis`,
context: {
types: ['null'],
},
args: {
...axisConfig,
accessors: {
types: ['string'],
help: 'The columns to display on the y axis.',
multi: true,
},
},
fn: function fn(_context: unknown, args: YConfig) {
return {
type: 'lens_xy_yConfig',
...args,
};
},
};

export interface XConfig extends AxisConfig {
accessor: string;
}

type XConfigResult = XConfig & { type: 'lens_xy_xConfig' };

export const xConfig: ExpressionFunction<'lens_xy_xConfig', null, XConfig, XConfigResult> = {
name: 'lens_xy_xConfig',
aliases: [],
type: 'lens_xy_xConfig',
help: `Configure the xy chart's x axis`,
context: {
types: ['null'],
},
args: {
...axisConfig,
accessor: {
types: ['string'],
help: 'The column to display on the x axis.',
},
},
fn: function fn(_context: unknown, args: XConfig) {
return {
type: 'lens_xy_xConfig',
...args,
};
},
};

export type SeriesType = 'bar' | 'horizontal_bar' | 'line' | 'area';

export interface XYArgs {
seriesType: SeriesType;
title: string;
legend: LegendConfig;
y: YConfig;
x: XConfig;
splitSeriesAccessors: string[];
stackAccessors: string[];
}

export type State = XYArgs;
export type PersistableState = XYArgs;
Loading

0 comments on commit 717eaff

Please sign in to comment.