Skip to content

Commit

Permalink
added interative conditionals + tests
Browse files Browse the repository at this point in the history
  • Loading branch information
semd committed Dec 14, 2022
1 parent 41cca66 commit f60c338
Show file tree
Hide file tree
Showing 7 changed files with 190 additions and 52 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ describe('PartitionVisComponent', function () {
syncColors: false,
fireEvent: jest.fn(),
renderComplete: jest.fn(),
interactive: true,
columnCellValueActions: [],
services: {
data: dataPluginMock.createStartContract(),
Expand Down Expand Up @@ -173,6 +174,16 @@ describe('PartitionVisComponent', function () {
});
});

it('should render legend actions when it is interactive', async () => {
const component = shallow(<PartitionVisComponent {...wrapperProps} interactive={true} />);
expect(component.find(Settings).prop('legendAction')).toBeDefined();
});

it('should not render legend actions when it is not interactive', async () => {
const component = shallow(<PartitionVisComponent {...wrapperProps} interactive={false} />);
expect(component.find(Settings).prop('legendAction')).toBeUndefined();
});

it('hides the legend if the legend toggle is clicked', async () => {
const component = mountWithIntl(<PartitionVisComponent {...wrapperProps} />);
await actWithTimeout(async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ export interface PartitionVisComponentProps {
uiState: PersistedState;
fireEvent: IInterpreterRenderHandlers['event'];
renderComplete: IInterpreterRenderHandlers['done'];
interactive: boolean;
chartsThemeService: ChartsPluginSetup['theme'];
palettesRegistry: PaletteRegistry;
services: Pick<StartDeps, 'data' | 'fieldFormats'>;
Expand All @@ -100,6 +101,7 @@ const PartitionVisComponent = (props: PartitionVisComponentProps) => {
visType,
services,
syncColors,
interactive,
} = props;
const visParams = useMemo(() => filterOutConfig(visType, preVisParams), [preVisParams, visType]);
const chartTheme = props.chartsThemeService.useChartsTheme();
Expand Down Expand Up @@ -315,6 +317,32 @@ const PartitionVisComponent = (props: PartitionVisComponentProps) => {
]
);

const legendActions = useMemo(
() =>
interactive
? getLegendActions(
canFilter,
getLegendActionEventData(visData),
handleLegendAction,
columnCellValueActions,
visParams,
visData,
services.data.actions,
services.fieldFormats
)
: undefined,
[
columnCellValueActions,
getLegendActionEventData,
handleLegendAction,
interactive,
services.data.actions,
services.fieldFormats,
visData,
visParams,
]
);

const rescaleFactor = useMemo(() => {
const overallSum = visData.rows.reduce((sum, row) => sum + row[metricColumn.id], 0);
const slices = visData.rows.map((row) => row[metricColumn.id] / overallSum);
Expand Down Expand Up @@ -448,16 +476,7 @@ const PartitionVisComponent = (props: PartitionVisComponentProps) => {
splitChartFormatter
);
}}
legendAction={getLegendActions(
canFilter,
getLegendActionEventData(visData),
handleLegendAction,
columnCellValueActions,
visParams,
visData,
services.data.actions,
services.fieldFormats
)}
legendAction={legendActions}
theme={[
// Chart background should be transparent for the usage at Canvas.
{ background: { color: 'transparent' } },
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { createMockPieParams, createMockVisData } from '../mocks';
import { CellValueAction } from '../types';
import { getColumnCellValueActions } from './partition_vis_renderer';

const visParams = createMockPieParams();
const visData = createMockVisData();

const cellValueAction: CellValueAction = {
displayName: 'Test',
id: 'test',
iconType: 'test-icon',
execute: () => {},
};

describe('getColumnCellValueActions', () => {
it('should get column cellValue actions for each params bucket', async () => {
const result = await getColumnCellValueActions(visParams, visData, async () => [
cellValueAction,
]);
expect(result).toHaveLength(visParams.dimensions.buckets?.length ?? 0);
});

it('should contain the cellValue actions', async () => {
const result = await getColumnCellValueActions(visParams, visData, async () => [
cellValueAction,
cellValueAction,
]);
expect(result[0]).toEqual([cellValueAction, cellValueAction]);
});

it('should return empty array if no buckets', async () => {
const result = await getColumnCellValueActions(
{ ...visParams, dimensions: { ...visParams.dimensions, buckets: undefined } },
visData,
async () => [cellValueAction]
);
expect(result).toEqual([]);
});

it('should return empty array if getCompatibleCellValueActions not passed', async () => {
const result = await getColumnCellValueActions(visParams, visData, undefined);
expect(result).toEqual([]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,18 @@ import { render, unmountComponentAtNode } from 'react-dom';
import { I18nProvider } from '@kbn/i18n-react';
import { css } from '@emotion/react';
import { i18n } from '@kbn/i18n';
import { ExpressionRenderDefinition } from '@kbn/expressions-plugin/public';
import { Datatable, ExpressionRenderDefinition } from '@kbn/expressions-plugin/public';
import type { PersistedState } from '@kbn/visualizations-plugin/public';
import { withSuspense } from '@kbn/presentation-util-plugin/public';
import { KibanaThemeProvider } from '@kbn/kibana-react-plugin/public';
import { METRIC_TYPE } from '@kbn/analytics';
import { getColumnByAccessor } from '@kbn/visualizations-plugin/common/utils';
import { VisTypePieDependencies } from '../plugin';
import { PARTITION_VIS_RENDERER_NAME } from '../../common/constants';
import { ChartTypes, RenderValue } from '../../common/types';
import { CellValueAction, GetCompatibleCellValueActions } from '../types';
import { ChartTypes, PartitionVisParams, RenderValue } from '../../common/types';
// eslint-disable-next-line @kbn/imports/no_boundary_crossing
import { extractContainerType, extractVisualizationType } from '../../../common';
import { CellValueAction, ColumnCellValueActions } from '../types';

export const strings = {
getDisplayName: () =>
Expand All @@ -44,6 +44,28 @@ const partitionVisRenderer = css({
height: '100%',
});

/**
* Retrieves the compatible CELL_VALUE_TRIGGER actions indexed by column
**/
export const getColumnCellValueActions = async (
visConfig: PartitionVisParams,
visData: Datatable,
getCompatibleCellValueActions: GetCompatibleCellValueActions | undefined
) => {
if (!Array.isArray(visConfig.dimensions.buckets) || !getCompatibleCellValueActions) {
return [];
}
return Promise.all(
visConfig.dimensions.buckets.reduce<Array<Promise<CellValueAction[]>>>((acc, accessor) => {
const column = getColumnByAccessor(accessor, visData.columns);
if (column) {
acc.push(getCompatibleCellValueActions([{ columnMeta: column.meta }]));
}
return acc;
}, [])
);
};

export const getPartitionVisRenderer: (
deps: VisTypePieDependencies
) => ExpressionRenderDefinition<RenderValue> = ({ getStartDeps }) => ({
Expand All @@ -62,24 +84,11 @@ export const getPartitionVisRenderer: (
unmountComponentAtNode(domNode);
});

const { getCompatibleCellValueActions } = handlers;
let columnCellValueActions: ColumnCellValueActions = [];

if (getCompatibleCellValueActions && Array.isArray(visConfig.dimensions.buckets)) {
columnCellValueActions = await Promise.all(
visConfig.dimensions.buckets.reduce<Array<Promise<CellValueAction[]>>>((acc, accessor) => {
const column = getColumnByAccessor(accessor, visData.columns);
if (column) {
acc.push(
getCompatibleCellValueActions([{ columnMeta: column.meta }]) as Promise<
CellValueAction[]
>
);
}
return acc;
}, [])
);
}
const columnCellValueActions = await getColumnCellValueActions(
visConfig,
visData,
handlers.getCompatibleCellValueActions as GetCompatibleCellValueActions
);

const renderComplete = () => {
const executionContext = handlers.getExecutionContext();
Expand Down Expand Up @@ -111,6 +120,7 @@ export const getPartitionVisRenderer: (
visType={visConfig.isDonut ? ChartTypes.DONUT : visType}
renderComplete={renderComplete}
fireEvent={handlers.event}
interactive={handlers.isInteractive()}
uiState={handlers.uiState as PersistedState}
services={{ data: plugins.data, fieldFormats: plugins.fieldFormats }}
syncColors={syncColors}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,11 @@ export const DatatableComponent = (props: DatatableRenderProps) => {
[firstTableRef, onClickValue, isInteractive]
);

const columnCellValueActions = useMemo(
() => (isInteractive ? props.columnCellValueActions : undefined),
[props.columnCellValueActions, isInteractive]
);

const handleTransposedColumnClick = useMemo(
() =>
isInteractive
Expand Down Expand Up @@ -310,7 +315,7 @@ export const DatatableComponent = (props: DatatableRenderProps) => {
alignments,
headerRowHeight,
headerRowLines,
props.columnCellValueActions,
columnCellValueActions,
dataGridRef.current?.closeCellPopover,
props.columnFilterable
),
Expand All @@ -328,8 +333,8 @@ export const DatatableComponent = (props: DatatableRenderProps) => {
alignments,
headerRowHeight,
headerRowLines,
columnCellValueActions,
props.columnFilterable,
props.columnCellValueActions,
]
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,20 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import type { DatatableProps } from '../../../common/expressions';
import { createMockExecutionContext } from '@kbn/expressions-plugin/common/mocks';
import type { DatatableProps } from '../../../common/expressions';
import type { FormatFactory } from '../../../common';
import { getDatatable } from '../../../common/expressions';
import { getColumnCellValueActions } from './expression';
import type { Datatable } from '@kbn/expressions-plugin/common';
import { LensCellValueAction } from '../../types';

const cellValueAction: LensCellValueAction = {
displayName: 'Test',
id: 'test',
iconType: 'test-icon',
execute: () => {},
};
function sampleArgs() {
const indexPatternId = 'indexPatternId';
const data: Datatable = {
Expand Down Expand Up @@ -93,4 +100,26 @@ describe('datatable_expression', () => {
});
});
});

describe('getColumnCellValueActions', () => {
it('should return column cell value actions', async () => {
const config = sampleArgs();
const result = await getColumnCellValueActions(config, async () => [cellValueAction]);
expect(result).toEqual([[cellValueAction], [cellValueAction], [cellValueAction]]);
});

it('should return empty actions if no data passed', async () => {
const result = await getColumnCellValueActions(
{ data: null } as unknown as DatatableProps,
async () => [cellValueAction]
);
expect(result).toEqual([]);
});

it('should return empty actions if no getCompatibleCellValueActions handler passed', async () => {
const config = sampleArgs();
const result = await getColumnCellValueActions(config, undefined);
expect(result).toEqual([]);
});
});
});
47 changes: 30 additions & 17 deletions x-pack/plugins/lens/public/visualizations/datatable/expression.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ import { KibanaThemeProvider } from '@kbn/kibana-react-plugin/public';
import { trackUiCounterEvents } from '../../lens_ui_telemetry';
import { DatatableComponent } from './components/table_basic';

import type { ILensInterpreterRenderHandlers, LensCellValueAction } from '../../types';
import type {
GetCompatibleCellValueActions,
ILensInterpreterRenderHandlers,
LensCellValueAction,
} from '../../types';
import type { FormatFactory } from '../../../common';
import type { DatatableProps } from '../../../common/expressions';

Expand Down Expand Up @@ -49,6 +53,27 @@ async function columnsFilterable(table: Datatable, handlers: IInterpreterRenderH
);
}

/**
* Retrieves the compatible CELL_VALUE_TRIGGER actions indexed by column
**/
export async function getColumnCellValueActions(
config: DatatableProps,
getCompatibleCellValueActions: GetCompatibleCellValueActions | undefined
): Promise<LensCellValueAction[][]> {
if (!config.data || !getCompatibleCellValueActions) {
return [];
}
return Promise.all(
config.data.columns.map(({ meta: columnMeta }) => {
try {
return getCompatibleCellValueActions([{ columnMeta }]);
} catch {
return [];
}
})
);
}

export const getDatatableRenderer = (dependencies: {
formatFactory: FormatFactory;
getType: Promise<(name: string) => IAggType>;
Expand Down Expand Up @@ -104,22 +129,10 @@ export const getDatatableRenderer = (dependencies: {
}
}

let columnCellValueActions: LensCellValueAction[][] = [];
if (getCompatibleCellValueActions) {
if (!!config.data) {
columnCellValueActions = await Promise.all(
config.data.columns.map(({ meta: columnMeta }) => {
try {
return getCompatibleCellValueActions([{ columnMeta }]) as Promise<
LensCellValueAction[]
>;
} catch {
return [];
}
})
);
}
}
const columnCellValueActions = await getColumnCellValueActions(
config,
getCompatibleCellValueActions as GetCompatibleCellValueActions | undefined
);

ReactDOM.render(
<KibanaThemeProvider theme$={dependencies.theme.theme$}>
Expand Down

0 comments on commit f60c338

Please sign in to comment.