Skip to content

Commit

Permalink
[Lens] Mosaic / mekko vis type (#117668)
Browse files Browse the repository at this point in the history
* [Lens] Mosaic / mekko vis type

Closes: #104223

* some updates

* fix color palette logic

* fix suggestions

* fix JEST

* fix some parts

* update labels

* Fix JEST

* add showExperimentalBadge

* add sorting

* fix toolbar options

* fix Marco suggestion

Co-authored-by: Kibana Machine <[email protected]>
  • Loading branch information
2 people authored and dmlemeshko committed Nov 29, 2021
1 parent 1d5d921 commit 47e8a7b
Show file tree
Hide file tree
Showing 16 changed files with 753 additions and 173 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const pie: ExpressionFunctionDefinition<
},
shape: {
types: ['string'],
options: ['pie', 'donut', 'treemap'],
options: ['pie', 'donut', 'treemap', 'mosaic'],
help: '',
},
hideLabels: {
Expand Down
6 changes: 4 additions & 2 deletions x-pack/plugins/lens/common/expressions/pie_chart/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import type { PaletteOutput } from '../../../../../../src/plugins/charts/common';
import type { LensMultiTable, LayerType } from '../../types';

export type PieChartTypes = 'donut' | 'pie' | 'treemap' | 'mosaic';

export interface SharedPieLayerState {
groups: string[];
metric?: string;
Expand All @@ -27,15 +29,15 @@ export type PieLayerState = SharedPieLayerState & {
};

export interface PieVisualizationState {
shape: 'donut' | 'pie' | 'treemap';
shape: PieChartTypes;
layers: PieLayerState[];
palette?: PaletteOutput;
}

export type PieExpressionArgs = SharedPieLayerState & {
title?: string;
description?: string;
shape: 'pie' | 'donut' | 'treemap';
shape: PieChartTypes;
hideLabels: boolean;
palette: PaletteOutput;
};
Expand Down
31 changes: 31 additions & 0 deletions x-pack/plugins/lens/public/assets/chart_mosaic.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* 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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React from 'react';
import type { EuiIconProps } from '@elastic/eui';

export const LensIconChartMosaic = ({ title, titleId, ...props }: Omit<EuiIconProps, 'type'>) => (
<svg
viewBox="0 0 30 22"
width={30}
height={22}
fill="none"
xmlns="http://www.w3.org/2000/svg"
aria-labelledby={titleId}
{...props}
>
{title ? <title id={titleId} /> : null}
<path
className="lensChartIcon__subdued"
d="M2 0a1 1 0 00-1 1v2a1 1 0 001 1h6a1 1 0 001-1V1a1 1 0 00-1-1H2zM2 14a1 1 0 00-1 1v6a1 1 0 001 1h6a1 1 0 001-1v-6a1 1 0 00-1-1H2zM11 13a1 1 0 011-1h6a1 1 0 011 1v8a1 1 0 01-1 1h-6a1 1 0 01-1-1v-8zM12 0a1 1 0 100 2h6a1 1 0 100-2h-6zM21 15a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1h-6a1 1 0 01-1-1v-6zM22 0a1 1 0 00-1 1v4a1 1 0 001 1h6a1 1 0 001-1V1a1 1 0 00-1-1h-6z"
/>
<path
className="lensChartIcon__accent"
d="M11 5a1 1 0 011-1h6a1 1 0 011 1v4a1 1 0 01-1 1h-6a1 1 0 01-1-1V5zM1 7a1 1 0 011-1h6a1 1 0 011 1v4a1 1 0 01-1 1H2a1 1 0 01-1-1V7zM22 8a1 1 0 00-1 1v2a1 1 0 001 1h6a1 1 0 001-1V9a1 1 0 00-1-1h-6z"
/>
</svg>
);
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,39 @@ describe('LayerPanel', () => {

const group = instance
.find(EuiFormRow)
.findWhere((e) => e.prop('error') === 'Required dimension');
.findWhere((e) => e.prop('error') === 'Requires field');

expect(group).toHaveLength(1);
});

it('should render the required warning when only one group is configured (with requiredMinDimensionCount)', async () => {
mockVisualization.getConfiguration.mockReturnValue({
groups: [
{
groupLabel: 'A',
groupId: 'a',
accessors: [{ columnId: 'x' }],
filterOperations: () => true,
supportsMoreColumns: false,
dataTestSubj: 'lnsGroup',
},
{
groupLabel: 'B',
groupId: 'b',
accessors: [{ columnId: 'y' }],
filterOperations: () => true,
supportsMoreColumns: true,
dataTestSubj: 'lnsGroup',
requiredMinDimensionCount: 2,
},
],
});

const { instance } = await mountWithProvider(<LayerPanel {...getDefaultProps()} />);

const group = instance
.find(EuiFormRow)
.findWhere((e) => e.prop('error') === 'Requires 2 fields');

expect(group).toHaveLength(1);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,27 @@ export function LayerPanel(
</header>

{groups.map((group, groupIndex) => {
const isMissing = !isEmptyLayer && group.required && group.accessors.length === 0;
let isMissing = false;

if (!isEmptyLayer) {
if (group.requiredMinDimensionCount) {
isMissing = group.accessors.length < group.requiredMinDimensionCount;
} else if (group.required) {
isMissing = group.accessors.length === 0;
}
}

const isMissingError = group.requiredMinDimensionCount
? i18n.translate('xpack.lens.editorFrame.requiresTwoOrMoreFieldsWarningLabel', {
defaultMessage: 'Requires {requiredMinDimensionCount} fields',
values: {
requiredMinDimensionCount: group.requiredMinDimensionCount,
},
})
: i18n.translate('xpack.lens.editorFrame.requiresFieldWarningLabel', {
defaultMessage: 'Requires field',
});

const isOptional = !group.required;
return (
<EuiFormRow
Expand Down Expand Up @@ -423,13 +443,7 @@ export function LayerPanel(
labelType="legend"
key={group.groupId}
isInvalid={isMissing}
error={
isMissing
? i18n.translate('xpack.lens.editorFrame.requiredDimensionWarningLabel', {
defaultMessage: 'Required dimension',
})
: []
}
error={isMissing ? isMissingError : []}
>
<>
{group.accessors.length ? (
Expand Down
63 changes: 61 additions & 2 deletions x-pack/plugins/lens/public/pie_visualization/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,41 +6,100 @@
*/

import { i18n } from '@kbn/i18n';
import { PartitionLayout } from '@elastic/charts';
import { LensIconChartDonut } from '../assets/chart_donut';
import { LensIconChartPie } from '../assets/chart_pie';
import { LensIconChartTreemap } from '../assets/chart_treemap';
import { LensIconChartMosaic } from '../assets/chart_mosaic';

import type { SharedPieLayerState } from '../../common/expressions';

interface CategoryOption {
value: SharedPieLayerState['categoryDisplay'];
inputDisplay: string;
}

const groupLabel = i18n.translate('xpack.lens.pie.groupLabel', {
defaultMessage: 'Proportion',
});

const categoryOptions: CategoryOption[] = [
{
value: 'default',
inputDisplay: i18n.translate('xpack.lens.pieChart.showCategoriesLabel', {
defaultMessage: 'Inside or outside',
}),
},
{
value: 'inside',
inputDisplay: i18n.translate('xpack.lens.pieChart.fitInsideOnlyLabel', {
defaultMessage: 'Inside only',
}),
},
{
value: 'hide',
inputDisplay: i18n.translate('xpack.lens.pieChart.categoriesInLegendLabel', {
defaultMessage: 'Hide labels',
}),
},
];

const categoryOptionsTreemap: CategoryOption[] = [
{
value: 'default',
inputDisplay: i18n.translate('xpack.lens.pieChart.showTreemapCategoriesLabel', {
defaultMessage: 'Show labels',
}),
},
{
value: 'hide',
inputDisplay: i18n.translate('xpack.lens.pieChart.categoriesInLegendLabel', {
defaultMessage: 'Hide labels',
}),
},
];

export const CHART_NAMES = {
donut: {
icon: LensIconChartDonut,
label: i18n.translate('xpack.lens.pie.donutLabel', {
defaultMessage: 'Donut',
}),
partitionType: PartitionLayout.sunburst,
groupLabel,
categoryOptions,
},
pie: {
icon: LensIconChartPie,
label: i18n.translate('xpack.lens.pie.pielabel', {
defaultMessage: 'Pie',
}),

partitionType: PartitionLayout.sunburst,
groupLabel,
categoryOptions,
},
treemap: {
icon: LensIconChartTreemap,
label: i18n.translate('xpack.lens.pie.treemaplabel', {
defaultMessage: 'Treemap',
}),

partitionType: PartitionLayout.treemap,
groupLabel,
categoryOptions: categoryOptionsTreemap,
},
mosaic: {
icon: LensIconChartMosaic,
label: i18n.translate('xpack.lens.pie.mosaiclabel', {
defaultMessage: 'Mosaic',
}),
partitionType: PartitionLayout.mosaic,
groupLabel,
categoryOptions: [] as CategoryOption[],
},
};

export const MAX_PIE_BUCKETS = 3;
export const MAX_TREEMAP_BUCKETS = 2;
export const MAX_MOSAIC_BUCKETS = 2;

export const DEFAULT_PERCENT_DECIMALS = 2;
61 changes: 51 additions & 10 deletions x-pack/plugins/lens/public/pie_visualization/render_function.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import {
Partition,
PartitionConfig,
PartitionLayer,
PartitionLayout,
PartitionFillLabel,
RecursivePartial,
Position,
Expand All @@ -29,7 +28,13 @@ import { VisualizationContainer } from '../visualization_container';
import { CHART_NAMES, DEFAULT_PERCENT_DECIMALS } from './constants';
import type { FormatFactory } from '../../common';
import type { PieExpressionProps } from '../../common/expressions';
import { getSliceValue, getFilterContext } from './render_helpers';
import {
getSliceValue,
getFilterContext,
isTreemapOrMosaicShape,
byDataColorPaletteMap,
extractUniqTermsMap,
} from './render_helpers';
import { EmptyPlaceholder } from '../shared_components';
import './visualization.scss';
import {
Expand Down Expand Up @@ -110,6 +115,22 @@ export function PieComponent(
})
).length;

const shouldUseByDataPalette = !syncColors && ['mosaic'].includes(shape) && bucketColumns[1]?.id;
let byDataPalette: ReturnType<typeof byDataColorPaletteMap>;
if (shouldUseByDataPalette) {
byDataPalette = byDataColorPaletteMap(
firstTable,
bucketColumns[1].id,
paletteService.get(palette.name),
palette
);
}

let sortingMap: Record<string, number>;
if (shape === 'mosaic') {
sortingMap = extractUniqTermsMap(firstTable, bucketColumns[0].id);
}

const layers: PartitionLayer[] = bucketColumns.map((col, layerIndex) => {
return {
groupByRollup: (d: Datum) => d[col.id] ?? EMPTY_SLICE,
Expand All @@ -124,13 +145,29 @@ export function PieComponent(
return String(d);
},
fillLabel,
sortPredicate:
shape === 'mosaic'
? ([name1, node1], [, node2]) => {
// Sorting for first group
if (bucketColumns.length === 1 || (node1.children.length && name1 in sortingMap)) {
return sortingMap[name1];
}
// Sorting for second group
return node2.value - node1.value;
}
: undefined,
shape: {
fillColor: (d) => {
const seriesLayers: SeriesLayer[] = [];

// Mind the difference here: the contrast computation for the text ignores the alpha/opacity
// therefore change it for dask mode
const defaultColor = isDarkMode ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)';

// Color is determined by round-robin on the index of the innermost slice
// This has to be done recursively until we get to the slice index
let tempParent: typeof d | typeof d['parent'] = d;

while (tempParent.parent && tempParent.depth > 0) {
seriesLayers.unshift({
name: String(tempParent.parent.children[tempParent.sortIndex][0]),
Expand All @@ -140,12 +177,14 @@ export function PieComponent(
tempParent = tempParent.parent;
}

if (shape === 'treemap') {
if (byDataPalette && seriesLayers[1]) {
return byDataPalette.getColor(seriesLayers[1].name) || defaultColor;
}

if (isTreemapOrMosaicShape(shape)) {
// Only highlight the innermost color of the treemap, as it accurately represents area
if (layerIndex < bucketColumns.length - 1) {
// Mind the difference here: the contrast computation for the text ignores the alpha/opacity
// therefore change it for dask mode
return isDarkMode ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)';
return defaultColor;
}
// only use the top level series layer for coloring
if (seriesLayers.length > 1) {
Expand All @@ -164,14 +203,14 @@ export function PieComponent(
palette.params
);

return outputColor || 'rgba(0,0,0,0)';
return outputColor || defaultColor;
},
},
};
});

const config: RecursivePartial<PartitionConfig> = {
partitionLayout: shape === 'treemap' ? PartitionLayout.treemap : PartitionLayout.sunburst,
partitionLayout: CHART_NAMES[shape].partitionType,
fontFamily: chartTheme.barSeriesStyle?.displayValue?.fontFamily,
outerSizeRatio: 1,
specialFirstInnermostSector: true,
Expand All @@ -191,7 +230,7 @@ export function PieComponent(
sectorLineWidth: 1.5,
circlePadding: 4,
};
if (shape === 'treemap') {
if (isTreemapOrMosaicShape(shape)) {
if (hideLabels || categoryDisplay === 'hide') {
config.fillLabel = { textColor: 'rgba(0,0,0,0)' };
}
Expand Down Expand Up @@ -279,7 +318,9 @@ export function PieComponent(
showLegend={
!hideLabels &&
(legendDisplay === 'show' ||
(legendDisplay === 'default' && bucketColumns.length > 1 && shape !== 'treemap'))
(legendDisplay === 'default' &&
bucketColumns.length > 1 &&
!isTreemapOrMosaicShape(shape)))
}
legendPosition={legendPosition || Position.Right}
legendMaxDepth={nestedLegend ? undefined : 1 /* Color is based only on first layer */}
Expand Down
Loading

0 comments on commit 47e8a7b

Please sign in to comment.