Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(partition): add element click, over, out events #578

Merged
133 changes: 99 additions & 34 deletions .playground/playground.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,51 +4,116 @@ import {
ScaleType,
Position,
Axis,
LineSeries,
LineAnnotation,
RectAnnotation,
AnnotationDomainTypes,
LineAnnotationDatum,
RectAnnotationDatum,
Settings,
PartitionElementEvent,
XYChartElementEvent,
Partition,
BarSeries,
} from '../src';
import { SeededDataGenerator } from '../src/mocks/utils';

type PieDatum = [string, number, string, number];
const pieData: Array<PieDatum> = [
['CN', 301, 'CN', 64],
['CN', 301, 'IN', 44],
['CN', 301, 'US', 24],
['CN', 301, 'ID', 13],
['CN', 301, 'BR', 8],
['IN', 245, 'IN', 41],
['IN', 245, 'CN', 36],
['IN', 245, 'US', 22],
['IN', 245, 'BR', 11],
['IN', 245, 'ID', 10],
['US', 130, 'CN', 33],
['US', 130, 'IN', 23],
['US', 130, 'US', 9],
['US', 130, 'ID', 7],
['US', 130, 'BR', 5],
['ID', 55, 'CN', 9],
['ID', 55, 'IN', 8],
['ID', 55, 'ID', 5],
['ID', 55, 'BR', 4],
['ID', 55, 'US', 3],
['PK', 43, 'CN', 8],
['PK', 43, 'IN', 5],
['PK', 43, 'US', 5],
['PK', 43, 'FR', 2],
['PK', 43, 'PK', 2],
];
export class Playground extends React.Component<{}, { isSunburstShown: boolean }> {
onClick = (elements: Array<PartitionElementEvent | XYChartElementEvent>) => {
// eslint-disable-next-line no-console
console.log(elements[0]);
};
render() {
const dg = new SeededDataGenerator();
const data = dg.generateGroupedSeries(10, 2).map((item) => ({
...item,
y1: item.y + 100,
}));
const lineDatum: LineAnnotationDatum[] = [{ dataValue: 321321 }];
const rectDatum: RectAnnotationDatum[] = [{ coordinates: { x1: 100 } }];

return (
<>
<div className="chart">
<Chart>
<Axis id="y1" position={Position.Left} title="y1" />
<Axis id="y2" domain={{ fit: true }} groupId="g2" position={Position.Right} title="y2" />
<Axis id="x" position={Position.Bottom} title="x" />
<LineSeries
id="line1"
xScaleType={ScaleType.Linear}
<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']}
splitSeriesAccessors={['g']}
data={data}
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} $`;
},
}}
/>
<LineSeries
id="line2"
groupId="g2"
xScaleType={ScaleType.Linear}
xAccessor="x"
yAccessors={['y1']}
splitSeriesAccessors={['g']}
data={data}
</Chart>
</div>
<div className="chart">
<Chart>
<Settings onElementClick={this.onClick} />
<Partition
id="pie"
data={pieData}
valueAccessor={(d) => {
return d[3];
}}
layers={[
{
groupByRollup: (d: PieDatum) => {
return d[0];
},
nodeLabel: (d) => {
return `dest: ${d}`;
},
},
{
groupByRollup: (d: PieDatum) => {
return d[2];
},
nodeLabel: (d) => {
return `source: ${d}`;
},
},
]}
/>
<LineAnnotation id="sss" dataValues={lineDatum} domainType={AnnotationDomainTypes.XDomain} />
<RectAnnotation id="111" dataValues={rectDatum} />
</Chart>
</div>
</>
Expand Down
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.
9 changes: 9 additions & 0 deletions integration/tests/interactions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,5 +76,14 @@ describe.only('Tooltips', () => {
},
);
});
it('shows tooltip on sunburst', async () => {
await common.expectChartWithMouseAtUrlToMatchScreenshot(
'http://localhost:9001/?path=/story/interactions--sunburst-slice-clicks',
{
x: 350,
y: 100,
},
);
});
});
});
9 changes: 9 additions & 0 deletions src/chart_types/partition_chart/state/chart_state.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,15 @@ import { Partition } from '../renderer/canvas/partition';
import { isTooltipVisibleSelector } from '../state/selectors/is_tooltip_visible';
import { getTooltipInfoSelector } from '../state/selectors/tooltip';
import { Tooltip } from '../../../components/tooltip';
import { createOnElementClickCaller } from './selectors/on_element_click_caller';

const EMPTY_MAP = new Map();
export class PartitionState implements InternalChartState {
onElementClickCaller: (state: GlobalChartState) => void;

constructor() {
this.onElementClickCaller = createOnElementClickCaller();
}
chartType = ChartTypes.Partition;
isBrushAvailable() {
return false;
Expand Down Expand Up @@ -49,4 +55,7 @@ export class PartitionState implements InternalChartState {
y1: position.y,
};
}
eventCallbacks(globalState: GlobalChartState) {
this.onElementClickCaller(globalState);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import createCachedSelector from 're-reselect';
import { Selector } from 'reselect';
import { GlobalChartState, PointerState } from '../../../../state/chart_state';
import { getSettingsSpecSelector } from '../../../../state/selectors/get_settings_specs';
import { SettingsSpec, LayerValue } from '../../../../specs';
import { QuadViewModel } from '../../layout/types/viewmodel_types';
import { getPickedShapes } from './picked_shapes';
import { getPieSpecOrNull } from './pie_spec';
import { ChartTypes } from '../../..';
import { PARENT_KEY, DEPTH_KEY, SORT_INDEX_KEY, AGGREGATE_KEY, CHILDREN_KEY } from '../../layout/utils/group_by_rollup';
import { SeriesIdentifier } from '../../../xy_chart/utils/series';

const getLastClickSelector = (state: GlobalChartState) => state.interactions.pointer.lastClick;

interface Props {
settings: SettingsSpec | undefined;
lastClick: PointerState | null;
pickedShapes: QuadViewModel[];
}

function isClicking(prevProps: Props | null, nextProps: Props | null) {
if (nextProps === null) {
return false;
}
if (!nextProps.settings || !nextProps.settings.onElementClick || nextProps.pickedShapes.length === 0) {
return false;
}
const prevLastClick = prevProps !== null ? prevProps.lastClick : null;
const nextLastClick = nextProps !== null ? nextProps.lastClick : null;

if (prevLastClick === null && nextLastClick !== null) {
return true;
}
if (prevLastClick !== null && nextLastClick !== null && prevLastClick.time !== nextLastClick.time) {
return true;
}
return false;
}

/**
* Will call the onElementClick listener every time the following preconditions are met:
* - the onElementClick listener is available
* - we have at least one highlighted geometry
* - the pointer state goes from down state to up state
*/
export function createOnElementClickCaller(): (state: GlobalChartState) => void {
let prevProps: Props | null = null;
let selector: Selector<GlobalChartState, void> | null = null;
return (state: GlobalChartState) => {
if (selector === null && state.chartType === ChartTypes.Partition) {
selector = createCachedSelector(
[getPieSpecOrNull, getLastClickSelector, getSettingsSpecSelector, getPickedShapes],
(pieSpec, lastClick: PointerState | null, settings: SettingsSpec, pickedShapes: QuadViewModel[]): void => {
const nextProps = {
lastClick,
settings,
pickedShapes,
};
if (!pieSpec) {
return;
}
if (isClicking(prevProps, nextProps)) {
if (settings && settings.onElementClick) {
const elements = pickedShapes.map<[Array<LayerValue>, SeriesIdentifier]>((model) => {
const values: Array<LayerValue> = [];
values.push({
groupByRollup: model.dataName,
value: model.value,
});
let parent = model.parent;
let index = model.parent.sortIndex;
while (parent[DEPTH_KEY] > 0) {
const value = parent[AGGREGATE_KEY];
const dataName = parent[PARENT_KEY][CHILDREN_KEY][index][0];
values.push({ groupByRollup: dataName, value });

parent = parent[PARENT_KEY];
index = parent[SORT_INDEX_KEY];
}
return [
values.reverse(),
{
specId: pieSpec.id,
key: `spec{${pieSpec.id}}`,
},
];
});
settings.onElementClick(elements);
}
}
prevProps = nextProps;
},
)({
keySelector: (state: GlobalChartState) => state.chartId,
});
}
if (selector) {
selector(state);
}
};
}
19 changes: 19 additions & 0 deletions src/chart_types/partition_chart/state/selectors/picked_shapes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import createCachedSelector from 're-reselect';
import { partitionGeometries } from './geometries';
import { QuadViewModel } from '../../layout/types/viewmodel_types';
import { GlobalChartState } from '../../../../state/chart_state';

function getCurrentPointerPosition(state: GlobalChartState) {
return state.interactions.pointer.current.position;
}

export const getPickedShapes = createCachedSelector(
[partitionGeometries, getCurrentPointerPosition],
(geoms, pointerPosition): Array<QuadViewModel> => {
const picker = geoms.pickQuads;
const diskCenter = geoms.diskCenter;
const x = pointerPosition.x - diskCenter.x;
const y = pointerPosition.y - diskCenter.y;
return picker(x, y);
},
)((state) => state.chartId);
10 changes: 10 additions & 0 deletions src/chart_types/partition_chart/state/selectors/pie_spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { GlobalChartState } from '../../../../state/chart_state';
import { getSpecsFromStore } from '../../../../state/utils';
import { PartitionSpec } from '../../specs';
import { ChartTypes } from '../../..';
import { SpecTypes } from '../../../../specs';

export function getPieSpecOrNull(state: GlobalChartState): PartitionSpec | null {
const pieSpecs = getSpecsFromStore<PartitionSpec>(state.specs, ChartTypes.Partition, SpecTypes.Series);
return pieSpecs.length > 0 ? pieSpecs[0] : null;
}
27 changes: 5 additions & 22 deletions src/chart_types/partition_chart/state/selectors/tooltip.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,9 @@
import createCachedSelector from 're-reselect';
import { GlobalChartState } from '../../../../state/chart_state';
import { partitionGeometries } from './geometries';
import { INPUT_KEY } from '../../layout/utils/group_by_rollup';
import { QuadViewModel } from '../../layout/types/viewmodel_types';
import { TooltipInfo } from '../../../../components/tooltip/types';
import { ChartTypes } from '../../..';
import { SpecTypes } from '../../../../specs';
import { getSpecsFromStore } from '../../../../state/utils';
import { PartitionSpec } from '../../specs';

function getCurrentPointerPosition(state: GlobalChartState) {
return state.interactions.pointer.current.position;
}

function getPieSpecOrNull(state: GlobalChartState): PartitionSpec | null {
const pieSpecs = getSpecsFromStore<PartitionSpec>(state.specs, ChartTypes.Partition, SpecTypes.Series);
return pieSpecs.length > 0 ? pieSpecs[0] : null;
}
import { getPieSpecOrNull } from './pie_spec';
import { getPickedShapes } from './picked_shapes';

function getValueFormatter(state: GlobalChartState) {
return getPieSpecOrNull(state)?.valueFormatter;
Expand All @@ -32,16 +19,12 @@ const EMPTY_TOOLTIP = Object.freeze({
});

export const getTooltipInfoSelector = createCachedSelector(
[getPieSpecOrNull, partitionGeometries, getCurrentPointerPosition, getValueFormatter, getLabelFormatters],
(pieSpec, geoms, pointerPosition, valueFormatter, labelFormatters): TooltipInfo => {
[getPieSpecOrNull, getPickedShapes, getValueFormatter, getLabelFormatters],
(pieSpec, pickedShapes, valueFormatter, labelFormatters): TooltipInfo => {
if (!pieSpec || !valueFormatter || !labelFormatters) {
return EMPTY_TOOLTIP;
}
const picker = geoms.pickQuads;
const diskCenter = geoms.diskCenter;
const x = pointerPosition.x - diskCenter.x;
const y = pointerPosition.y - diskCenter.y;
const pickedShapes: Array<QuadViewModel> = picker(x, y);

const datumIndices = new Set();
const tooltipInfo: TooltipInfo = {
header: null,
Expand Down
10 changes: 8 additions & 2 deletions src/chart_types/xy_chart/rendering/rendering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,10 @@ function renderPoints(
seriesIdentifier,
styleOverrides,
};
mutableIndexedGeometryMapUpsert(indexedGeometries, xValue, pointGeometry);
mutableIndexedGeometryMapUpsert(indexedGeometries, xValue, {
...pointGeometry,
datum: datum.datum,
});
// use the geometry only if the yDatum in contained in the current yScale domain
const isHidden = yDatum === null || (isLogScale && yDatum <= 0);
if (!isHidden && yScale.isValueInDomain(yDatum)) {
Expand Down Expand Up @@ -293,7 +296,10 @@ export function renderBars(
seriesIdentifier,
seriesStyle,
};
mutableIndexedGeometryMapUpsert(indexedGeometries, datum.x, barGeometry);
mutableIndexedGeometryMapUpsert(indexedGeometries, datum.x, {
...barGeometry,
datum: datum.datum,
});
barGeometries.push(barGeometry);
});

Expand Down
Loading