From 004d36d0b2945944ce85b1d5bc9ccdc858c0c399 Mon Sep 17 00:00:00 2001 From: Raj Jaiswal Date: Wed, 18 Nov 2026 16:12:37 +0000 Subject: [PATCH] feat: Add internal hover debounce to core chart In dense charts, series highlight, legend highlight, legend scroll-into-view and the tooltip all react to every pointer move, which causes a lot of motion. The existing tooltip.debounce only delays the tooltip. This adds an internal hoverDebounce prop to core chart (a number in ms, or true for 150ms). The hovered series and its legend item highlight as soon as the pointer reaches them, and onHighlight and onLegendItemHighlight fire at once. Dimming the other series and legend items waits for the delay when nothing is dimmed yet; once they are dimmed, moving to another target swaps the highlight at once. Column series dim at once, as their hover state alone is hard to see. The tooltip, including the legend item tooltip, waits for the delay, and the legend scrolls the highlighted item into view only after the pointer has rested for the delay. Undimming has no fade. highlightItems, highlightChartPoint and highlightChartGroup from the public API follow the same model, so a chart that syncs highlights through onHighlight lights the same series at once and dims after the delay. Keyboard navigation and legend item focus are not delayed. A pending hover is dropped when the pointer leaves its target or enters the tooltip, on Escape, chart focus, visibility changes, zoom start and destroy, and is replaced by a newer pointer, legend or API hover. The previewed highlight is then restored, and onHighlight or onClearHighlight reports the result. A click applies the pending hover first, so pinning doesn't wait, and a pending point or group is checked for visibility again when the delay ends. DebouncedCall can now take a key: scheduling the key that is already pending keeps it, flush() runs the pending call, and cancelPending() (renamed from cancelPrevious()) reports whether something was pending. tooltip.debounce is ignored while hoverDebounce is set, and is planned for removal. The core dev pages get a "Hover debounce (ms)" setting. Without hoverDebounce, the behavior is unchanged. --- pages/03-core/boost.page.tsx | 3 +- pages/03-core/core-bar-chart.page.tsx | 2 +- pages/03-core/core-dual-axis-chart.page.tsx | 5 +- pages/03-core/core-legend.page.tsx | 7 +- pages/03-core/core-line-chart.page.tsx | 1 + pages/03-core/heatmap.page.tsx | 17 +- pages/03-core/simple-zooming.page.tsx | 4 +- pages/03-core/solidgauge.page.tsx | 13 +- pages/common/page-settings.tsx | 18 +- .../chart-core-hover-debounce.test.tsx | 467 ++++++++++++++++++ src/core/__tests__/common.tsx | 13 +- src/core/chart-api/chart-extra-context.tsx | 4 + src/core/chart-api/chart-extra-highlight.ts | 185 ++++++- src/core/chart-api/chart-extra-legend.tsx | 33 +- src/core/chart-api/chart-extra-pointer.tsx | 65 ++- src/core/chart-api/chart-extra-tooltip.tsx | 36 +- src/core/chart-api/index.tsx | 211 +++++++- src/core/chart-core.tsx | 32 +- src/core/components/core-legend.tsx | 33 +- src/core/interfaces.ts | 1 + src/core/internal-interfaces.ts | 8 + .../components/chart-legend/index.tsx | 51 +- src/internal/utils/__tests__/utils.test.ts | 84 +++- src/internal/utils/highcharts.ts | 7 +- src/internal/utils/use-debounced-value.tsx | 4 +- src/internal/utils/utils.ts | 38 +- test/functional/hover-debounce.test.ts | 85 ++++ 27 files changed, 1323 insertions(+), 104 deletions(-) create mode 100644 src/core/__tests__/chart-core-hover-debounce.test.tsx create mode 100644 test/functional/hover-debounce.test.ts diff --git a/pages/03-core/boost.page.tsx b/pages/03-core/boost.page.tsx index 88ad1821..9c9b84f8 100644 --- a/pages/03-core/boost.page.tsx +++ b/pages/03-core/boost.page.tsx @@ -35,6 +35,7 @@ export default function () { ), }, + "hoverDebounce", ]} /> } @@ -56,7 +57,7 @@ function Component({ boostEnabled }: { boostEnabled: boolean }) { const { chartProps } = useChartSettings({ boost: true }); return ( }> + }>
} > } + settings={} > } diff --git a/pages/03-core/heatmap.page.tsx b/pages/03-core/heatmap.page.tsx index 22af22f3..0892d837 100644 --- a/pages/03-core/heatmap.page.tsx +++ b/pages/03-core/heatmap.page.tsx @@ -1,7 +1,12 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { ComponentType } from "react"; + +import { CoreChartProps } from "../../lib/components/core/interfaces"; +import { InternalHoverProps } from "../../lib/components/core/internal-interfaces"; import CoreChart from "../../lib/components/internal-do-not-use/core-chart"; +import { PageSettingsForm, useChartSettings } from "../common/page-settings"; import { Page } from "../common/templates"; import { useHighcharts } from "../common/use-highcharts"; import pseudoRandom from "../utils/pseudo-random"; @@ -39,13 +44,21 @@ function generateHeatmapData() { const { series, instances } = generateHeatmapData(); +const HoverCoreChart = CoreChart as ComponentType; + export default function () { const highcharts = useHighcharts({ heatmap: true }); + const { chartProps } = useChartSettings(); return ( - - } + > + ({ more: true }); - const commonProps = omit(chartProps.cartesian, ["ref"]); + const commonProps = chartProps.core; const scatterChartRef = useRef(null) as React.MutableRefObject; const getScatterChart = () => scatterChartRef.current!; const navigatorChartRef = useRef(null) as React.MutableRefObject; diff --git a/pages/03-core/solidgauge.page.tsx b/pages/03-core/solidgauge.page.tsx index a34963f6..9f24a6ca 100644 --- a/pages/03-core/solidgauge.page.tsx +++ b/pages/03-core/solidgauge.page.tsx @@ -1,8 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { omit } from "lodash"; - import CoreChart from "../../lib/components/internal-do-not-use/core-chart"; import { PageSettingsForm, useChartSettings } from "../common/page-settings"; import { Page } from "../common/templates"; @@ -28,12 +26,19 @@ export default function () { subtitle="This page demonstrates the use of solid gauge charts for displaying single-value metrics." settings={ } > (DEFAULT_SETTINGS); @@ -92,7 +94,7 @@ export function useChartSettings & InternalZoomProps & { ref: React.Ref }; pie: Omit & { ref: React.Ref }; - core: Omit & InternalZoomProps; + core: Omit & InternalZoomProps & InternalHoverProps; }; isEmpty: boolean; } { @@ -119,6 +121,7 @@ export function useChartSettings) => { setUrlParams(partial as Partial>); @@ -206,6 +209,7 @@ export function useChartSettings 0 ? settings.hoverDebounce : undefined, }, }, isEmpty: settings.emptySeries || settings.seriesLoading || settings.seriesError, @@ -517,6 +521,16 @@ export function PageSettingsForm({ Hide zoom controls ); + case "hoverDebounce": + return ( + + setSettings({ hoverDebounce: detail.value ? parseInt(detail.value) : 0 })} + /> + + ); case "useFallback": return ( ({ + header: () => `${point?.series.name} ${point?.x}`, + body: () => "Body", +}); + +const getLegendTooltipContent: CoreChartProps.GetLegendTooltipContent = ({ legendItem }) => ({ + header:
{legendItem.name}
, + body: <>Body, +}); + +const dimmedLegendItems = () => + createChartWrapper() + .findLegend()! + .findAll(`.${legendTestClasses["dimmed-item"]}`) + .map((w) => w.getElement().textContent); + +function mockPointCoordinates() { + hc.getChart().series.forEach((s, sIndex) => { + s.points.forEach((p) => { + p.plotX = p.index; + p.plotY = 1 + sIndex; + }); + }); +} + +const highlightMarkers = () => createChartWrapper().findAllByClassName(testClasses["highlight-marker"]).length; +const selectedMarkers = () => createChartWrapper().findAllByClassName(testClasses["highlight-marker-selected"]).length; +const selectedMarkerFill = () => + createChartWrapper().findByClassName(testClasses["highlight-marker-selected"])?.getElement().getAttribute("fill") ?? + null; + +const tooltipHeader = () => createChartWrapper().findTooltip()?.findHeader()?.getElement().textContent ?? null; +const legendTooltip = () => createChartWrapper().findLegend()!.findItemTooltip(); +const pressEscape = () => act(() => fireEvent.keyDown(document.body, { key: "Escape", keyCode: 27 })); +const focusLegendItem = (index: number) => act(() => createChartWrapper().findLegend()!.findItems()[index].focus()); + +beforeEach(() => { + vi.useFakeTimers(); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("CoreChart: hover debounce", () => { + test("highlights the hovered series and cursor at once, and dims the others and shows the tooltip once the delay passes", () => { + const onHighlight = vi.fn(); + renderChart({ highcharts, options: { series }, hoverDebounce: 100, getTooltipContent, onHighlight }); + + mockPointCoordinates(); + act(() => hc.highlightChartPoint(0, 1)); + act(() => vi.advanceTimersByTime(99)); + + expect(hc.getChartSeries(0).state).toBe("hover"); + expect(hc.getChartSeries(1).state).toBe(""); + expect(highlightMarkers()).toBe(2); + expect(selectedMarkers()).toBe(1); + expect(dimmedLegendItems()).toEqual([]); + expect(tooltipHeader()).toBe(null); + expect(onHighlight).toHaveBeenCalledTimes(1); + expect(onHighlight.mock.calls[0][0].detail.point).toBe(hc.getChartPoint(0, 1)); + + act(() => hc.highlightChartPoint(0, 1)); + act(() => vi.advanceTimersByTime(1)); + + expect(tooltipHeader()).toBe("L1 1"); + expect(hc.getChartSeries(1).state).toBe("inactive"); + expect(dimmedLegendItems()).toEqual(["L2"]); + expect(onHighlight).toHaveBeenCalledTimes(1); + }); + + test("drops a pending hover once the pointer leaves it, and restores the series and cursor", () => { + const onClearHighlight = vi.fn(); + renderChart({ highcharts, options: { series }, hoverDebounce: 100, getTooltipContent, onClearHighlight }); + + mockPointCoordinates(); + act(() => hc.highlightChartPoint(0, 1)); + act(() => vi.advanceTimersByTime(99)); + act(() => hc.leaveChartPoint(0, 1)); + act(() => vi.advanceTimersByTime(1)); + + expect(tooltipHeader()).toBe(null); + expect(dimmedLegendItems()).toEqual([]); + + act(() => vi.advanceTimersByTime(200)); + + expect(highlightMarkers()).toBe(0); + expect(hc.getChartSeries(0).state).toBe(""); + expect(hc.getChartSeries(1).state).toBe(""); + expect(onClearHighlight).toHaveBeenCalled(); + }); + + test("swaps the highlighted series at once once dimmed and applies the last target once it settles", () => { + const onHighlight = vi.fn(); + renderChart({ highcharts, options: { series }, hoverDebounce: 100, getTooltipContent, onHighlight }); + + act(() => hc.highlightChartPoint(0, 1)); + act(() => vi.advanceTimersByTime(100)); + act(() => hc.highlightChartPoint(1, 1)); + act(() => vi.advanceTimersByTime(60)); + act(() => hc.highlightChartPoint(1, 2)); + act(() => vi.advanceTimersByTime(60)); + + expect(tooltipHeader()).toBe("L1 1"); + expect(hc.getChartSeries(0).state).toBe("inactive"); + expect(dimmedLegendItems()).toEqual(["L1"]); + + act(() => vi.advanceTimersByTime(40)); + + expect(tooltipHeader()).toBe("L2 2"); + expect(onHighlight).toHaveBeenCalledTimes(3); + }); + + test.each([ + { + type: "column", + series: [ + { type: "column", name: "C1", data: [1, 2] }, + { type: "column", name: "C2", data: [3, 4] }, + ], + first: [0, 0], + second: [1, 1], + dimmedAtOnce: ["C2"], + }, + { + type: "pie", + series: [ + { + type: "pie", + name: "P", + data: [ + { name: "A", y: 1 }, + { name: "B", y: 2 }, + ], + }, + ], + first: [0, 0], + second: [0, 1], + dimmedAtOnce: [], + }, + ] as const)( + "highlights a hovered $type point at once, dims the others at once for columns, and swaps it at once when dimmed", + ({ series, first, second, dimmedAtOnce }) => { + renderChart({ highcharts, options: { series: series as Highcharts.SeriesOptionsType[] }, hoverDebounce: 100 }); + + act(() => hc.highlightChartPoint(...first)); + + expect(hc.getChartPoint(...first).state).toBe("hover"); + expect(hc.getChartPoint(...second).state === "inactive").toBe(dimmedAtOnce.length > 0); + expect(dimmedLegendItems()).toEqual(dimmedAtOnce); + + act(() => vi.advanceTimersByTime(100)); + + expect(hc.getChartPoint(...second).state).toBe("inactive"); + + act(() => hc.highlightChartPoint(...second)); + + expect(hc.getChartPoint(...second).state).toBe("hover"); + expect(hc.getChartPoint(...first).state).toBe("inactive"); + }, + ); + + test("uses a 150ms delay when hoverDebounce=true and ignores tooltip.debounce", () => { + renderChart({ + highcharts, + options: { series }, + hoverDebounce: true, + tooltip: { debounce: 500 }, + getTooltipContent, + }); + + act(() => hc.highlightChartPoint(0, 1)); + act(() => vi.advanceTimersByTime(149)); + expect(tooltipHeader()).toBe(null); + + act(() => hc.highlightChartPoint(0, 1)); + act(() => vi.advanceTimersByTime(1)); + expect(tooltipHeader()).toBe("L1 1"); + }); + + test("applies the same effects at once with a zero delay", () => { + renderChart({ highcharts, options: { series }, hoverDebounce: 0, getLegendTooltipContent }); + + hoverLegendItem(0); + + expect(hc.getChartSeries(1).state).toBe("inactive"); + expect(dimmedLegendItems()).toEqual(["L2"]); + + act(() => vi.advanceTimersByTime(1)); + + expect(legendTooltip()).not.toBe(null); + }); + + test("drops a pending target when the pointer enters the tooltip", () => { + renderChart({ highcharts, options: { series }, hoverDebounce: 100, getTooltipContent }); + + act(() => hc.highlightChartPoint(0, 1)); + act(() => vi.advanceTimersByTime(100)); + act(() => hc.highlightChartPoint(1, 2)); + act(() => { + fireEvent.mouseEnter(createChartWrapper().findTooltip()!.getElement()); + }); + act(() => vi.advanceTimersByTime(200)); + + expect(tooltipHeader()).toBe("L1 1"); + expect(dimmedLegendItems()).toEqual(["L2"]); + }); + + test("pins the tooltip on click without waiting for the delay", () => { + const data = [ + { name: "P1", y: 10 }, + { name: "P2", y: 30 }, + ]; + renderChart({ + highcharts, + options: { series: [{ type: "pie", name: "Pie", data }] }, + hoverDebounce: 100, + getTooltipContent: ({ point }) => ({ header: () => `${point?.name}`, body: () => "Body" }), + }); + + act(() => hc.highlightChartPoint(0, 1)); + act(() => hc.clickChartPoint(0, 1)); + + expect(tooltipHeader()).toBe("P2"); + expect(createChartWrapper().findTooltip()!.findDismissButton()).not.toBe(null); + }); + + test("skips a pending point that is no longer visible and clears its cursor", () => { + renderChart({ highcharts, options: { series }, hoverDebounce: 100, getTooltipContent }); + + mockPointCoordinates(); + act(() => hc.highlightChartPoint(0, 1)); + act(() => { + hc.getChartPoint(0, 1).visible = false; + }); + act(() => vi.advanceTimersByTime(200)); + + expect(tooltipHeader()).toBe(null); + expect(highlightMarkers()).toBe(0); + expect(hc.getChartSeries(0).state).toBe(""); + }); + + test.each([ + { + name: "the chart receives keyboard focus", + action: () => act(() => createChartWrapper().findApplication()!.focus()), + }, + { name: "Escape is pressed", action: pressEscape }, + { name: "series visibility changes", action: () => toggleLegendItem(1) }, + ])("drops a pending pointer hover when $name", ({ action }) => { + const onHighlight = vi.fn(); + renderStatefulChart({ + highcharts, + options: { series }, + hoverDebounce: 100, + visibleItems: ["L1", "L2"], + getTooltipContent, + onHighlight, + }); + + act(() => hc.highlightChartPoint(0, 1)); + action(); + act(() => vi.advanceTimersByTime(200)); + + expect(tooltipHeader()).toBe(null); + expect(dimmedLegendItems()).toEqual([]); + expect(onHighlight).toHaveBeenCalledTimes(1); + }); + + test("drops a pending pointer hover when a zoom selection starts", () => { + renderZoomChart({ zoom: { enabled: true }, hoverDebounce: 100, getTooltipContent }); + + act(() => hc.highlightChartPoint(0, 1)); + enterZoomMode(); + act(() => vi.advanceTimersByTime(200)); + + expect(tooltipHeader()).toBe(null); + expect(dimmedLegendItems()).toEqual([]); + }); + + describe("API", () => { + test("lights the series at once and dims the others after the delay", () => { + let api: null | CoreChartProps.ChartAPI = null; + renderChart({ highcharts, options: { series }, hoverDebounce: 100, callback: (chartApi) => (api = chartApi) }); + + act(() => api!.highlightItems(["L1"])); + + expect(hc.getChartSeries(0).state).toBe("hover"); + expect(hc.getChartSeries(1).state).toBe(""); + expect(dimmedLegendItems()).toEqual([]); + + act(() => vi.advanceTimersByTime(100)); + + expect(hc.getChartSeries(1).state).toBe("inactive"); + expect(dimmedLegendItems()).toEqual(["L2"]); + + act(() => api!.clearChartHighlight()); + + expect(hc.getChartSeries(1).state).toBe(""); + expect(dimmedLegendItems()).toEqual([]); + }); + + test("replaces a pending pointer hover and its cursor", () => { + let api: null | CoreChartProps.ChartAPI = null; + renderChart({ + highcharts, + options: { series }, + hoverDebounce: 100, + getTooltipContent, + callback: (chartApi) => (api = chartApi), + }); + + mockPointCoordinates(); + act(() => hc.highlightChartPoint(0, 1)); + act(() => api!.highlightChartPoint(hc.getChartPoint(1, 2))); + + expect(hc.getChartSeries(1).state).toBe("hover"); + expect(selectedMarkerFill()).toBe(hc.getChartSeries(1).color); + + act(() => vi.advanceTimersByTime(200)); + + expect(tooltipHeader()).toBe("L2 2"); + }); + }); + + describe("legend", () => { + test("highlights a hovered item's series at once, and dims the others and shows the item tooltip once the delay passes", () => { + const onLegendItemHighlight = vi.fn(); + renderChart({ + highcharts, + options: { series }, + hoverDebounce: 100, + getLegendTooltipContent, + onLegendItemHighlight, + }); + + hoverLegendItem(0); + act(() => vi.advanceTimersByTime(99)); + + expect(hc.getChartSeries(0).state).toBe("hover"); + expect(hc.getChartSeries(1).state).toBe(""); + expect(dimmedLegendItems()).toEqual([]); + expect(legendTooltip()).toBe(null); + expect(onLegendItemHighlight).toHaveBeenCalledTimes(1); + + act(() => vi.advanceTimersByTime(1)); + + expect(hc.getChartSeries(0).state).toBe("hover"); + expect(hc.getChartSeries(1).state).toBe("inactive"); + expect(dimmedLegendItems()).toEqual(["L2"]); + expect(legendTooltip()).not.toBe(null); + expect(onLegendItemHighlight).toHaveBeenCalledTimes(1); + }); + + test("drops a pending item highlight as soon as the pointer leaves it", () => { + renderChart({ highcharts, options: { series }, hoverDebounce: 100 }); + + hoverLegendItem(0); + act(() => vi.advanceTimersByTime(90)); + leaveLegendItem(0); + act(() => vi.advanceTimersByTime(15)); + + expect(dimmedLegendItems()).toEqual([]); + + act(() => vi.advanceTimersByTime(500)); + + expect(hc.getChartSeries(0).state).toBe(""); + }); + + test("drops a pending item highlight when the item is toggled", () => { + renderStatefulChart({ highcharts, options: { series }, hoverDebounce: 100, visibleItems: ["L1", "L2"] }); + + hoverLegendItem(0); + toggleLegendItem(0); + act(() => vi.advanceTimersByTime(200)); + + expect(hc.getChartSeries(1).state).toBe(""); + }); + + test("lets Escape cancel a pending item highlight and tooltip, and clears the highlight it reported", () => { + const onClearHighlight = vi.fn(); + renderChart({ highcharts, options: { series }, hoverDebounce: 100, getLegendTooltipContent, onClearHighlight }); + + hoverLegendItem(0); + act(() => vi.advanceTimersByTime(50)); + pressEscape(); + act(() => vi.advanceTimersByTime(200)); + + expect(legendTooltip()).toBe(null); + expect(hc.getChartSeries(0).state).toBe(""); + expect(dimmedLegendItems()).toEqual([]); + expect(onClearHighlight).toHaveBeenCalledTimes(1); + }); + + test("highlights a focused item at once, replacing pending pointer and legend hovers", () => { + renderChart({ highcharts, options: { series }, hoverDebounce: 100, getTooltipContent }); + + act(() => hc.highlightChartPoint(0, 1)); + hoverLegendItem(0); + focusLegendItem(1); + + expect(dimmedLegendItems()).toEqual(["L1"]); + + act(() => vi.advanceTimersByTime(200)); + + expect(dimmedLegendItems()).toEqual(["L1"]); + expect(tooltipHeader()).toBe(null); + }); + + test("keeps a new item highlight when the plot hover is lost", () => { + renderChart({ highcharts, options: { series }, hoverDebounce: 100, getTooltipContent }); + + act(() => hc.highlightChartPoint(0, 1)); + act(() => hc.leaveChartPoint(0, 1)); + hoverLegendItem(1); + act(() => vi.advanceTimersByTime(200)); + + expect(dimmedLegendItems()).toEqual(["L1"]); + }); + + test("does not reopen the item tooltip after the delay changes and the pointer leaves", () => { + const { rerender } = renderChart({ + highcharts, + options: { series }, + hoverDebounce: 300, + getLegendTooltipContent, + }); + + hoverLegendItem(0); + rerender({ highcharts, options: { series }, hoverDebounce: 100, getLegendTooltipContent }); + leaveLegendItem(0); + act(() => vi.advanceTimersByTime(500)); + + expect(legendTooltip()).toBe(null); + }); + }); +}); diff --git a/src/core/__tests__/common.tsx b/src/core/__tests__/common.tsx index c8405afe..68dc7e52 100644 --- a/src/core/__tests__/common.tsx +++ b/src/core/__tests__/common.tsx @@ -10,7 +10,7 @@ import { ButtonWrapper } from "@cloudscape-design/components/test-utils/dom"; import "@cloudscape-design/components/test-utils/dom"; import { CoreChartProps } from "../../../lib/components/core/interfaces"; -import { InternalZoomProps } from "../../../lib/components/core/internal-interfaces"; +import { InternalHoverProps, InternalZoomProps } from "../../../lib/components/core/internal-interfaces"; import testClasses from "../../../lib/components/core/test-classes/styles.selectors"; import { fireNonCancelableEvent } from "../../../lib/components/internal/events"; import { TestI18nProvider } from "../../../lib/components/internal/utils/test-i18n-provider"; @@ -31,9 +31,9 @@ export class ExtendedTestWrapper extends CoreChartWrapper { } // The core chart accepts the internal zoom properties, which are not part of its public interface yet. -const CoreChartWithZoom = CoreChart as React.ComponentType; +const CoreChartWithZoom = CoreChart as React.ComponentType; -export function StatefulChart(props: CoreChartProps & InternalZoomProps) { +export function StatefulChart(props: CoreChartProps & InternalZoomProps & InternalHoverProps) { const [visibleItems, setVisibleItems] = useState(props.visibleItems ?? []); const [zoomRange, setZoomRange] = useState(props.zoomRange); return ( @@ -55,16 +55,17 @@ export function StatefulChart(props: CoreChartProps & InternalZoomProps) { } export type CoreChartTestProps = Partial & - InternalZoomProps & { + InternalZoomProps & + InternalHoverProps & { onLegendItemHighlight?: () => void; i18nProvider?: Record>; }; export function renderChart( { i18nProvider, ...props }: CoreChartTestProps, - Component: React.ComponentType = CoreChartWithZoom, + Component: React.ComponentType = CoreChartWithZoom, ) { - const ComponentWrapper = (props: CoreChartProps & InternalZoomProps) => { + const ComponentWrapper = (props: CoreChartProps & InternalZoomProps & InternalHoverProps) => { return i18nProvider ? ( diff --git a/src/core/chart-api/chart-extra-context.tsx b/src/core/chart-api/chart-extra-context.tsx index 47d5e053..c9a85232 100644 --- a/src/core/chart-api/chart-extra-context.tsx +++ b/src/core/chart-api/chart-extra-context.tsx @@ -34,6 +34,8 @@ export namespace ChartExtraContext { labels: ChartLabels; getItemOptions?: CoreChartProps.GetItemOptions; zoomEnabled: boolean; + hoverDelay: number; + hoverDebounceEnabled: boolean; } export interface Handlers { @@ -68,6 +70,8 @@ export function createChartContext(): ChartExtraContext { keyboardNavigationEnabled: false, labels: {}, zoomEnabled: false, + hoverDelay: -1, + hoverDebounceEnabled: false, }, handlers: {}, state: {}, diff --git a/src/core/chart-api/chart-extra-highlight.ts b/src/core/chart-api/chart-extra-highlight.ts index 6abf89a7..49135900 100644 --- a/src/core/chart-api/chart-extra-highlight.ts +++ b/src/core/chart-api/chart-extra-highlight.ts @@ -8,6 +8,7 @@ import { getChartSeries, getLinkedSeries, getMasterSeries, + getMasterSeriesOf, getSeriesData, SafeChart, SafeSeries, @@ -32,6 +33,8 @@ export class ChartExtraHighlight { // The recover is necessary if the chart was re-rendered while the highlighting is set. For example, // when triggered a state update from the consumer-provided tooltip footer action. private seriesState = new Map(); + private previewState = new Map(); + private pointPreviewState = new Map>(); private pointState = new Map>(); private columnStatesSynced = false; @@ -43,6 +46,7 @@ export class ChartExtraHighlight { // The method highlights specified series or points (by id). It is used when hovering over the legend items. public highlightChartItems = (itemIds: readonly string[]) => { + this.discardPreview(); const itemIdsSet = new Set(itemIds); for (const s of getChartSeries(this.context.chart())) { // In pie charts it is the points, not series, that are shown in the legend, and can be highlighted. @@ -55,7 +59,8 @@ export class ChartExtraHighlight { } else { const seriesActive = itemIdsSet.has(getSeriesId(s)); const masterSeriesActive = s.linkedParent ? itemIdsSet.has(getSeriesId(s.linkedParent)) : false; - this.setSeriesState(s, seriesActive || masterSeriesActive ? "" : "inactive"); + const activeState = this.context.settings.hoverDebounceEnabled ? "hover" : ""; + this.setSeriesState(s, seriesActive || masterSeriesActive ? activeState : "inactive"); } } setPlotLinesState(this.context.chart(), (lineId) => itemIdsSet.has(lineId)); @@ -65,6 +70,7 @@ export class ChartExtraHighlight { // do not have IDs, so we match points and series by their references instead. This is used to control // highlight state when chart elements are hovered or focused. public highlightChartGroup = (points: readonly Highcharts.Point[]) => { + this.discardPreview(); const includedPoints = new Set(); const includedSeries = new Set(); const includedSeriesIds = new Set(); @@ -92,6 +98,7 @@ export class ChartExtraHighlight { // This method is similar to the above, but it takes a single point. This is used for point highlighting // in cartesian charts, and for pie chart segments. public highlightChartPoint = (point: Highcharts.Point) => { + this.discardPreview(); const masterSeries = getMasterSeries(point); const linkedSeries = new Set(getLinkedSeries(point)); for (const s of getChartSeries(this.context.chart())) { @@ -116,8 +123,149 @@ export class ChartExtraHighlight { setPlotLinesState(this.context.chart(), (lineId) => lineId === getSeriesId(masterSeries)); }; + public previewChartPoint = (point: Highcharts.Point) => { + const linkedSeries = new Set(getLinkedSeries(point)); + return this.previewStates( + (s) => (linkedSeries.has(s) ? "hover" : null), + (p) => (p === point ? "hover" : null), + ["pie", "column"], + point.series.type === "column", + ); + }; + + public previewChartGroup = (group: readonly Highcharts.Point[]) => { + const groupPoints = new Set(group); + const groupSeriesIds = new Set(group.map((p) => getSeriesId(getMasterSeries(p)))); + return this.previewStates( + (s) => (groupSeriesIds.has(getSeriesId(getMasterSeriesOf(s))) ? "" : null), + (p) => (groupPoints.has(p) ? "" : null), + ["column"], + group.some((p) => p.series.type === "column"), + ); + }; + + public previewChartItems = (itemIds: readonly string[]) => { + return this.previewStates( + (s) => (itemIds.includes(getSeriesId(getMasterSeriesOf(s))) ? "hover" : null), + (p) => (itemIds.includes(getPointId(p)) ? "hover" : null), + ["pie"], + getChartSeries(this.context.chart()).some( + (s) => s.type === "column" && itemIds.includes(getSeriesId(getMasterSeriesOf(s))), + ), + ); + }; + + private previewStates( + getSeriesTargetState: (series: SafeSeries) => null | "" | "hover", + getPointTargetState: (point: Highcharts.Point) => null | "" | "hover", + pointSeriesTypes: readonly string[], + dimAtOnce: boolean, + ) { + const dimmed = dimAtOnce || this.isDimmed(); + const getNonTargetState = (appliedState: "" | State) => + dimmed ? "inactive" : appliedState === "hover" ? "" : appliedState; + const hoveredPoints: Highcharts.Point[] = []; + for (const s of getChartSeries(this.context.chart())) { + if (s.type !== "pie") { + this.setSeriesPreviewState(s, getSeriesTargetState(s) ?? getNonTargetState(this.getSeriesState(s))); + } + if (pointSeriesTypes.includes(s.type)) { + for (const p of getSeriesData(s)) { + const state = getPointTargetState(p) ?? getNonTargetState(this.getPointState(p)); + if (state === "hover") { + hoveredPoints.push(p); + } else { + this.setPointPreviewState(p, state); + } + } + } + } + hoveredPoints.forEach((p) => this.setPointPreviewState(p, "hover")); + return dimmed; + } + + public cancelPreview = () => { + if (this.previewState.size === 0 && this.pointPreviewState.size === 0) { + return; + } + const previewedSeries = this.previewState; + const previewedPoints = this.pointPreviewState; + this.discardPreview(); + const hoveredPoints: Highcharts.Point[] = []; + for (const s of getChartSeries(this.context.chart())) { + if (previewedSeries.has(getSeriesId(s))) { + this.applySeriesState(s, this.getSeriesState(s)); + } + const previewedSeriesPoints = previewedPoints.get(getSeriesId(s)); + for (const p of previewedSeriesPoints ? getSeriesData(s) : []) { + if (previewedSeriesPoints?.has(this.getPointKey(p))) { + const state = this.getPointState(p); + if (state === "hover") { + hoveredPoints.push(p); + } else { + this.applyPointState(p, state); + } + } + } + } + hoveredPoints.forEach((p) => this.applyPointState(p, "hover")); + }; + + private discardPreview() { + this.previewState = new Map(); + this.pointPreviewState = new Map(); + } + + private isDimmed() { + return ( + [...this.seriesState.values()].includes("inactive") || + [...this.pointState.values()].some((states) => [...states.values()].includes("inactive")) + ); + } + + private getSeriesState(series: SafeSeries) { + return this.seriesState.get(getSeriesId(series)) ?? ""; + } + + private getPointState(point: Highcharts.Point) { + return this.pointState.get(getSeriesId(point.series))?.get(this.getPointKey(point)) ?? ""; + } + + private withInstantUndim(series: { options: object }, state: string, setState: () => void) { + if (this.context.settings.hoverDebounceEnabled) { + applyWithInstantUndim(series, state, setState); + } else { + setState(); + } + } + + private setSeriesPreviewState(series: SafeSeries, state: "" | Highcharts.SeriesStateValue) { + this.previewState.set(getSeriesId(series), state); + this.applySeriesState(series, state); + } + + private setPointPreviewState(point: Highcharts.Point, state: "" | Highcharts.PointStateValue) { + const seriesPoints = this.pointPreviewState.get(getSeriesId(point.series)) ?? new Map(); + seriesPoints.set(this.getPointKey(point), state); + this.pointPreviewState.set(getSeriesId(point.series), seriesPoints); + this.applyPointState(point, state, point.series.type !== "column" || !this.columnStatesSynced); + } + + private applySeriesState(series: SafeSeries, state: "" | Highcharts.SeriesStateValue) { + (series.setState as SeriesSetStateWithLock)[SET_STATE_LOCK] = false; + this.withInstantUndim(series, state, () => series.setState(state, false)); + (series.setState as SeriesSetStateWithLock)[SET_STATE_LOCK] = true; + } + + private applyPointState(point: Highcharts.Point, state: "" | Highcharts.PointStateValue, move = true) { + (point.setState as PointSetStateWithLock)[SET_STATE_LOCK] = false; + this.withInstantUndim(point.series, state, () => point.setState(state, move)); + (point.setState as PointSetStateWithLock)[SET_STATE_LOCK] = true; + } + // Removes dimmed state from all series and points. public clearChartItemsHighlight = () => { + this.discardPreview(); for (const s of getChartSeries(this.context.chart())) { this.setSeriesState(s, ""); for (const p of getSeriesData(s)) { @@ -129,18 +277,14 @@ export class ChartExtraHighlight { // Makes the specified series active or dimmed. private setSeriesState(series: SafeSeries, state: "" | Highcharts.SeriesStateValue) { - (series.setState as SeriesSetStateWithLock)[SET_STATE_LOCK] = false; - series.setState(state, false); + this.applySeriesState(series, state); this.updateStoredSeriesState(series, state); - (series.setState as SeriesSetStateWithLock)[SET_STATE_LOCK] = true; } // Makes the specified point active or dimmed. private setPointState(point: Highcharts.Point, state: "" | Highcharts.PointStateValue, move = true) { - (point.setState as PointSetStateWithLock)[SET_STATE_LOCK] = false; - point.setState(state, move); + this.applyPointState(point, state, move); this.updateStoredPointState(point, state); - (point.setState as PointSetStateWithLock)[SET_STATE_LOCK] = true; } // Restores series and points highlight state after chart's re-render. @@ -162,6 +306,19 @@ export class ChartExtraHighlight { } } setPlotLinesState(this.context.chart(), (lineId) => !inactiveSeriesIds.has(lineId)); + for (const s of getChartSeries(this.context.chart())) { + const previewState = this.previewState.get(getSeriesId(s)); + if (previewState !== undefined) { + this.applySeriesState(s, previewState); + } + const pointPreviewStates = this.pointPreviewState.get(getSeriesId(s)); + for (const p of pointPreviewStates ? getSeriesData(s) : []) { + const pointPreviewState = pointPreviewStates?.get(this.getPointKey(p)); + if (pointPreviewState !== undefined) { + this.applyPointState(p, pointPreviewState); + } + } + } } private updateStoredSeriesState(series: SafeSeries, state: "" | Highcharts.SeriesStateValue) { @@ -236,3 +393,17 @@ function iteratePlotLines(chart: SafeChart, cb: (lineId: string, line: Highchart } }); } + +function applyWithInstantUndim(series: { options: object }, state: string, setState: () => void) { + const states = (series.options as { states?: Record }).states; + if (state === "inactive" || !states) { + setState(); + return; + } + const key = state || "normal"; + const stateOptions = states[key] ?? (states[key] = {}); + const animation = stateOptions.animation; + stateOptions.animation = { duration: 1 }; + setState(); + stateOptions.animation = animation; +} diff --git a/src/core/chart-api/chart-extra-legend.tsx b/src/core/chart-api/chart-extra-legend.tsx index bdbde6f0..223e308d 100644 --- a/src/core/chart-api/chart-extra-legend.tsx +++ b/src/core/chart-api/chart-extra-legend.tsx @@ -17,6 +17,8 @@ import { ChartExtraContext } from "./chart-extra-context"; // The reactive state is used to propagate changes in legend items to the core legend React component. export interface ReactiveLegendState { items: readonly CoreChartProps.LegendItem[]; + previewItemIds: readonly string[]; + previewDimmed: boolean; } // Chart helper that implements custom legend behaviors. @@ -25,7 +27,7 @@ export class ChartExtraLegend extends AsyncStore { private visibilityMode: "internal" | "external" = "external"; constructor(context: ChartExtraContext) { - super({ items: [] }); + super({ items: [], previewItemIds: [], previewDimmed: false }); this.context = context; } @@ -74,15 +76,42 @@ export class ChartExtraLegend extends AsyncStore { public onHighlightItems = (highlightedItems: readonly string[]) => { const currentItems = this.get().items; const updatedItems = currentItems.map(({ ...i }) => ({ ...i, highlighted: highlightedItems.includes(i.id) })); + this.onCancelPreview(); this.updateLegendItems(updatedItems); }; // Clears legend highlight state. public onClearHighlight = () => { const nextItems = this.get().items.map(({ ...item }) => ({ ...item, highlighted: false })); + this.onCancelPreview(); this.updateLegendItems(nextItems); }; + public onPreviewPoint = (point: Highcharts.Point, dimmed: boolean) => { + const itemIds = point.series.type === "pie" ? [getPointId(point)] : [getSeriesId(getMasterSeries(point))]; + this.onPreviewItems(itemIds, dimmed); + }; + + public onPreviewGroup = (group: readonly Highcharts.Point[], dimmed: boolean) => { + this.onPreviewItems( + group.map((point) => getSeriesId(getMasterSeries(point))), + dimmed, + ); + }; + + public onPreviewItems = (itemIds: readonly string[], dimmed: boolean) => { + const state = this.get(); + if (!isEqualArrays(state.previewItemIds, itemIds, (a, b) => a === b) || state.previewDimmed !== dimmed) { + this.set((state) => ({ ...state, previewItemIds: itemIds, previewDimmed: dimmed })); + } + }; + + public onCancelPreview = () => { + if (this.get().previewItemIds.length > 0) { + this.set((state) => ({ ...state, previewItemIds: [], previewDimmed: false })); + } + }; + private initLegend = () => { const prevState = this.get().items.reduce((map, item) => map.set(item.id, item), new Map()); const itemSpecs = getChartLegendItems({ @@ -111,7 +140,7 @@ export class ChartExtraLegend extends AsyncStore { ); } if (!isEqualArrays(this.get().items, nextItems, isLegendItemsEqual)) { - this.set(() => ({ items: nextItems })); + this.set((state) => ({ ...state, items: nextItems })); } }; diff --git a/src/core/chart-api/chart-extra-pointer.tsx b/src/core/chart-api/chart-extra-pointer.tsx index eaf70eae..98464956 100644 --- a/src/core/chart-api/chart-extra-pointer.tsx +++ b/src/core/chart-api/chart-extra-pointer.tsx @@ -4,16 +4,20 @@ import type Highcharts from "highcharts"; import { getChartSeries, isPointVisible, SafeChart } from "../../internal/utils/highcharts"; -import { DebouncedCall } from "../../internal/utils/utils"; +import { DebouncedCall, isEqualArrays } from "../../internal/utils/utils"; import { isInsidePlot } from "../utils"; import { ChartExtraContext } from "./chart-extra-context"; const HOVER_LOST_DELAY = 25; +export type PointerHoverTarget = Highcharts.Point | Highcharts.Point[]; + export interface ChartExtraPointerHandlers { onPointHover(point: Highcharts.Point): void; onGroupHover(group: Highcharts.Point[]): void; onHoverLost(): void; + onHoverPreview(target: PointerHoverTarget): void; + onHoverPreviewCancel(): void; onPointClick(point: Highcharts.Point): void; onGroupClick(group: Highcharts.Point[]): void; isLocked(): boolean; @@ -27,6 +31,9 @@ export class ChartExtraPointer { private hoveredGroup: null | Highcharts.Point[] = null; private tooltipHovered = false; private hoverLostCall = new DebouncedCall(); + private hover = new DebouncedCall(isSameHoverTarget); + private pointerMoveDocument: null | Document = null; + private lastPointerMoveAt = 0; constructor(context: ChartExtraContext, handlers: ChartExtraPointerHandlers) { this.context = context; @@ -34,11 +41,28 @@ export class ChartExtraPointer { } public onChartLoad = (chart: SafeChart) => { + this.trackPointerMoves(chart.container.ownerDocument); chart.container.addEventListener("mousemove", this.onChartMousemove); chart.container.addEventListener("mouseout", this.onChartMouseout); }; + public cancelPendingHover = () => this.hover.cancelPending(); + + public getLastPointerMoveAt = () => this.lastPointerMoveAt; + + private trackPointerMoves(document: null | Document) { + this.pointerMoveDocument?.removeEventListener("mousemove", this.onDocumentMousemove, { capture: true }); + this.pointerMoveDocument = document; + this.pointerMoveDocument?.addEventListener("mousemove", this.onDocumentMousemove, { capture: true, passive: true }); + } + + private onDocumentMousemove = () => { + this.lastPointerMoveAt = Date.now(); + }; + public onChartDestroy = () => { + this.hover.cancelPending(); + this.trackPointerMoves(null); this.context.chartOrNull?.container?.removeEventListener("mousemove", this.onChartMousemove); this.context.chartOrNull?.container?.removeEventListener("mouseout", this.onChartMouseout); }; @@ -67,6 +91,9 @@ export class ChartExtraPointer { this.tooltipHovered = true; this.hoveredPoint = null; this.hoveredGroup = null; + if (this.hover.cancelPending()) { + this.handlers.onHoverPreviewCancel(); + } }; // When the pointer leaves the tooltip it can hover another point or group. If that does not happen, @@ -150,6 +177,7 @@ export class ChartExtraPointer { if (this.handlers.isLocked()) { return false; } + this.hover.flush(); const targetPoint = point ?? (this.hoveredPoint && isPointVisible(this.hoveredPoint) ? this.hoveredPoint : null); if (targetPoint) { this.handlers.onPointClick(targetPoint); @@ -166,7 +194,7 @@ export class ChartExtraPointer { if (isPointVisible(point)) { this.hoveredPoint = point; this.hoveredGroup = null; - this.handlers.onPointHover(point); + this.scheduleHover(point); this.applyCursorStyle(); } }; @@ -176,7 +204,7 @@ export class ChartExtraPointer { const availablePoints = group.filter(isPointVisible); this.hoveredPoint = null; this.hoveredGroup = availablePoints; - this.handlers.onGroupHover(availablePoints); + this.scheduleHover(availablePoints); this.applyCursorStyle(); } }; @@ -193,6 +221,30 @@ export class ChartExtraPointer { }, HOVER_LOST_DELAY); }; + private scheduleHover = (target: PointerHoverTarget) => { + if (this.hover.call(() => this.applyHover(target), this.context.settings.hoverDelay, target)) { + this.handlers.onHoverPreview(target); + } + }; + + private applyHover = (target: PointerHoverTarget) => { + const current = this.hoveredPoint ?? this.hoveredGroup; + if (!current || !isSameHoverTarget(current, target)) { + this.handlers.onHoverPreviewCancel(); + } else if (Array.isArray(target)) { + const group = target.filter(isPointVisible); + if (group.length > 0 || target.length === 0) { + this.handlers.onGroupHover(group); + } else { + this.handlers.onHoverPreviewCancel(); + } + } else if (isPointVisible(target)) { + this.handlers.onPointHover(target); + } else { + this.handlers.onHoverPreviewCancel(); + } + }; + private applyCursorStyle = () => { const container = this.context.chart().container; if (container) { @@ -201,3 +253,10 @@ export class ChartExtraPointer { } }; } + +export function isSameHoverTarget(a: PointerHoverTarget, b: PointerHoverTarget) { + if (Array.isArray(a) && Array.isArray(b)) { + return isEqualArrays(a, b, (x, y) => x === y); + } + return a === b; +} diff --git a/src/core/chart-api/chart-extra-tooltip.tsx b/src/core/chart-api/chart-extra-tooltip.tsx index d9c8cce2..6c36a39c 100644 --- a/src/core/chart-api/chart-extra-tooltip.tsx +++ b/src/core/chart-api/chart-extra-tooltip.tsx @@ -96,6 +96,20 @@ export class ChartExtraTooltip extends AsyncStore { } } + public showCursor(point: null | Highcharts.Point, group: readonly Highcharts.Point[]) { + if (!this.tooltipLock && this.chartType === "cartesian") { + this.createCursor(point, group); + } + } + + public restoreCursor() { + if (this.lastGroup && this.get().visible) { + this.updateTooltipCursor({ point: this.lastPoint, group: this.lastGroup }); + } else { + this.cursor.hide(); + } + } + public hideTooltip() { this.cursor.hide(); this.targetTrack.hide(); @@ -127,9 +141,7 @@ export class ChartExtraTooltip extends AsyncStore { this.lastPoint = props.point; this.lastGroup = props.group; - const chartType = - getChartSeries(this.context.chart()).find((s) => s.type === "pie" || s.type === "solidgauge")?.type ?? - "cartesian"; + const chartType = this.chartType; if (chartType === "pie") { return this.updateTooltipCursorPie(props.group[0]); } else if (chartType === "solidgauge") { @@ -148,14 +160,24 @@ export class ChartExtraTooltip extends AsyncStore { }) => { const pointRect = point ? getPointRect(point) : getGroupRect(group.slice(0, 1)); const groupRect = getGroupRect(group); + this.createCursor(point, group); + this.targetTrack.rect(this.context.chart().renderer, { ...pointRect, ...this.commonTrackAttrs }); + this.groupTrack.rect(this.context.chart().renderer, { ...groupRect, ...this.commonTrackAttrs }); + }; + + private createCursor(point: null | Highcharts.Point, group: readonly Highcharts.Point[]) { // The cursor is not shown when column series are present (a UX decision). const hideCursorLine = getChartSeries(this.context.chart()).some( (s) => s.type === "column" || s.type === "heatmap", ); - this.cursor.create(groupRect, point, group, !hideCursorLine); - this.targetTrack.rect(this.context.chart().renderer, { ...pointRect, ...this.commonTrackAttrs }); - this.groupTrack.rect(this.context.chart().renderer, { ...groupRect, ...this.commonTrackAttrs }); - }; + this.cursor.create(getGroupRect(group), point, group, !hideCursorLine); + } + + private get chartType() { + return ( + getChartSeries(this.context.chart()).find((s) => s.type === "pie" || s.type === "solidgauge")?.type ?? "cartesian" + ); + } private updateTooltipCursorPie = (point: Highcharts.Point) => { // We only create target track for pie chart as pie chart does not support groups. diff --git a/src/core/chart-api/index.tsx b/src/core/chart-api/index.tsx index 0a517d72..ec72f679 100644 --- a/src/core/chart-api/index.tsx +++ b/src/core/chart-api/index.tsx @@ -7,7 +7,7 @@ import type Highcharts from "highcharts"; import { fireNonCancelableEvent } from "../../internal/events"; import { ReadonlyAsyncStore } from "../../internal/utils/async-store"; import { getChartSeries, getSeriesData } from "../../internal/utils/highcharts"; -import { Writeable } from "../../internal/utils/utils"; +import { DebouncedCall, isEqualArrays, Writeable } from "../../internal/utils/utils"; import { CoreChartProps } from "../interfaces"; import { getChartAccessibleDescription, @@ -21,10 +21,20 @@ import { ChartExtraHighlight } from "./chart-extra-highlight"; import { ChartExtraLegend, ReactiveLegendState } from "./chart-extra-legend"; import { ChartExtraNavigation, ChartExtraNavigationHandlers } from "./chart-extra-navigation"; import { ChartExtraNodata, ReactiveNodataState } from "./chart-extra-nodata"; -import { ChartExtraPointer, ChartExtraPointerHandlers } from "./chart-extra-pointer"; +import { + ChartExtraPointer, + ChartExtraPointerHandlers, + isSameHoverTarget, + PointerHoverTarget, +} from "./chart-extra-pointer"; import { ChartExtraTooltip, ReactiveTooltipState } from "./chart-extra-tooltip"; import { ChartExtraZoom, ChartExtraZoomHandlers, ReactiveZoomState } from "./chart-extra-zoom"; +interface HighlightTarget { + point: null | Highcharts.Point; + group: readonly Highcharts.Point[]; +} + // The API helper injects Cloudscape custom behaviors, and returns the API instance that comes with // reactive state and handlers to be assigned as Highcharts options, used by Cloudscape components // (tooltip, legend, and other), or exposed as public core chart API. @@ -95,6 +105,12 @@ export class ChartAPI { private chartExtraNodata = new ChartExtraNodata(this.context); private chartExtraAxisTitles = new ChartExtraAxisTitles(this.context); private chartExtraZoom = new ChartExtraZoom(this.context, this.zoomHandlers); + private legendItemHighlight = new DebouncedCall(); + private apiHighlight = new DebouncedCall((a, b) => + typeof a === "string" || typeof b === "string" ? a === b : isSameHoverTarget(a, b), + ); + private appliedHighlight: null | HighlightTarget = null; + private notifiedHighlight: null | HighlightTarget = null; constructor( settings: ChartExtraContext.Settings, @@ -157,6 +173,8 @@ export class ChartAPI { // There is no cleanup or destroy event in Highcharts options, so we define a custom one // to be used when the React component unmounts. public onChartDestroy = () => { + this.legendItemHighlight.cancelPending(); + this.apiHighlight.cancelPending(); this.chartExtraNavigation.onChartDestroy(); this.chartExtraPointer.onChartDestroy(); this.chartExtraTooltip.onChartDestroy(); @@ -232,36 +250,52 @@ export class ChartAPI { public updateItemsVisibility = this.chartExtraLegend.updateItemsVisibility.bind(this.chartExtraLegend); // A callback used by the legend and filter components when series/segments visibility changes. - public onItemVisibilityChange = (items: readonly string[], detail: CoreChartProps.InteractionKind) => - this.chartExtraLegend.onItemVisibilityChange(items, detail); + public onItemVisibilityChange = (items: readonly string[], detail: CoreChartProps.InteractionKind) => { + this.changeItemsVisibility(items, detail); + }; // Callbacks used by the legend component when items highlight state changes. - public onHighlightChartItems = (itemIds: readonly string[]) => { - if (!this.isTooltipPinned) { - this.chartExtraHighlight.highlightChartItems(itemIds); - this.chartExtraLegend.onHighlightItems(itemIds); + public onHighlightChartItems = (itemIds: readonly string[]) => this.highlightChartItems(itemIds); + public onEnterLegendItem = (itemId: string, highlight: () => void) => { + this.scheduleHighlight( + "legend", + this.legendItemHighlight, + itemId, + () => { + if (this.chartExtraLegend.get().items.some((item) => item.id === itemId && item.visible)) { + highlight(); + } + }, + () => this.previewItems([itemId]), + ); + }; + public onLeaveLegendItem = () => { + if (this.legendItemHighlight.cancelPending()) { + this.restorePreview({ notify: false }); } }; public onClearChartItemsHighlight = () => { + this.cancelPendingHovers({ notify: false }); if (!this.isTooltipPinned) { this.chartExtraHighlight.clearChartItemsHighlight(); this.chartExtraLegend.onClearHighlight(); + this.notifiedHighlight = null; // Notify the consumer that a clear-highlight action was made. fireNonCancelableEvent(this.context.handlers.onClearHighlight, { isApiCall: false }); } }; - // Callbacks used for hover and keyboard navigation, and also exposed to the public API to give the ability - // to highlight and show tooltip for the given point or group manually. + // Callbacks used for hover and keyboard navigation. public highlightChartItems = (itemIds: readonly string[]) => { + this.cancelPendingHovers({ notify: false }); if (!this.isTooltipPinned) { this.chartExtraHighlight.highlightChartItems(itemIds); this.chartExtraLegend.onHighlightItems(itemIds); } }; public setItemsVisible = (visibleItemsIds: readonly string[]) => { - this.chartExtraLegend.onItemVisibilityChange(visibleItemsIds, { interactionType: "api" }); + this.changeItemsVisibility(visibleItemsIds, { interactionType: "api" }); }; public highlightChartPoint = (point: Highcharts.Point, { isApiCall }: { isApiCall: boolean }) => { if (!this.isTooltipPinned) { @@ -273,17 +307,17 @@ export class ChartAPI { this.highlightActions(group as Writeable, { isApiCall }); } }; - public clearChartHighlight = ({ isApiCall }: { isApiCall: boolean }) => { + public clearChartHighlight = ({ isApiCall, keepLegendHover }: { isApiCall: boolean; keepLegendHover?: boolean }) => { if (!this.isTooltipPinned) { - this.clearHighlightActions({ isApiCall }); + this.clearHighlightActions({ isApiCall, keepLegendHover }); } }; public get publicApi() { return { - highlightItems: (itemIds: readonly string[]) => this.highlightChartItems(itemIds), + highlightItems: (itemIds: readonly string[]) => this.highlightItemsFromApi(itemIds), setItemsVisible: (visibleItemIds: readonly string[]) => this.setItemsVisible(visibleItemIds), - highlightChartPoint: (point: Highcharts.Point) => this.highlightChartPoint(point, { isApiCall: true }), - highlightChartGroup: (group: readonly Highcharts.Point[]) => this.highlightChartGroup(group, { isApiCall: true }), + highlightChartPoint: (point: Highcharts.Point) => this.highlightTargetFromApi(point), + highlightChartGroup: (group: readonly Highcharts.Point[]) => this.highlightTargetFromApi([...group]), clearChartHighlight: () => this.clearChartHighlight({ isApiCall: true }), }; } @@ -299,6 +333,7 @@ export class ChartAPI { // Dismiss any visible non-pinned tooltip when ESC is pressed. // Returns true if a tooltip was dismissed, false otherwise. // Used by ESC handlers at group/point level to decide whether to also navigate. + this.cancelPendingHovers(); const tooltipState = this.chartExtraTooltip.get(); if (tooltipState.visible && !tooltipState.pinned) { this.clearChartHighlight({ isApiCall: false }); @@ -350,7 +385,16 @@ export class ChartAPI { this.highlightChartGroup(group, { isApiCall: false }); }, onHoverLost: () => { - this.clearChartHighlight({ isApiCall: false }); + this.clearChartHighlight({ isApiCall: false, keepLegendHover: true }); + }, + onHoverPreview: (target) => { + this.cancelPendingHovers({ pointer: false, notify: false }); + if (!this.isTooltipPinned) { + this.showPreview(target); + } + }, + onHoverPreviewCancel: () => { + this.restorePreview({ notify: true }); }, onPointClick: (point) => { this.pinTooltipOnPoint(point); @@ -452,8 +496,8 @@ export class ChartAPI { target: Highcharts.Point | Highcharts.Point[], { isApiCall, overrideTooltipLock }: { isApiCall: boolean; overrideTooltipLock?: boolean }, ) { - const point = Array.isArray(target) ? null : target; - const group = Array.isArray(target) ? target : this.context.derived.getPointsByX(target.x); + this.cancelPendingHovers({ notify: false }); + const { point, group } = this.getHighlightTarget(target); if (!this.isTooltipPinned) { // Update Highcharts elements state. @@ -473,11 +517,134 @@ export class ChartAPI { } // Notify the consumer that a highlight action was made. - fireNonCancelableEvent(this.context.handlers.onHighlight, { point, group, isApiCall }); + this.appliedHighlight = { point, group }; + this.notifyHighlight(point, group, isApiCall); + } + } + + public cancelPendingHovers = ({ pointer = true, legend = true, api = true, notify = true } = {}) => { + const hadPointerHover = pointer && this.chartExtraPointer.cancelPendingHover(); + const hadLegendHighlight = legend && this.legendItemHighlight.cancelPending(); + const hadApiHighlight = api && this.apiHighlight.cancelPending(); + if (hadPointerHover || hadLegendHighlight || hadApiHighlight) { + this.restorePreview({ notify, legendPreviewed: hadLegendHighlight }); + } + }; + + public getLegendScrollDelay = () => { + const delay = this.context.settings.hoverDelay; + return delay > 0 ? Math.max(0, this.chartExtraPointer.getLastPointerMoveAt() + delay - Date.now()) : 0; + }; + + public get hoverDebounceEnabled() { + return this.context.settings.hoverDebounceEnabled; + } + + private notifyHighlight(point: null | Highcharts.Point, group: readonly Highcharts.Point[], isApiCall: boolean) { + const notified = this.notifiedHighlight; + if ( + this.hoverDebounceEnabled && + !isApiCall && + notified && + notified.point === point && + isEqualArrays(notified.group, group, (a, b) => a === b) + ) { + return; } + this.notifiedHighlight = { point, group }; + fireNonCancelableEvent(this.context.handlers.onHighlight, { point, group, isApiCall }); + } + + private showPreview(target: PointerHoverTarget, { notify = true } = {}) { + const { point, group } = this.getHighlightTarget(target); + this.chartExtraTooltip.showCursor(point, group); + if (!this.hoverDebounceEnabled) { + return; + } + if (point) { + this.chartExtraLegend.onPreviewPoint(point, this.chartExtraHighlight.previewChartPoint(point)); + } else { + this.chartExtraLegend.onPreviewGroup(group, this.chartExtraHighlight.previewChartGroup(group)); + } + if (notify) { + this.notifyHighlight(point, group, false); + } + } + + private get isApiHighlightDelayed() { + return this.hoverDebounceEnabled && this.context.settings.hoverDelay > 0 && !this.isTooltipPinned; + } + + private highlightItemsFromApi(itemIds: readonly string[]) { + const apply = () => this.highlightChartItems(itemIds); + if (this.isApiHighlightDelayed) { + this.scheduleHighlight("api", this.apiHighlight, itemIds.join("\u0000"), apply, () => this.previewItems(itemIds)); + } else { + apply(); + } + } + + private highlightTargetFromApi(target: PointerHoverTarget) { + const apply = () => this.highlightActions(target, { isApiCall: true }); + if (this.isApiHighlightDelayed) { + this.scheduleHighlight("api", this.apiHighlight, target, apply, () => + this.showPreview(target, { notify: false }), + ); + } else { + apply(); + } + } + + private scheduleHighlight( + source: "legend" | "api", + call: DebouncedCall, + key: Key, + apply: () => void, + preview: () => void, + ) { + this.cancelPendingHovers({ [source]: false, notify: false }); + if (call.call(apply, this.context.settings.hoverDelay, key) && !this.isTooltipPinned) { + preview(); + } + } + + private previewItems(itemIds: readonly string[]) { + this.chartExtraLegend.onPreviewItems(itemIds, this.chartExtraHighlight.previewChartItems(itemIds)); + } + + private changeItemsVisibility(itemIds: readonly string[], detail: CoreChartProps.InteractionKind) { + this.cancelPendingHovers(); + this.chartExtraLegend.onItemVisibilityChange(itemIds, detail); + } + + private restorePreview({ notify, legendPreviewed = false }: { notify: boolean; legendPreviewed?: boolean }) { + this.chartExtraTooltip.restoreCursor(); + this.chartExtraHighlight.cancelPreview(); + this.chartExtraLegend.onCancelPreview(); + if (notify && !this.isTooltipPinned && this.hoverDebounceEnabled) { + if (this.appliedHighlight) { + this.notifyHighlight(this.appliedHighlight.point, this.appliedHighlight.group, false); + } else if (this.notifiedHighlight || legendPreviewed) { + this.notifiedHighlight = null; + fireNonCancelableEvent(this.context.handlers.onClearHighlight, { isApiCall: false }); + } + } + } + + private getHighlightTarget(target: PointerHoverTarget) { + const point = Array.isArray(target) ? null : target; + const group = Array.isArray(target) ? target : this.context.derived.getPointsByX(target.x); + return { point, group }; } - private clearHighlightActions = ({ isApiCall }: { isApiCall: boolean }) => { + private clearHighlightActions = ({ + isApiCall, + keepLegendHover, + }: { + isApiCall: boolean; + keepLegendHover?: boolean; + }) => { + this.cancelPendingHovers({ legend: !keepLegendHover, notify: false }); if (!this.isTooltipPinned) { // Update Highcharts elements state. this.chartExtraHighlight.clearChartItemsHighlight(); @@ -485,6 +652,8 @@ export class ChartAPI { // Update tooltip and legend state. this.chartExtraTooltip.hideTooltip(); this.chartExtraLegend.onClearHighlight(); + this.appliedHighlight = null; + this.notifiedHighlight = null; // Notify the consumer that a clear-highlight action was made. fireNonCancelableEvent(this.context.handlers.onClearHighlight, { isApiCall }); diff --git a/src/core/chart-core.tsx b/src/core/chart-core.tsx index 66f919ec..51dff0f1 100644 --- a/src/core/chart-core.tsx +++ b/src/core/chart-core.tsx @@ -35,12 +35,14 @@ import { ChartZoomLiveRegion } from "./components/core-zoom-live-region"; import { getFormatter } from "./formatters"; import { useChartI18n } from "./i18n-utils"; import { CoreChartProps } from "./interfaces"; -import { InternalZoomProps } from "./internal-interfaces"; +import { InternalHoverProps, InternalZoomProps } from "./internal-interfaces"; import { getLegendsProps, getPointAccessibleDescription } from "./utils"; import styles from "./styles.css.js"; import testClasses from "./test-classes/styles.css.js"; +const DEFAULT_HOVER_DEBOUNCE = 150; + /** * CoreChart is the core internal abstraction that accepts the entire set of Highcharts options along * with Cloudscape props to define custom tooltip, no-data, formatters, items visibility, and more. @@ -59,6 +61,7 @@ export function InternalCoreChart({ zoom: zoomOptions, zoomRange, onZoomRangeChange, + hoverDebounce, legend: legendOptions, fallback = , callback, @@ -78,11 +81,18 @@ export function InternalCoreChart({ __internalRootRef, getItemOptions, ...rest -}: CoreChartProps & InternalBaseComponentProps & InternalZoomProps) { +}: CoreChartProps & InternalBaseComponentProps & InternalZoomProps & InternalHoverProps) { const highcharts = rest.highcharts as null | typeof Highcharts; const labels = useChartI18n({ ariaLabel, ariaDescription, i18nStrings }); // The zoom applies to the first x-axis, and is ignored when the chart does not define one. const zoomEnabled = !!zoomOptions?.enabled && (castArray(options.xAxis)?.length ?? 0) > 0; + const hoverDelay = + hoverDebounce === true + ? DEFAULT_HOVER_DEBOUNCE + : typeof hoverDebounce === "number" && hoverDebounce > 0 + ? hoverDebounce + : -1; + const hoverDebounceEnabled = hoverDebounce !== undefined && hoverDebounce !== false; const context: ChartExtraContext["settings"] = { chartId: useUniqueId(), noDataEnabled: !!noDataOptions, @@ -92,6 +102,8 @@ export function InternalCoreChart({ labels, getItemOptions: getItemOptions ?? (() => ({})), zoomEnabled, + hoverDelay, + hoverDebounceEnabled, }; const handlers = { onHighlight, onClearHighlight, onVisibleItemsChange, onZoomRangeChange }; const state = { visibleItems, zoomRange }; @@ -107,6 +119,8 @@ export function InternalCoreChart({ i18nStrings, onItemHighlight: onLegendItemHighlight, getLegendTooltipContent: rest.getLegendTooltipContent, + tooltipShowDelay: hoverDebounceEnabled ? Math.max(hoverDelay, 0) : undefined, + delayScrollIntoView: hoverDebounceEnabled, }; const containerProps = { fitHeight, @@ -130,10 +144,13 @@ export function InternalCoreChart({ return; } - if (event.keyCode === KeyCode.escape && context.tooltipEnabled) { - const tooltipState = api.tooltipStore.get(); - if (tooltipState.visible && !tooltipState.pinned) { - api.hideTooltip(); + if (event.keyCode === KeyCode.escape) { + api.cancelPendingHovers(); + if (context.tooltipEnabled) { + const tooltipState = api.tooltipStore.get(); + if (tooltipState.visible && !tooltipState.pinned) { + api.hideTooltip(); + } } } }; @@ -415,6 +432,9 @@ export function InternalCoreChart({ {context.tooltipEnabled && ( ; getLegendTooltipContent?: CoreChartProps.GetLegendTooltipContent; + tooltipShowDelay?: number; + delayScrollIntoView?: boolean; }) { const i18n = useInternalI18n("[charts]"); const legendAriaLabel = i18n("i18nStrings.legendAriaLabel", i18nStrings?.legendAriaLabel); @@ -44,7 +48,9 @@ export function ChartLegend({ const ariaLabel = isSecondary ? secondaryLegendAriaLabel : legendAriaLabel; const legendItems = useSelector(api.legendStore, (s) => s.items); - const someHighlighted = legendItems.some((item) => item.highlighted); + const previewItemIds = useSelector(api.legendStore, (s) => s.previewItemIds); + const previewDimmed = useSelector(api.legendStore, (s) => s.previewDimmed); + const someHighlighted = legendItems.some((item) => item.highlighted) || (previewItemIds.length > 0 && previewDimmed); const isChartTooltipPinned = useSelector(api.tooltipStore, (s) => s.pinned); const filteredItems = isSecondary ? legendItems.filter((item) => item.isSecondary) @@ -87,18 +93,35 @@ export function ChartLegend({ ariaLabel={ariaLabel} className={className} legendTitle={title} - items={filteredItems} + items={ + previewItemIds.length > 0 + ? filteredItems.map((item) => ({ ...item, highlighted: previewItemIds.includes(item.id) })) + : filteredItems + } someHighlighted={someHighlighted} horizontalAlignment={horizontalAlignment} enableHorizontalScroll={enableHorizontalScroll} + tooltipShowDelay={tooltipShowDelay} + getScrollIntoViewDelay={delayScrollIntoView ? api.getLegendScrollDelay : undefined} actions={actions} alignment={alignment} onToggleItem={onToggleItem} onSelectItem={onSelectItem} onItemHighlightExit={api.onClearChartItemsHighlight} - onItemHighlightEnter={(item) => { - api.onHighlightChartItems([item.id]); - fireNonCancelableEvent(onItemHighlight, { item }); + onItemHoverLeave={api.onLeaveLegendItem} + onItemHighlightEnter={(item, detail) => { + if (!detail.pointer) { + api.onHighlightChartItems([item.id]); + fireNonCancelableEvent(onItemHighlight, { item }); + } else if (api.hoverDebounceEnabled) { + fireNonCancelableEvent(onItemHighlight, { item }); + api.onEnterLegendItem(item.id, () => api.onHighlightChartItems([item.id])); + } else { + api.onEnterLegendItem(item.id, () => { + api.onHighlightChartItems([item.id]); + fireNonCancelableEvent(onItemHighlight, { item }); + }); + } }} getTooltipContent={(props) => { if (isChartTooltipPinned) { diff --git a/src/core/interfaces.ts b/src/core/interfaces.ts index 9c910817..bf242282 100644 --- a/src/core/interfaces.ts +++ b/src/core/interfaces.ts @@ -549,6 +549,7 @@ export namespace CoreChartProps { enabled?: boolean; placement?: "middle" | "outside" | "target"; size?: "small" | "medium" | "large"; + // Superseded by the internal hoverDebounce prop (see InternalHoverProps) and planned for removal. debounce?: number | boolean; seriesSorting?: "as-added" | "by-value-desc"; } diff --git a/src/core/internal-interfaces.ts b/src/core/internal-interfaces.ts index 254b4b0d..5d59d4e7 100644 --- a/src/core/internal-interfaces.ts +++ b/src/core/internal-interfaces.ts @@ -25,3 +25,11 @@ export interface InternalZoomProps { zoomRange?: ZoomRange | null; onZoomRangeChange?: NonCancelableEventHandler; } + +// Highlights the hovered series and legend item immediately, and delays dimming the other series and legend items, +// the tooltip, and legend scroll-into-view until the pointer settles on a target. It supersedes tooltip.debounce, +// which only delays the tooltip: tooltip.debounce is ignored while hoverDebounce is set, and is planned for removal +// once consumers have moved to hoverDebounce. +export interface InternalHoverProps { + hoverDebounce?: number | boolean; +} diff --git a/src/internal/components/chart-legend/index.tsx b/src/internal/components/chart-legend/index.tsx index b2107a03..ccd05376 100644 --- a/src/internal/components/chart-legend/index.tsx +++ b/src/internal/components/chart-legend/index.tsx @@ -44,9 +44,12 @@ export interface ChartLegendProps { horizontalAlignment: LegendHorizontalAlignment; onToggleItem: (itemId: string) => void; onSelectItem: (itemId: string) => void; - onItemHighlightEnter: (item: LegendItem) => void; + onItemHighlightEnter: (item: LegendItem, detail: { pointer: boolean }) => void; onItemHighlightExit: () => void; + onItemHoverLeave?: () => void; getTooltipContent: (props: GetLegendTooltipContentProps) => null | LegendTooltipContent; + tooltipShowDelay?: number; + getScrollIntoViewDelay?: () => number; } export const ChartLegend = ({ @@ -62,9 +65,12 @@ export const ChartLegend = ({ onSelectItem, onItemHighlightEnter, onItemHighlightExit, + onItemHoverLeave, getTooltipContent, horizontalAlignment, enableHorizontalScroll, + tooltipShowDelay = TOOLTIP_SHOW_DELAY, + getScrollIntoViewDelay, }: ChartLegendProps) => { const containerRef = useRef(null); const elementsByIndexRef = useRef>([]); @@ -74,11 +80,13 @@ export const ChartLegend = ({ const scrollIntoViewControl = useMemo(() => new DebouncedCall(), []); const [selectedIndex, setSelectedIndex] = useState(0); const [tooltipItemId, setTooltipItemId] = useState(null); - const { showTooltip, hideTooltip } = useMemo(() => { + const tooltipShowDelayRef = useRef(tooltipShowDelay); + tooltipShowDelayRef.current = tooltipShowDelay; + const { showTooltip, hideTooltip, cancelTooltip } = useMemo(() => { const control = new DebouncedCall(); return { showTooltip(itemId: string) { - control.call(() => setTooltipItemId(itemId), TOOLTIP_SHOW_DELAY); + control.call(() => setTooltipItemId(itemId), tooltipShowDelayRef.current); }, hideTooltip(lock = false) { control.call(() => setTooltipItemId(null), TOOLTIP_BLUR_DELAY); @@ -86,34 +94,47 @@ export const ChartLegend = ({ control.lock(TOOLTIP_BLUR_DELAY); } }, + cancelTooltip() { + control.cancelPending(); + }, }; }, []); + useEffect(() => cancelTooltip, [cancelTooltip]); useEffect(() => { - if (!tooltipItemId) { - return; - } const onDocumentKeyDown = (event: KeyboardEvent) => { - if (event.keyCode === KeyCode.escape) { + if (event.keyCode !== KeyCode.escape) { + return; + } + if (tooltipItemId) { hideTooltip(true); elementsByIdRef.current[tooltipItemId]?.focus(); + } else { + cancelTooltip(); } }; document.addEventListener("keydown", onDocumentKeyDown, true); return () => { document.removeEventListener("keydown", onDocumentKeyDown, true); }; - }, [tooltipItemId, hideTooltip]); + }, [tooltipItemId, hideTooltip, cancelTooltip]); const isMouseInContainer = useRef(false); // Scrolling to the highlighted legend item. + const getScrollIntoViewDelayRef = useRef(getScrollIntoViewDelay); + getScrollIntoViewDelayRef.current = getScrollIntoViewDelay; useEffect(() => { const highlightedIndex = items.findIndex((item) => item.highlighted); if (highlightedIndex === -1) { return; } - scrollIntoViewControl.call(() => { + const scroll = () => { + const delay = getScrollIntoViewDelayRef.current?.() ?? 0; + if (delay > 0) { + scrollIntoViewControl.call(scroll, delay); + return; + } if (isMouseInContainer.current) { return; } @@ -122,14 +143,15 @@ export const ChartLegend = ({ return; } scrollIntoViewNearestContainer(element, { behavior: "smooth", scrollMode: "if-needed" }); - }, SCROLL_DELAY); + }; + scrollIntoViewControl.call(scroll, getScrollIntoViewDelayRef.current?.() ?? SCROLL_DELAY); }, [items, scrollIntoViewControl]); - const showHighlight = (itemId: string) => { + const showHighlight = (itemId: string, pointer = false) => { const item = items.find((item) => item.id === itemId); if (item?.visible) { - highlightControl.cancelPrevious(); - onItemHighlightEnter(item); + highlightControl.cancelPending(); + onItemHighlightEnter(item, { pointer }); } }; const clearHighlight = () => { @@ -265,10 +287,11 @@ export const ChartLegend = ({ {items.map((item, index) => { const handlers = { onMouseEnter: () => { - showHighlight(item.id); + showHighlight(item.id, true); showTooltip(item.id); }, onMouseLeave: () => { + onItemHoverLeave?.(); clearHighlight(); hideTooltip(); }, diff --git a/src/internal/utils/__tests__/utils.test.ts b/src/internal/utils/__tests__/utils.test.ts index a40444f0..7133b029 100644 --- a/src/internal/utils/__tests__/utils.test.ts +++ b/src/internal/utils/__tests__/utils.test.ts @@ -1,7 +1,9 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { escapeHtml } from "../../../../lib/components/internal/utils/utils"; +import { vi } from "vitest"; + +import { DebouncedCall, escapeHtml } from "../../../../lib/components/internal/utils/utils"; describe("escapeHtml", () => { test.each([ @@ -19,3 +21,83 @@ describe("escapeHtml", () => { expect(escapeHtml(input)).toBe(expected); }); }); + +describe("DebouncedCall", () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + test("keeps a pending call for the same key instead of restarting the delay", () => { + const debounced = new DebouncedCall(); + const first = vi.fn(); + const second = vi.fn(); + + expect(debounced.call(first, 100, "a")).toBe(true); + vi.advanceTimersByTime(60); + expect(debounced.call(second, 100, "a")).toBe(false); + vi.advanceTimersByTime(40); + + expect(first).toHaveBeenCalledTimes(1); + expect(second).not.toHaveBeenCalled(); + }); + + test("replaces a pending call for a different key", () => { + const debounced = new DebouncedCall(); + const first = vi.fn(); + const second = vi.fn(); + + debounced.call(first, 100, "a"); + vi.advanceTimersByTime(60); + debounced.call(second, 100, "b"); + vi.advanceTimersByTime(60); + + expect(first).not.toHaveBeenCalled(); + expect(second).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(40); + + expect(second).toHaveBeenCalledTimes(1); + }); + + test("compares keys with the given function", () => { + const debounced = new DebouncedCall<{ id: string }>((a, b) => a.id === b.id); + const first = vi.fn(); + + debounced.call(first, 100, { id: "a" }); + expect(debounced.call(vi.fn(), 100, { id: "a" })).toBe(false); + vi.advanceTimersByTime(100); + + expect(first).toHaveBeenCalledTimes(1); + }); + + test("runs the pending call at once on flush", () => { + const debounced = new DebouncedCall(); + const callback = vi.fn(); + + debounced.call(callback, 100); + debounced.flush(); + vi.advanceTimersByTime(100); + + expect(callback).toHaveBeenCalledTimes(1); + }); + + test("reports whether a call was pending when cancelled", () => { + const debounced = new DebouncedCall(); + const callback = vi.fn(); + + debounced.call(callback, 100); + + expect(debounced.cancelPending()).toBe(true); + expect(debounced.cancelPending()).toBe(false); + vi.advanceTimersByTime(100); + expect(callback).not.toHaveBeenCalled(); + }); + + test("calls at once without a delay", () => { + const debounced = new DebouncedCall(); + const callback = vi.fn(); + + expect(debounced.call(callback, -1, "a")).toBe(false); + expect(callback).toHaveBeenCalledTimes(1); + expect(debounced.cancelPending()).toBe(false); + }); +}); diff --git a/src/internal/utils/highcharts.ts b/src/internal/utils/highcharts.ts index 661fa3fd..28e4062c 100644 --- a/src/internal/utils/highcharts.ts +++ b/src/internal/utils/highcharts.ts @@ -39,8 +39,11 @@ export function getChartSeries(chart: SafeChart): SafeSeries[] { * Returns point series or series it is linked to. */ export function getMasterSeries(point: Point): SafeSeries { - const masterSeries = point.series.linkedParent ?? point.series; - return masterSeries; + return getMasterSeriesOf(point.series); +} + +export function getMasterSeriesOf(series: SafeSeries): SafeSeries { + return series.linkedParent ?? series; } /** diff --git a/src/internal/utils/use-debounced-value.tsx b/src/internal/utils/use-debounced-value.tsx index a3722093..6039d3a4 100644 --- a/src/internal/utils/use-debounced-value.tsx +++ b/src/internal/utils/use-debounced-value.tsx @@ -22,7 +22,9 @@ export function useDebouncedValue(value: T, duration: number) { setShouldRender(true); }, duration); - return () => current.cancelPrevious(); + return () => { + current.cancelPending(); + }; }, [value, duration]); if (duration <= 0) { diff --git a/src/internal/utils/utils.ts b/src/internal/utils/utils.ts index 083cf8e7..009a2eb5 100644 --- a/src/internal/utils/utils.ts +++ b/src/internal/utils/utils.ts @@ -39,24 +39,42 @@ export function escapeHtml(value: string): string { return value.replace(/[&<>"']/g, (char) => htmlEscapes[char]); } -export class DebouncedCall { +export class DebouncedCall { private locked = false; private lockTimeoutRef = setTimeout(() => {}, 0); private timeoutRef = setTimeout(() => {}, 0); + private pending: null | { callback: () => void; key?: Key } = null; - public call(callback: () => void, delay = -1) { - if (!this.locked) { - this.cancelPrevious(); - if (delay === -1) { - callback(); - } else { - this.timeoutRef = setTimeout(callback, delay); - } + constructor(private isSameKey: (a: Key, b: Key) => boolean = (a, b) => a === b) {} + + public call(callback: () => void, delay = -1, key?: Key): boolean { + if (this.locked) { + return false; + } + if (key !== undefined && this.pending?.key !== undefined && this.isSameKey(this.pending.key, key)) { + return false; } + this.cancelPending(); + if (delay === -1) { + callback(); + return false; + } + this.pending = { callback, key }; + this.timeoutRef = setTimeout(this.flush, delay); + return true; } - public cancelPrevious() { + public flush = () => { + const pending = this.pending; + this.cancelPending(); + pending?.callback(); + }; + + public cancelPending(): boolean { + const hadPending = this.pending !== null; clearTimeout(this.timeoutRef); + this.pending = null; + return hadPending; } public lock(timeout: number) { diff --git a/test/functional/hover-debounce.test.ts b/test/functional/hover-debounce.test.ts new file mode 100644 index 00000000..b28bd2d1 --- /dev/null +++ b/test/functional/hover-debounce.test.ts @@ -0,0 +1,85 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { expect, test } from "vitest"; + +import "@cloudscape-design/components/test-utils/selectors"; +import "../../lib/components/test-utils/selectors"; +import createWrapper from "../../lib/components/test-utils/selectors"; +import CoreChartWrapper from "../../lib/components/test-utils/selectors/internal/core"; +import { setupTest } from "../utils"; + +import coreTestClasses from "../../lib/components/core/test-classes/styles.selectors.js"; +import legendTestClasses from "../../lib/components/internal/components/chart-legend/test-classes/styles.selectors.js"; + +const chart = createWrapper().findComponent(`.${coreTestClasses.root}`, CoreChartWrapper); +const tooltip = chart.findTooltip().toSelector(); +const tooltipHeader = chart.findTooltip().findHeader().toSelector(); +const dimmedLegendItems = `${chart.findLegend().toSelector()} .${legendTestClasses["dimmed-item"]}`; +const inactiveSeries = `${chart.toSelector()} .highcharts-series-inactive`; +const cursorMarkers = `${chart.toSelector()} .${coreTestClasses["highlight-marker"]}`; +const point = (series: number, index: number) => + `${chart.toSelector()} g.highcharts-markers.highcharts-series-${series} path.highcharts-point:nth-child(${index})`; +const legendItem = (index: number) => chart.findLegend().findItems().get(index).toSelector(); + +const pageUrl = (hoverDebounce: number) => `#/03-core/core-line-chart?hoverDebounce=${hoverDebounce}`; + +type ChartPage = Parameters[1]>[0]; + +async function center(page: ChartPage, selector: string) { + const box = await page.getBoundingBox(selector); + return [box.left + box.width / 2, box.top + box.height / 2] as const; +} + +test( + "shows the cursor at once and the tooltip once the delay passes", + setupTest(pageUrl(1000), async (page) => { + const [x, y] = await center(page, point(0, 10)); + await page.moveCursorTo(x, y); + + await expect(page.getElementsCount(cursorMarkers)).resolves.toBeGreaterThan(0); + await expect(page.isExisting(tooltip)).resolves.toBe(false); + + await page.waitForAssertion(() => expect(page.isExisting(tooltip)).resolves.toBe(true)); + }), +); + +test( + "keeps the current tooltip while the pointer moves to another point until it rests", + setupTest(pageUrl(1000), async (page) => { + const [ax, ay] = await center(page, point(0, 10)); + await page.moveCursorTo(ax, ay); + await page.waitForAssertion(() => expect(page.isExisting(tooltip)).resolves.toBe(true)); + const [firstHeader] = await page.getElementsText(tooltipHeader); + + const [bx, by] = await center(page, point(1, 25)); + await page.moveCursorTo(bx, by); + await expect(page.getElementsText(tooltipHeader)).resolves.toEqual([firstHeader]); + + await page.waitForAssertion(() => expect(page.getElementsText(tooltipHeader)).resolves.not.toEqual([firstHeader])); + }), +); + +test( + "delays dimming the other series when hovering a legend item", + setupTest(pageUrl(1000), async (page) => { + const [x, y] = await center(page, legendItem(1)); + await page.moveCursorTo(x, y); + + await expect(page.getElementsCount(dimmedLegendItems)).resolves.toBe(0); + await expect(page.getElementsCount(inactiveSeries)).resolves.toBe(0); + + await page.waitForAssertion(() => expect(page.getElementsCount(dimmedLegendItems)).resolves.toBeGreaterThan(0)); + await expect(page.getElementsCount(inactiveSeries)).resolves.toBeGreaterThan(0); + }), +); + +test( + "shows the tooltip immediately when the delay is 0", + setupTest(pageUrl(0), async (page) => { + const [x, y] = await center(page, point(0, 10)); + await page.moveCursorTo(x, y); + + await expect(page.isExisting(tooltip)).resolves.toBe(true); + }), +);