Skip to content

feat: added onMouseOver and onMouseOut props to Bar #602

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

Merged
merged 2 commits into from
Jun 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions packages/docs/docs/api/visualizations/Bar.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,18 @@ If you only have one series in your data, both the `type` and `color` props can
<td>–</td>
<td>Callback that will be run when a point/section is clicked.</td>
</tr>
<tr>
<td>onMouseOver</td>
<td>function</td>
<td>–</td>
<td>Callback that will be run when a bar is hovered.</td>
</tr>
<tr>
<td>onMouseOut</td>
<td>function</td>
<td>–</td>
<td>Callback that will be run when a bar is no longer hovered.</td>
</tr>
<tr>
<td>metric</td>
<td>string</td>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright 2025 Adobe. All rights reserved.
* This file is licensed 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 REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import { createElement, useMemo } from 'react';

import { Datum } from '@spectrum-charts/vega-spec-builder';

import { Bar, BarElement, Chart, ChartChildElement } from '../index';
import { getAllMarkElements } from '../utils';

type MappedMarkElement = { name: string; element: BarElement };

export type MarkMouseInputDetail = {
markName?: string;
onMouseOver?: (datum: Datum) => void;
onMouseOut?: (datum: Datum) => void;
};

export default function useMarkMouseInputDetails(children: ChartChildElement[]): MarkMouseInputDetail[] {
const markElements = useMemo(() => {
return [
...getAllMarkElements(createElement(Chart, { data: [] }, children), Bar, []),
] as MappedMarkElement[];
}, [children]);

return useMemo(
() =>
markElements
.filter((mark) => {
const barProps = mark.element.props;
return barProps.onMouseOver || barProps.onMouseOut;
})
.map((mark) => {
const barProps = mark.element.props;
return {
markName: mark.name,
onMouseOver: barProps.onMouseOver,
onMouseOut: barProps.onMouseOut,
};
}) as MarkMouseInputDetail[],
[markElements]
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@
*/
import { createElement, useMemo } from 'react';

import { Bar, BarElement, Chart, ChartChildElement, Line, LineElement, OnClickCallback } from '../index';
import { Bar, BarElement, Chart, ChartChildElement, Line, LineElement, MarkCallback } from '../index';
import { getAllMarkElements } from '../utils';

type MappedMarkElement = { name: string; element: BarElement | LineElement };

export type MarkOnClickDetail = {
markName?: string;
onClick?: OnClickCallback;
onClick?: MarkCallback;
};

export default function useMarkOnClickDetails(children: ChartChildElement[]): MarkOnClickDetail[] {
Expand Down
7 changes: 5 additions & 2 deletions packages/react-spectrum-charts/src/hooks/useNewChartView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
setSelectedSignals,
} from '../utils';
import useLegend from './useLegend';
import useMarkMouseInputDetails from './useMarkMouseInputDetails';
import useMarkOnClickDetails from './useMarkOnClickDetails';
import usePopovers from './usePopovers';

Expand All @@ -45,6 +46,7 @@ const useNewChartView = (
onMouseOver: onLegendMouseOver,
} = useLegend(sanitizedChildren); // gets props from the legend if it exists
const markClickDetails = useMarkOnClickDetails(sanitizedChildren);
const markMouseInputDetails = useMarkMouseInputDetails(sanitizedChildren);

const legendHasPopover = useMemo(
() => popovers.some((p) => p.parent === Legend.displayName && !p.chartPopoverProps.rightClick),
Expand Down Expand Up @@ -125,8 +127,8 @@ const useNewChartView = (
}
}
view.addEventListener('click', getOnChartMarkClickCallback(chartView, markClickDetails));
view.addEventListener('mouseover', getOnMouseInputCallback(onLegendMouseOver));
view.addEventListener('mouseout', getOnMouseInputCallback(onLegendMouseOut));
view.addEventListener('mouseover', getOnMouseInputCallback(onLegendMouseOver, markMouseInputDetails));
view.addEventListener('mouseout', getOnMouseInputCallback(onLegendMouseOut, markMouseInputDetails));
},
[
chartId,
Expand All @@ -137,6 +139,7 @@ const useNewChartView = (
legendHiddenSeries,
legendIsToggleable,
markClickDetails,
markMouseInputDetails,
onLegendClick,
onLegendMouseOut,
onLegendMouseOver,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import React, { ReactElement, createElement } from 'react';
import React, { ReactElement, createElement, useState } from 'react';

import { StoryFn } from '@storybook/react';

import { Datum } from '@spectrum-charts/vega-spec-builder';

import { Annotation } from '../../../components/Annotation';
import useChartProps from '../../../hooks/useChartProps';
import { Axis, Bar, BarProps, Chart } from '../../../index';
Expand Down Expand Up @@ -41,6 +43,41 @@ const BarStoryWithUTCData: StoryFn<typeof Bar> = (args): ReactElement => {
);
};

const OnMouseInputsStory: StoryFn<typeof Bar> = (args): ReactElement => {
const [hoveredData, setHoveredData] = useState<Datum | null>(null);
const [isHovering, setIsHovering] = useState(false);

const controlledMouseOver = (datum: Datum) => {
if (!isHovering) {
setHoveredData(datum);
setIsHovering(true);
}
};
const controlledMouseOut = () => {
if (isHovering) {
setIsHovering(false);
}
};

const chartProps = useChartProps({ data: barData, width: 600, height: 600 });
return (
<div>
<div data-testid="hover-info">
{isHovering && hoveredData ? (
<div data-testid="hover-data">{JSON.stringify(hoveredData, null, 2)}</div>
) : (
<div data-testid="no-hover">No bar hovered</div>
)}
</div>
<Chart {...chartProps}>
<Axis position={args.orientation === 'horizontal' ? 'left' : 'bottom'} baseline title="Browser" />
<Axis position={args.orientation === 'horizontal' ? 'bottom' : 'left'} grid title="Downloads" />
<Bar {...args} onMouseOver={controlledMouseOver} onMouseOut={controlledMouseOut} />
</Chart>
</div>
);
};

const BarStory: StoryFn<typeof Bar> = (args): ReactElement => {
const chartProps = useChartProps({ data: barData, width: 600, height: 600 });
return (
Expand Down Expand Up @@ -107,6 +144,12 @@ OnClick.args = {
metric: 'downloads',
};

const OnMouseInputs = bindWithProps(OnMouseInputsStory);
OnMouseInputs.args = {
dimension: 'browser',
metric: 'downloads',
};

const BarWithUTCDatetimeFormat = bindWithProps(BarStoryWithUTCData);
BarWithUTCDatetimeFormat.args = {
...defaultProps,
Expand All @@ -125,5 +168,6 @@ export {
WithAnnotation,
HasSquareCorners,
OnClick,
OnMouseInputs,
BarWithUTCDatetimeFormat,
};
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,25 @@
* governing permissions and limitations under the License.
*/
import { Bar } from '../../../components';
import { clickNthElement, findAllMarksByGroupName, findChart, render } from '../../../test-utils';
import {
clickNthElement,
findAllMarksByGroupName,
findChart,
hoverNthElement,
render,
screen,
unhoverNthElement,
} from '../../../test-utils';
import '../../../test-utils/__mocks__/matchMedia.mock.js';
import { BarWithUTCDatetimeFormat, Basic, OnClick, Opacity, PaddingRatio, WithAnnotation } from './Bar.story';
import {
BarWithUTCDatetimeFormat,
Basic,
OnClick,
OnMouseInputs,
Opacity,
PaddingRatio,
WithAnnotation,
} from './Bar.story';
import { Color, DodgedStacked } from './DodgedBar.story';
import { Basic as StackedBasic } from './StackedBar.story';
import { barData } from './data';
Expand Down Expand Up @@ -128,4 +144,70 @@ describe('Bar', () => {
await clickNthElement(bars, 4);
expect(onClick).toHaveBeenCalledWith(expect.objectContaining(barData[4]));
});

test('should call onMouseOver and onMouseOut callbacks when hovering bar items', async () => {
const onMouseOver = jest.fn();
const onMouseOut = jest.fn();
render(<Basic {...Basic.args} onMouseOver={onMouseOver} onMouseOut={onMouseOut} />);
const chart = await findChart();
const bars = await findAllMarksByGroupName(chart, 'bar0');

await hoverNthElement(bars, 0);
expect(onMouseOver).toHaveBeenCalledWith(expect.objectContaining(barData[0]));

await unhoverNthElement(bars, 0);
expect(onMouseOut).toHaveBeenCalledWith(expect.objectContaining(barData[0]));
});

test('should display custom hover information in UI when mousing over bar items', async () => {
render(<OnMouseInputs {...OnMouseInputs.args} />);
const chart = await findChart();
const bars = await findAllMarksByGroupName(chart, 'bar0');

// Initially no hover info should be displayed
expect(screen.getByTestId('no-hover')).toBeInTheDocument();
expect(screen.queryByTestId('hover-data')).not.toBeInTheDocument();

// Hover over first bar (Chrome, 27000)
await hoverNthElement(bars, 0);

expect(screen.queryByTestId('no-hover')).not.toBeInTheDocument();
let hoverData = screen.getByTestId('hover-data');
expect(hoverData).toBeInTheDocument();

const firstBarData = JSON.parse(hoverData.textContent || '{}');
expect(firstBarData.browser).toBe('Chrome');
expect(firstBarData.downloads).toBe(27000);
expect(firstBarData.percentLabel).toBe('53.1%');
expect(firstBarData.rscMarkId).toBe(1);
expect(firstBarData.downloads0).toBe(0);
expect(firstBarData.downloads1).toBe(27000);
expect(firstBarData.rscStackId).toBe('Chrome');

// Re-query bars after hover state change to get fresh DOM references
const barsAfterHover = await findAllMarksByGroupName(chart, 'bar0');

// Unhover first bar
await unhoverNthElement(barsAfterHover, 0);
expect(screen.getByTestId('no-hover')).toBeInTheDocument();
expect(screen.queryByTestId('hover-data')).not.toBeInTheDocument();

// Re-query bars after unhover state change for fresh DOM references
const barsAfterUnhover = await findAllMarksByGroupName(chart, 'bar0');

// Hover over second bar (Firefox, 8000)
await hoverNthElement(barsAfterUnhover, 1);

hoverData = screen.getByTestId('hover-data');
expect(hoverData).toBeInTheDocument();

const secondBarData = JSON.parse(hoverData.textContent || '{}');
expect(secondBarData.browser).toBe('Firefox');
expect(secondBarData.downloads).toBe(8000);
expect(secondBarData.percentLabel).toBe('15.7%');
expect(secondBarData.rscMarkId).toBe(2);
expect(secondBarData.downloads0).toBe(0);
expect(secondBarData.downloads1).toBe(8000);
expect(secondBarData.rscStackId).toBe('Firefox');
});
});
8 changes: 6 additions & 2 deletions packages/react-spectrum-charts/src/types/marks/bar.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { JSXElementConstructor, ReactElement } from 'react';
import { BarOptions } from '@spectrum-charts/vega-spec-builder';

import { ChartPopoverElement, ChartTooltipElement } from '../dialogs';
import { Children, OnClickCallback } from '../util.types';
import { Children, MarkCallback } from '../util.types';
import { BarAnnotationElement, TrendlineElement } from './supplemental';

export interface BarProps
Expand All @@ -24,7 +24,11 @@ export interface BarProps
> {
children?: Children<BarAnnotationElement | ChartPopoverElement | ChartTooltipElement | TrendlineElement>;
/** Callback that will be run when a point/section is clicked */
onClick?: OnClickCallback;
onClick?: MarkCallback;
/** Callback that will be run when a point/section is hovered */
onMouseOver?: MarkCallback;
/** Callback that will be run when a point/section is no longer hovered */
onMouseOut?: MarkCallback;
}

export type BarElement = ReactElement<BarProps, JSXElementConstructor<BarProps>>;
4 changes: 2 additions & 2 deletions packages/react-spectrum-charts/src/types/marks/line.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { JSXElementConstructor, ReactElement } from 'react';
import { LineOptions } from '@spectrum-charts/vega-spec-builder';

import { ChartPopoverElement, ChartTooltipElement } from '../dialogs';
import { Children, OnClickCallback } from '../util.types';
import { Children, MarkCallback } from '../util.types';
import { MetricRangeElement, TrendlineElement } from './supplemental';

type LineChildElement = ChartTooltipElement | ChartPopoverElement | MetricRangeElement | TrendlineElement;
Expand All @@ -25,7 +25,7 @@ export interface LineProps
> {
children?: Children<LineChildElement>;
/** Callback that will be run when a point/section is clicked */
onClick?: OnClickCallback;
onClick?: MarkCallback;
}

export type LineElement = ReactElement<LineProps, JSXElementConstructor<LineProps>>;
4 changes: 2 additions & 2 deletions packages/react-spectrum-charts/src/types/util.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ import { Datum } from '@spectrum-charts/vega-spec-builder';

export type ChildElement<T> = T | string | boolean | Iterable<ReactNode>;
export type Children<T> = ChildElement<T> | ChildElement<T>[];
export type OnClickCallback = (datum: Datum) => void;
export type MarkCallback = (datum: Datum) => void;

export interface ClickableChartProps {
/** Callback that will be run when a point/section is clicked */
onClick?: OnClickCallback;
onClick?: MarkCallback;
}
Loading