Skip to content

Commit

Permalink
[Lens] Avoid to change sub chart type on field drop for multiple laye…
Browse files Browse the repository at this point in the history
…rs (#157871)

## Summary

Fixed #156504 

This PR adds the support for mixed chart types on field drop scenario,
without breaking the chart switch suggestion logic.


![lens_mixed_support](https://github.com/elastic/kibana/assets/924948/3e9aba9c-2190-409f-91e8-4c582a0dbce3)


### Checklist

Delete any items that are not applicable to this PR.

- [ ] 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)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [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
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces—unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes—Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

Co-authored-by: Stratoula Kalafateli <efstratia.kalafateli@elastic.co>
  • Loading branch information
dej611 and stratoula authored May 17, 2023
1 parent 94c9491 commit 4eccf31
Show file tree
Hide file tree
Showing 5 changed files with 97 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ export function EditorFrame(props: EditorFrameProps) {
visualizationMap,
datasourceMap[activeDatasourceId],
field,
framePublicAPI.dataViews
framePublicAPI.dataViews,
true
);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export function getSuggestions({
activeData,
dataViews,
mainPalette,
allowMixed,
}: {
datasourceMap: DatasourceMap;
datasourceStates: DatasourceStates;
Expand All @@ -65,6 +66,7 @@ export function getSuggestions({
activeData?: Record<string, Datatable>;
dataViews: DataViewsState;
mainPalette?: PaletteOutput;
allowMixed?: boolean;
}): Suggestion[] {
const datasources = Object.entries(datasourceMap).filter(
([datasourceId]) => datasourceStates[datasourceId] && !datasourceStates[datasourceId].isLoading
Expand Down Expand Up @@ -164,7 +166,8 @@ export function getSuggestions({
subVisualizationId,
palette,
visualizeTriggerFieldContext && 'isVisualizeAction' in visualizeTriggerFieldContext,
activeData
activeData,
allowMixed
);
});
})
Expand Down Expand Up @@ -233,7 +236,8 @@ function getVisualizationSuggestions(
subVisualizationId?: string,
mainPalette?: PaletteOutput,
isFromContext?: boolean,
activeData?: Record<string, Datatable>
activeData?: Record<string, Datatable>,
allowMixed?: boolean
) {
try {
return visualization
Expand All @@ -245,6 +249,7 @@ function getVisualizationSuggestions(
mainPalette,
isFromContext,
activeData,
allowMixed,
})
.map(({ state, ...visualizationSuggestion }) => ({
...visualizationSuggestion,
Expand Down Expand Up @@ -296,7 +301,8 @@ export function getTopSuggestionForField(
visualizationMap: Record<string, Visualization<unknown>>,
datasource: Datasource,
field: DragDropIdentifier,
dataViews: DataViewsState
dataViews: DataViewsState,
allowMixed?: boolean
) {
const hasData = Object.values(datasourceLayers).some(
(datasourceLayer) => datasourceLayer && datasourceLayer.getTableSpec().length > 0
Expand All @@ -319,6 +325,7 @@ export function getTopSuggestionForField(
field,
mainPalette,
dataViews,
allowMixed,
});
return (
suggestions.find((s) => s.visualizationId === visualization.activeId) ||
Expand Down
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 @@ -897,6 +897,7 @@ export interface SuggestionRequest<T = unknown> {
*/
subVisualizationId?: string;
activeData?: Record<string, Datatable>;
allowMixed?: boolean;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,69 @@ describe('xy_suggestions', () => {
]);
});

test('suggests mixed xy chart keeping original subType when switching from another x y chart with multiple layers', () => {
(generateId as jest.Mock).mockReturnValueOnce('aaa');
const suggestions = getSuggestions({
allowMixed: true,
table: {
isMultiRow: true,
columns: [numCol('bytes'), dateCol('date')],
layerId: 'first',
changeType: 'unchanged',
},
keptLayerIds: ['first', 'second'],
state: {
legend: { isVisible: true, position: 'bottom' },
valueLabels: 'hide',
preferredSeriesType: 'bar',
layers: [
{
layerId: 'first',
layerType: LayerTypes.DATA,
seriesType: 'bar',
xAccessor: 'date',
accessors: ['bytes'],
splitAccessor: undefined,
},
{
layerId: 'second',
layerType: LayerTypes.DATA,
seriesType: 'line',
xAccessor: undefined,
accessors: [],
splitAccessor: undefined,
},
],
},
});

expect(suggestions).toHaveLength(visualizationTypes.length);
expect(suggestions.map(({ state }) => xyVisualization.getVisualizationTypeId(state))).toEqual([
'line', // line + line = line
'mixed', // any other combination is mixed
'mixed',
'mixed',
'mixed',
'mixed',
'mixed',
'mixed',
'mixed',
'mixed',
]);
expect(suggestions.map(({ state }) => state.layers.map((l) => l.layerId))).toEqual([
['first', 'second'],
['first', 'second'],
['first', 'second'],
['first', 'second'],
['first', 'second'],
['first', 'second'],
['first', 'second'],
['first', 'second'],
['first', 'second'],
['first', 'second'],
]);
});

test('suggests all basic x y chart with date on x', () => {
(generateId as jest.Mock).mockReturnValueOnce('aaa');
const [suggestion, ...rest] = getSuggestions({
Expand Down
28 changes: 21 additions & 7 deletions x-pack/plugins/lens/public/visualizations/xy/xy_suggestions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export function getSuggestions({
subVisualizationId,
mainPalette,
isFromContext,
allowMixed,
}: SuggestionRequest<State>): Array<VisualizationSuggestion<State>> {
const incompleteTable =
!table.isMultiRow ||
Expand All @@ -79,10 +80,11 @@ export function getSuggestions({
keptLayerIds,
state,
subVisualizationId as SeriesType | undefined,
mainPalette
mainPalette,
allowMixed
);

if (suggestions && suggestions instanceof Array) {
if (Array.isArray(suggestions)) {
return suggestions;
}

Expand All @@ -94,7 +96,8 @@ function getSuggestionForColumns(
keptLayerIds: string[],
currentState?: State,
seriesType?: SeriesType,
mainPalette?: PaletteOutput
mainPalette?: PaletteOutput,
allowMixed?: boolean
): VisualizationSuggestion<State> | Array<VisualizationSuggestion<State>> | undefined {
const [buckets, values] = partition(table.columns, (col) => col.operation.isBucketed);

Expand All @@ -111,6 +114,7 @@ function getSuggestionForColumns(
keptLayerIds,
requestedSeriesType: seriesType,
mainPalette,
allowMixed,
});
} else if (buckets.length === 0) {
const [yValues, [xValue, splitBy]] = partition(
Expand All @@ -128,6 +132,7 @@ function getSuggestionForColumns(
keptLayerIds,
requestedSeriesType: seriesType,
mainPalette,
allowMixed,
});
}
}
Expand Down Expand Up @@ -214,6 +219,7 @@ function getSuggestionsForLayer({
keptLayerIds,
requestedSeriesType,
mainPalette,
allowMixed,
}: {
layerId: string;
changeType: TableChangeType;
Expand All @@ -225,6 +231,7 @@ function getSuggestionsForLayer({
keptLayerIds: string[];
requestedSeriesType?: SeriesType;
mainPalette?: PaletteOutput;
allowMixed?: boolean;
}): VisualizationSuggestion<State> | Array<VisualizationSuggestion<State>> {
const title = getSuggestionTitle(yValues, xValue, tableLabel);
const seriesType: SeriesType =
Expand All @@ -242,6 +249,7 @@ function getSuggestionsForLayer({
keptLayerIds,
// only use palette if there is a breakdown by dimension
mainPalette: splitBy ? mainPalette : undefined,
allowMixed,
};

// handles the simplest cases, acting as a chart switcher
Expand Down Expand Up @@ -473,6 +481,7 @@ function buildSuggestion({
keptLayerIds,
hide,
mainPalette,
allowMixed,
}: {
currentState: XYState | undefined;
seriesType: SeriesType;
Expand All @@ -485,6 +494,7 @@ function buildSuggestion({
keptLayerIds: string[];
hide?: boolean;
mainPalette?: PaletteOutput;
allowMixed?: boolean;
}) {
if (seriesType.includes('percentage') && xValue?.operation.scale === 'ordinal' && !splitBy) {
splitBy = xValue;
Expand Down Expand Up @@ -526,10 +536,14 @@ function buildSuggestion({
// Update in place
.map((layer) => (layer.layerId === layerId ? newLayer : layer))
// Replace the seriesType on all previous layers
.map((layer) => ({
...layer,
seriesType,
}))
.map((layer) =>
allowMixed
? layer
: {
...layer,
seriesType,
}
)
: [];

const state: State = {
Expand Down

0 comments on commit 4eccf31

Please sign in to comment.