Skip to content

Commit

Permalink
feat(partition): add legend and highlighters (opensearch-project#616)
Browse files Browse the repository at this point in the history
This commit adds the legend and highlighters to partition charts.
Two new options are added to the <Settings/> components: `flatLegend` will flat the legend for pie/tree hierarchical legend and `legendMaxDepth` will limit the legend hierarchy to a maximum depth value: 1 is the root level (can be combined with the `flatLegend`).

close opensearch-project#486, close opensearch-project#532
  • Loading branch information
markov00 authored Apr 14, 2020
1 parent e8bd5ea commit b939596
Show file tree
Hide file tree
Showing 80 changed files with 1,890 additions and 832 deletions.
61 changes: 3 additions & 58 deletions packages/osd-charts/.playground/playground.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,65 +17,10 @@
* under the License. */

import React from 'react';
import {
Chart,
ScaleType,
Position,
Axis,
Settings,
PartitionElementEvent,
XYChartElementEvent,
BarSeries,
} from '../src';
import { example } from '../stories/sunburst/12_very_small';

export class Playground extends React.Component<{}, { isSunburstShown: boolean }> {
onClick = (elements: Array<PartitionElementEvent | XYChartElementEvent>) => {
// eslint-disable-next-line no-console
console.log(elements[0]);
};
export class Playground extends React.Component {
render() {
return (
<>
<div className="chart">
<Chart size={[300, 200]}>
<Settings
onElementClick={this.onClick}
rotation={90}
theme={{
barSeriesStyle: {
displayValue: {
fontSize: 15,
fill: 'black',
offsetX: 5,
offsetY: -8,
},
},
}}
/>
<Axis id="y1" position={Position.Left} />
<BarSeries
id="amount"
xScaleType={ScaleType.Ordinal}
xAccessor="x"
yAccessors={['y']}
data={[
{ x: 'trousers', y: 390, val: 1222 },
{ x: 'watches', y: 0, val: 1222 },
{ x: 'bags', y: 750, val: 1222 },
{ x: 'cocktail dresses', y: 854, val: 1222 },
]}
displayValueSettings={{
showValueLabel: true,
isValueContainedInElement: true,
hideClippedValue: true,
valueFormatter: (d) => {
return `${d} $`;
},
}}
/>
</Chart>
</div>
</>
);
return <div className="chart">{example()}</div>;
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,12 @@ import { Tooltip } from '../../../components/tooltip';
import { createOnElementClickCaller } from './selectors/on_element_click_caller';
import { createOnElementOverCaller } from './selectors/on_element_over_caller';
import { createOnElementOutCaller } from './selectors/on_element_out_caller';
import { LegendItem } from '../../../commons/legend';
import { LegendItemLabel } from '../../../state/selectors/get_legend_items_labels';

const EMPTY_MAP = new Map();
const EMPTY_LEGEND_LIST: LegendItem[] = [];
const EMPTY_LEGEND_ITEM_LIST: LegendItemLabel[] = [];

/** @internal */
export class GoalState implements InternalChartState {
Expand All @@ -51,9 +55,12 @@ export class GoalState implements InternalChartState {
return false;
}
getLegendItems() {
return EMPTY_MAP;
return EMPTY_LEGEND_LIST;
}
getLegendItemsLabels() {
return EMPTY_LEGEND_ITEM_LIST;
}
getLegendItemsValues() {
getLegendExtraValues() {
return EMPTY_MAP;
}
chartRenderer(containerRef: BackwardRef) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ import { SettingsSpec, LayerValue } from '../../../../specs';
import { getPickedShapesLayerValues } from './picked_shapes';
import { getSpecOrNull } from './goal_spec';
import { ChartTypes } from '../../..';
import { SeriesIdentifier } from '../../../xy_chart/utils/series';
import { isClicking } from '../../../../state/utils';
import { getLastClickSelector } from '../../../../state/selectors/get_last_click';
import { SeriesIdentifier } from '../../../../commons/series_id';

/**
* Will call the onElementClick listener every time the following preconditions are met:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { ChartTypes } from '../../../index';
import { getChartIdSelector } from '../../../../state/selectors/get_chart_id';
import { getSpecOrNull } from './goal_spec';
import { getPickedShapesLayerValues } from './picked_shapes';
import { SeriesIdentifier } from '../../../xy_chart/utils/series';
import { SeriesIdentifier } from '../../../../commons/series_id';

function isOverElement(prevPickedShapes: Array<Array<LayerValue>> = [], nextPickedShapes: Array<Array<LayerValue>>) {
if (nextPickedShapes.length === 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export type ShapeViewModel = {
outsideLinksViewModel: OutsideLinksViewModel[];
diskCenter: PointObject;
pickQuads: PickFunction;
outerRadius: number;
};

export const nullShapeViewModel = (specifiedConfig?: Config, diskCenter?: PointObject): ShapeViewModel => ({
Expand All @@ -96,6 +97,7 @@ export const nullShapeViewModel = (specifiedConfig?: Config, diskCenter?: PointO
outsideLinksViewModel: [],
diskCenter: diskCenter || { x: 0, y: 0 },
pickQuads: () => [],
outerRadius: 0,
});

type TreeLevel = number;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License. */

import { HierarchyOfArrays } from '../utils/group_by_rollup';
import { Relation } from '../types/types';
import { ValueAccessor } from '../../../../utils/commons';
import { IndexedAccessorFn } from '../../../../utils/accessor';
import {
aggregateComparator,
aggregators,
childOrders,
groupByRollup,
mapEntryValue,
mapsToArrays,
} from '../utils/group_by_rollup';

export function getHierarchyOfArrays(
rawFacts: Relation,
valueAccessor: ValueAccessor,
groupByRollupAccessors: IndexedAccessorFn[],
): HierarchyOfArrays {
const aggregator = aggregators.sum;

const facts = rawFacts.filter((n) => {
const value = valueAccessor(n);
return Number.isFinite(value) && value >= 0;
});

// don't render anything if the total, the width or height is not positive
if (facts.reduce((p: number, n) => aggregator.reducer(p, valueAccessor(n)), aggregator.identity()) <= 0) {
return [];
}

// We can precompute things invariant of how the rectangle is divvied up.
// By introducing `scale`, we no longer need to deal with the dichotomy of
// size as data value vs size as number of pixels in the rectangle

return mapsToArrays(
groupByRollup(groupByRollupAccessors, valueAccessor, aggregator, facts),
aggregateComparator(mapEntryValue, childOrders.descending),
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,14 @@
* specific language governing permissions and limitations
* under the License. */

import { Part, Relation, TextMeasure } from '../types/types';
import { Part, TextMeasure } from '../types/types';
import { linkTextLayout } from './link_text_layout';
import { Config, PartitionLayout } from '../types/config_types';
import { TAU, trueBearingToStandardPositionAngle } from '../utils/math';
import { Distance, Pixels, Radius } from '../types/geometry_types';
import { meanAngle } from '../geometry';
import { treemap } from '../utils/treemap';
import { sunburst } from '../utils/sunburst';
import { IndexedAccessorFn } from '../../../../utils/accessor';
import { argsToRGBString, stringToRGB } from '../utils/d3_utils';
import {
nullShapeViewModel,
Expand All @@ -49,20 +48,16 @@ import {
} from './fill_text_layout';
import {
aggregateAccessor,
aggregateComparator,
aggregators,
ArrayEntry,
childOrders,
depthAccessor,
entryKey,
entryValue,
groupByRollup,
mapEntryValue,
mapsToArrays,
parentAccessor,
sortIndexAccessor,
HierarchyOfArrays,
} from '../utils/group_by_rollup';
import { StrokeStyle, ValueAccessor, ValueFormatter } from '../../../../utils/commons';
import { StrokeStyle, ValueFormatter } from '../../../../utils/commons';
import { percentValueGetter } from '../config/config';

function paddingAccessor(n: ArrayEntry) {
Expand Down Expand Up @@ -148,13 +143,11 @@ export function shapeViewModel(
textMeasure: TextMeasure,
config: Config,
layers: Layer[],
rawFacts: Relation,
rawTextGetter: RawTextGetter,
valueAccessor: ValueAccessor,
specifiedValueFormatter: ValueFormatter,
specifiedPercentFormatter: ValueFormatter,
valueGetter: ValueGetterFunction,
groupByRollupAccessors: IndexedAccessorFn[],
tree: HierarchyOfArrays,
): ShapeViewModel {
const {
width,
Expand All @@ -179,31 +172,11 @@ export function shapeViewModel(
y: height * margin.top + innerHeight / 2,
};

const aggregator = aggregators.sum;

const facts = rawFacts.filter((n) => {
const value = valueAccessor(n);
return Number.isFinite(value) && value >= 0;
});

// don't render anything if the total, the width or height is not positive
if (
facts.reduce((p: number, n) => aggregator.reducer(p, valueAccessor(n)), aggregator.identity()) <= 0 ||
!(width > 0) ||
!(height > 0)
) {
if (!(width > 0) || !(height > 0) || tree.length === 0) {
return nullShapeViewModel(config, diskCenter);
}

// We can precompute things invariant of how the rectangle is divvied up.
// By introducing `scale`, we no longer need to deal with the dichotomy of
// size as data value vs size as number of pixels in the rectangle

const tree = mapsToArrays(
groupByRollup(groupByRollupAccessors, valueAccessor, aggregator, facts),
aggregateComparator(mapEntryValue, childOrders.descending),
);

const totalValue = tree.reduce((p: number, n: ArrayEntry): number => p + mapEntryValue(n), 0);

const sunburstValueToAreaScale = TAU / totalValue;
Expand Down Expand Up @@ -332,5 +305,6 @@ export function shapeViewModel(
linkLabelViewModels,
outsideLinksViewModel,
pickQuads,
outerRadius,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ function renderTaperedBorder(
ctx.arc(0, 0, y0px, X0, X0);
ctx.arc(0, 0, y1px, X0, X1, false);
ctx.arc(0, 0, y0px, X1, X0, true);

ctx.fill();
if (strokeWidth > 0.001 && !(x0 === 0 && x1 === TAU)) {
// canvas2d uses a default of 1 if the lineWidth is assigned 0, so we use a small value to test, to avoid it
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { partitionGeometries } from '../../state/selectors/geometries';
import { nullShapeViewModel, QuadViewModel, ShapeViewModel } from '../../layout/types/viewmodel_types';
import { renderPartitionCanvas2d } from './canvas_renderers';
import { INPUT_KEY } from '../../layout/utils/group_by_rollup';
import { getChartContainerDimensionsSelector } from '../../../../state/selectors/get_chart_container_dimensions';

interface ReactiveChartStateProps {
initialized: boolean;
Expand Down Expand Up @@ -171,7 +172,7 @@ const mapStateToProps = (state: GlobalChartState): ReactiveChartStateProps => {
return {
initialized: true,
geometries: partitionGeometries(state),
chartContainerDimensions: state.parentDimensions,
chartContainerDimensions: getChartContainerDimensionsSelector(state),
};
};

Expand Down
Loading

0 comments on commit b939596

Please sign in to comment.