Skip to content

Commit

Permalink
[Security Solution][Lens] New trigger actions for chart legends and t…
Browse files Browse the repository at this point in the history
…able cell actions (#146779)

## Summary

Enable XY chart legends and Table cell actions to render dynamically
registered "cell value" actions, scoped for Lens embeddables only.
Security Solution actions were created to be displayed in the Lens
visualizations rendered.

closes #145708

### New Trigger

A new _uiActions_ trigger `CELL_VALUE_TRIGGER` has been created to
register these actions. It is used in both _TableChart_ cell actions and
_XyCharts_ legend actions to create additional action options.

#### Table cell actions

Actions registered and added to the `CELL_VALUE_TRIGGER` will be
appended to the cell actions of the table. The action compatibility is
checked for each column.


![table_cell_actions](https://user-images.githubusercontent.com/17747913/205046554-d4ccf5c5-e49a-44e5-8567-4f39756f3fef.png)


#### Chart legend actions

The same for XyCharts legends. All actions registered and added to the
`CELL_VALUE_TRIGGER` will be appended to the legend actions of the
charts. The action compatibility is checked for each series accessor.


![chart_legend_actions](https://user-images.githubusercontent.com/17747913/205046313-cd50481c-1a06-4bf7-a8fd-b387a98857c1.png)

#### Filter for & Filter out actions:

The XY and Table charts have the "Filter for & Filter out" actions
hardcoded in the components code. They manually check the value is
filterable before showing the actions, but the panel items and cell
actions are added explicitly for them in the components.

This logic has not changed in this PR, the actions added dynamically
using `CELL_VALUE_TRIGGER` are just appended after the "Filter for &
Filter out" options.

However, "Filter for / Filter out" actions could also be integrated into
this pattern, we would only have to register these actions to the
`CELL_VALUE_TRIGGER` with the proper `order` value, and then remove all
hardcoded logic in the components.

### Security Solution actions

The actions that we have registered from Security Solutions ("Add to
timeline" and "Copy to clipboard") will be displayed only when the
embeddable is rendered inside Security Solution, this is ensured via the
`isCompatible` actions method.


![security_actions](https://user-images.githubusercontent.com/17747913/205046643-6ea7e849-b3d6-43f3-91c8-034050375623.png)

### Security Solution Filter In/Out bug

There was a CSS rule present in a global Security Solution context,
affecting all the `EuiDataGrid` cell actions popovers:


https://github.com/elastic/kibana/blob/475e47ed993fba0ecd69caa211150f298e1eefe4/x-pack/plugins/security_solution/public/common/components/page/index.tsx#L124-L130

The goal of this rule was to save some vertical space, by hiding the two
auto-generated Filter In/Out actions (generally the first two cell
actions), so we could show the horizontal Filter In/Out custom buttons
added manually to the popover top header.


![old_filter_in_out](https://user-images.githubusercontent.com/17747913/205293269-aa1e6409-a809-4328-8079-ef1e09c0750d.png)

This CSS rule was causing a bug when rendering Table visualizations
(they use `EuiDataGrid` as well), always hiding the two first cell
actions in the popover.

After discussing this topic with the team, and considering there is an
ongoing task to unify the cell actions experience in Security and
centralize the implementation (see:
#144943), we decided to remove
the problematic CSS rule and the custom horizontal Filter buttons, so
the auto-generated Filter actions are displayed, this way all tables in
Security (alerts, events, and also embedded table charts) will have a
unified and consistent UX.


![new_filter_in_out](https://user-images.githubusercontent.com/17747913/205293120-3bf27a8a-90dd-47dd-a14e-d92570bff84f.png)

If the cell actions popover grows too much in the future we could apply
a "More actions ..." footer option strategy.

## Testing

The new actions will be displayed on any embedded Lens object rendered
inside Security. A good place to test that is Cases, since we can attach
Lens visualizations in the comments. However, Cases explicitly disables
all the trigger actions passing `disableTriggers` to the Lens
Embeddables.


https://github.com/elastic/kibana/blob/b80a23ee125cc4612b99e0b24e6ff2b55ebbdf55/x-pack/plugins/cases/public/components/markdown_editor/plugins/lens/processor.tsx#L52

The easiest way to test different chart types and tables is to
remove/comment the `disableTriggers` prop in the Cases processor
component, and then go to a Case and attach different Lens
visualizations. All actions should appear in the legends and table cell
hover actions.


### Checklist

- [x] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [x] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [x] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))

Co-authored-by: kibanamachine <[email protected]>
Co-authored-by: Angela Chuang <[email protected]>
  • Loading branch information
3 people authored Dec 16, 2022
1 parent c3a8b26 commit d8318ed
Show file tree
Hide file tree
Showing 53 changed files with 1,663 additions and 274 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ describe('PartitionVisComponent', function () {
syncColors: false,
fireEvent: jest.fn(),
renderComplete: jest.fn(),
interactive: true,
columnCellValueActions: [],
services: {
data: dataPluginMock.createStartContract(),
fieldFormats: fieldFormatsServiceMock.createStartContract(),
Expand Down Expand Up @@ -172,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 @@ -68,7 +68,7 @@ import {
} from './partition_vis_component.styles';
import { ChartTypes } from '../../common/types';
import { filterOutConfig } from '../utils/filter_out_config';
import { FilterEvent, StartDeps } from '../types';
import { ColumnCellValueActions, FilterEvent, StartDeps } from '../types';

declare global {
interface Window {
Expand All @@ -85,19 +85,23 @@ export interface PartitionVisComponentProps {
uiState: PersistedState;
fireEvent: IInterpreterRenderHandlers['event'];
renderComplete: IInterpreterRenderHandlers['done'];
interactive: boolean;
chartsThemeService: ChartsPluginSetup['theme'];
palettesRegistry: PaletteRegistry;
services: Pick<StartDeps, 'data' | 'fieldFormats'>;
syncColors: boolean;
columnCellValueActions: ColumnCellValueActions;
}

const PartitionVisComponent = (props: PartitionVisComponentProps) => {
const {
columnCellValueActions,
visData: originalVisData,
visParams: preVisParams,
visType,
services,
syncColors,
interactive,
} = props;
const visParams = useMemo(() => filterOutConfig(visType, preVisParams), [preVisParams, visType]);
const chartTheme = props.chartsThemeService.useChartsTheme();
Expand Down Expand Up @@ -313,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 @@ -446,15 +476,7 @@ const PartitionVisComponent = (props: PartitionVisComponentProps) => {
splitChartFormatter
);
}}
legendAction={getLegendActions(
canFilter,
getLegendActionEventData(visData),
handleLegendAction,
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,14 +11,20 @@ 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 type {
Datatable,
ExpressionRenderDefinition,
IInterpreterRenderHandlers,
} 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';

Expand All @@ -42,6 +48,30 @@ const partitionVisRenderer = css({
height: '100%',
});

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

export const getPartitionVisRenderer: (
deps: VisTypePieDependencies
) => ExpressionRenderDefinition<RenderValue> = ({ getStartDeps }) => ({
Expand Down Expand Up @@ -76,7 +106,10 @@ export const getPartitionVisRenderer: (
handlers.done();
};

const palettesRegistry = await plugins.charts.palettes.getPalettes();
const [columnCellValueActions, palettesRegistry] = await Promise.all([
getColumnCellValueActions(visConfig, visData, handlers.getCompatibleCellValueActions),
plugins.charts.palettes.getPalettes(),
]);

render(
<I18nProvider>
Expand All @@ -90,9 +123,11 @@ 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}
columnCellValueActions={columnCellValueActions}
/>
</div>
</KibanaThemeProvider>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { ValueClickContext } from '@kbn/embeddable-plugin/public';
import type { CellValueContext, ValueClickContext } from '@kbn/embeddable-plugin/public';
import { ChartsPluginSetup, ChartsPluginStart } from '@kbn/charts-plugin/public';
import {
Plugin as ExpressionsPublicPlugin,
Expand Down Expand Up @@ -35,3 +35,16 @@ export interface FilterEvent {
name: 'filter';
data: ValueClickContext['data'];
}

export interface CellValueAction {
id: string;
iconType: string;
displayName: string;
execute: (data: CellValueContext['data']) => void;
}

export type ColumnCellValueActions = CellValueAction[][];

export type GetCompatibleCellValueActions = (
data: CellValueContext['data']
) => Promise<CellValueAction[]>;
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,7 @@ export const getFilterEventData = (
return acc;
}, []);
};

export const getSeriesValueColumnIndex = (value: string, visData: Datatable): number => {
return visData.columns.findIndex(({ id }) => !!visData.rows.find((r) => r[id] === value));
};
Loading

0 comments on commit d8318ed

Please sign in to comment.