Skip to content
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
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,8 @@
"d3-format": "^3.1.0",
"immer": ">= 9.0.0",
"uuid": ">= 9.0.0",
"vega-embed": ">= 6.24.0",
"vega-tooltip": ">= 0.26.0"
"vega-embed": ">= 6.27.0",
"vega-tooltip": ">= 0.35.2"
},
"peerDependencies": {
"@adobe/react-spectrum": ">=3.23.0",
Expand Down
51 changes: 23 additions & 28 deletions src/Chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,7 @@ export const Chart = forwardRef<ChartHandle, ChartProps>(
data,
colors = 'categorical12',
colorScheme = DEFAULT_COLOR_SCHEME,
config,
dataTestId,
description,
debug = false,
emptyStateText = 'No data found',
height = 300,
Expand All @@ -61,13 +59,12 @@ export const Chart = forwardRef<ChartHandle, ChartProps>(
maxHeight = Infinity,
minWidth = 100,
maxWidth = Infinity,
opacities,
padding = 0,
renderer = 'svg',
symbolShapes,
symbolSizes,
theme = defaultTheme,
title,
tooltipAnchor = 'cursor',
tooltipPlacement = 'top',
width = 'auto',
UNSAFE_vegaSpec,
...props
Expand Down Expand Up @@ -118,29 +115,27 @@ export const Chart = forwardRef<ChartHandle, ChartProps>(
}

const rscChartProps: RscChartProps = {
chartView: chartView,
chartId: chartId,
data: data,
backgroundColor: backgroundColor,
colors: colors,
colorScheme: colorScheme,
config: config,
description: description,
debug: debug,
hiddenSeries: hiddenSeries,
highlightedSeries: highlightedSeries,
lineTypes: lineTypes,
lineWidths: lineWidths,
locale: locale,
opacities: opacities,
padding: padding,
renderer: renderer,
symbolShapes: symbolShapes,
symbolSizes: symbolSizes,
title: title,
chartWidth: chartWidth,
chartHeight: chartHeight,
UNSAFE_vegaSpec: UNSAFE_vegaSpec,
chartView,
chartId,
data,
backgroundColor,
colors,
colorScheme,
debug,
hiddenSeries,
highlightedSeries,
lineTypes,
lineWidths,
locale,
padding,
renderer,
title,
tooltipAnchor,
tooltipPlacement,
chartWidth,
chartHeight,
UNSAFE_vegaSpec,
...props,
};

const bigNumberElements = getBigNumberElementsFromChildren(props.children);
Expand Down
78 changes: 54 additions & 24 deletions src/RscChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ import { FC, MutableRefObject, forwardRef, useEffect, useMemo, useRef, useState

import {
COMPONENT_NAME,
DEFAULT_BACKGROUND_COLOR,
DEFAULT_COLOR_SCHEME,
DEFAULT_LINE_TYPES,
DEFAULT_LOCALE,
FILTERED_TABLE,
GROUP_DATA,
LEGEND_TOOLTIP_DELAY,
Expand Down Expand Up @@ -44,13 +40,22 @@ import {
} from '@utils';
import { renderToStaticMarkup } from 'react-dom/server';
import { Item } from 'vega';
import { Handler, Options as TooltipOptions } from 'vega-tooltip';
import { Handler, Position, Options as TooltipOptions } from 'vega-tooltip';

import { ActionButton, Dialog, DialogTrigger, View as SpectrumView } from '@adobe/react-spectrum';

import './Chart.css';
import { VegaChart } from './VegaChart';
import { ChartHandle, Datum, LegendDescription, LineType, MarkBounds, RscChartProps } from './types';
import {
ChartHandle,
ColorScheme,
Datum,
LegendDescription,
MarkBounds,
RscChartProps,
TooltipAnchor,
TooltipPlacement,
} from './types';

interface ChartDialogProps {
datum: Datum | null;
Expand All @@ -69,25 +74,27 @@ export const RscChart = forwardRef<ChartHandle, RscChartProps>(
(
{
chartView,
backgroundColor = DEFAULT_BACKGROUND_COLOR,
backgroundColor,
data,
colors = 'categorical12',
colorScheme = DEFAULT_COLOR_SCHEME,
colors,
colorScheme,
config,
description,
debug = false,
hiddenSeries = [],
debug,
hiddenSeries,
highlightedSeries,
lineTypes = DEFAULT_LINE_TYPES as LineType[],
lineWidths = ['M'],
locale = DEFAULT_LOCALE,
lineTypes,
lineWidths,
locale,
opacities,
padding = 0,
renderer = 'svg',
padding,
renderer,
symbolShapes,
symbolSizes,
title,
chartHeight = 300,
tooltipAnchor,
tooltipPlacement,
chartHeight,
chartWidth,
UNSAFE_vegaSpec,
chartId,
Expand Down Expand Up @@ -162,10 +169,10 @@ export const RscChart = forwardRef<ChartHandle, RscChartProps>(
padding
);

const tooltipConfig: TooltipOptions = { theme: colorScheme };
const tooltipOptions = getTooltipOptions(colorScheme, tooltipAnchor, tooltipPlacement);

if (tooltips.length || legendDescriptions) {
tooltipConfig.formatTooltip = (value) => {
tooltipOptions.formatTooltip = (value) => {
debugLog(debug, { title: 'Tooltip datum', contents: value });
if (value[COMPONENT_NAME]?.startsWith('legend') && legendDescriptions && 'index' in value) {
debugLog(debug, {
Expand Down Expand Up @@ -239,25 +246,25 @@ export const RscChart = forwardRef<ChartHandle, RscChartProps>(
locale={locale}
padding={padding}
signals={signals}
tooltip={tooltipConfig} // legend show/hide relies on this
tooltip={tooltipOptions} // legend show/hide relies on this
onNewView={(view) => {
chartView.current = view;
// Add a delay before displaying legend tooltips on hover.
let tooltipTimeout: NodeJS.Timeout | undefined;
view.tooltip((_, event, item, value) => {
const tooltipHandler = new Handler(tooltipConfig);
view.tooltip((viewRef, event, item, value) => {
const tooltipHandler = new Handler(tooltipOptions);
// Cancel delayed tooltips if the mouse moves before the delay is resolved.
if (tooltipTimeout) {
clearTimeout(tooltipTimeout);
tooltipTimeout = undefined;
}
if (event && event.type === 'pointermove' && itemIsLegendItem(item) && 'tooltip' in item) {
tooltipTimeout = setTimeout(() => {
tooltipHandler.call(this, event, item, value);
tooltipHandler.call(viewRef, event, item, value);
tooltipTimeout = undefined;
}, LEGEND_TOOLTIP_DELAY);
} else {
tooltipHandler.call(this, event, item, value);
tooltipHandler.call(viewRef, event, item, value);
}
});
if (popovers.length || onMarkClicks.length || legendIsToggleable || onLegendClick) {
Expand Down Expand Up @@ -336,6 +343,29 @@ const ChartDialog = ({ datum, popover, setIsPopoverOpen, targetElement }: ChartD
);
};

const getTooltipOptions = (
colorScheme: ColorScheme,
tooltipAnchor: TooltipAnchor,
tooltipPlacement: TooltipPlacement
): TooltipOptions => {
const position: Record<'top' | 'bottom' | 'right' | 'left', Position[]> = {
top: ['top', 'bottom', 'right', 'left', 'top-right', 'top-left', 'bottom-right', 'bottom-left'],
bottom: ['bottom', 'top', 'right', 'left', 'bottom-right', 'bottom-left', 'top-right', 'top-left'],
right: ['right', 'left', 'top', 'bottom', 'top-right', 'bottom-right', 'top-left', 'bottom-left'],
left: ['left', 'right', 'top', 'bottom', 'top-left', 'bottom-left', 'top-right', 'bottom-right'],
};

const offset = tooltipAnchor === 'cursor' ? 10 : 6;

return {
theme: colorScheme,
anchor: tooltipAnchor,
position: tooltipAnchor === 'mark' ? position[tooltipPlacement] : undefined,
offsetX: offset,
offsetY: offset,
};
};

const LegendTooltip: FC<LegendTooltipProps> = ({ value, descriptions, domain }) => {
const series = domain[value.index];
const description = descriptions.find((d) => d.seriesName === series);
Expand Down
33 changes: 30 additions & 3 deletions src/stories/Chart.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import React, { ReactElement } from 'react';
import { ReactElement } from 'react';

import useChartProps from '@hooks/useChartProps';
import { Axis, Chart, Line } from '@rsc';
import { Axis, Bar, Chart, ChartTooltip, Line } from '@rsc';
import { StoryFn } from '@storybook/react';
import { bindWithProps } from '@test-utils';

Expand Down Expand Up @@ -47,6 +47,26 @@ const ChartTimeStory: StoryFn<typeof Chart> = (args): ReactElement => {
);
};

const ChartBarTooltipStory: StoryFn<typeof Chart> = (args): ReactElement => {
const props = useChartProps(args);
return (
<Chart {...props}>
<Axis position="bottom" baseline />
<Axis position="left" grid />
<Bar dimension="x" metric="y" color="series">
<ChartTooltip>
{(datum) => (
<div className="bar-tooltip">
<div>x: {datum.x}</div>
<div>y: {datum.y}</div>
</div>
)}
</ChartTooltip>
</Bar>
</Chart>
);
};

const Basic = bindWithProps(ChartLineStory);

// Story specific props are passed here
Expand Down Expand Up @@ -91,4 +111,11 @@ Height.args = {
data,
};

export { Basic, BackgroundColor, Config, Locale, Width, Height };
const TooltipAnchor = bindWithProps(ChartBarTooltipStory);
TooltipAnchor.args = {
tooltipAnchor: 'mark',
tooltipPlacement: 'top',
data,
};

export { BackgroundColor, Basic, Config, Height, Locale, TooltipAnchor, Width };
59 changes: 57 additions & 2 deletions src/stories/Chart.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ import React, { createRef } from 'react';

import '@matchMediaMock';
import { Axis, Bar, Chart, ChartHandle, ChartTooltip, Line } from '@rsc';
import { findChart, getAllMarksByGroupName, render, screen } from '@test-utils';
import { findChart, getAllMarksByGroupName, hoverNthElement, render, screen } from '@test-utils';
import { getElement } from '@utils';

import { BackgroundColor, Basic, Config, Height, Locale, Width } from './Chart.story';
import { BackgroundColor, Basic, Config, Height, Locale, TooltipAnchor, Width } from './Chart.story';
import {
CssColors,
SpectrumColorNames,
Expand Down Expand Up @@ -298,4 +298,59 @@ describe('Chart', () => {
expect(getElement(PopoverTest, Line)).toStrictEqual(undefined);
});
});

describe('TooltipAnchor()', () => {
// get the integer value from a px string
const getPxValue = (pxString: string) => parseInt(pxString.replace('px', ''), 10);

test('should render the tooltip relative to the cursor if `tooltipAnchor` is set to `cursor`', async () => {
render(<TooltipAnchor {...TooltipAnchor.args} tooltipAnchor="cursor" />);

const chart = await findChart();
expect(chart).toBeInTheDocument();
const bars = getAllMarksByGroupName(chart, 'bar0');

await hoverNthElement(bars, 0);
const tooltip = document.getElementById('vg-tooltip-element');
expect(tooltip).toBeInTheDocument();
if (!tooltip) return;

// will be at 10, 10 since the cursor is at 0, 0 and the offset is 10
expect(getPxValue(tooltip.style.getPropertyValue('top'))).toBe(10);
expect(getPxValue(tooltip.style.getPropertyValue('left'))).toBe(10);
});

describe('tooltipAnchor = mark', () => {});

test('should render the tooltip relative to the mark if `tooltipAnchor` is set to `mark`', async () => {
render(<TooltipAnchor {...TooltipAnchor.args} tooltipAnchor="mark" tooltipPlacement="top" />);

const chart = await findChart();
expect(chart).toBeInTheDocument();
const bars = getAllMarksByGroupName(chart, 'bar0');

await hoverNthElement(bars, 0);
const tooltip = document.getElementById('vg-tooltip-element');
expect(tooltip).toBeInTheDocument();
if (!tooltip) return;

expect(getPxValue(tooltip.style.getPropertyValue('top'))).toBe(239);
expect(getPxValue(tooltip.style.getPropertyValue('left'))).toBe(35);
});

test('should render the tooltip to the right of the mark if placement is right', async () => {
render(<TooltipAnchor {...TooltipAnchor.args} tooltipAnchor="mark" tooltipPlacement="bottom" />);
const chart = await findChart();
expect(chart).toBeInTheDocument();
const bars = getAllMarksByGroupName(chart, 'bar0');

await hoverNthElement(bars, 0);
const tooltip = document.getElementById('vg-tooltip-element');
expect(tooltip).toBeInTheDocument();
if (!tooltip) return;

expect(getPxValue(tooltip.style.getPropertyValue('top'))).toBe(284);
expect(getPxValue(tooltip.style.getPropertyValue('left'))).toBe(35);
});
});
});
Loading
Loading