From 8b6c8efe52daaa4c9c1cf2726149842f23221b6a Mon Sep 17 00:00:00 2001 From: Shivam Rungta Date: Wed, 18 Nov 2026 13:34:32 +0100 Subject: [PATCH 1/3] feat: Add zoom to cartesian chart Make zoom public on CartesianChart and the core chart: the zoom, zoomRange and onZoomRangeChange properties, the enterZoomMode, exitZoomMode and resetZoom ref methods, the zoom labels in i18nStrings, and zoom finders in the test utils. --- pages/03-core/simple-zooming.page.tsx | 5 +- pages/common/page-settings.tsx | 5 +- .../__snapshots__/documenter.test.ts.snap | 373 ++++++++++++++++++ .../__tests__/cartesian-chart-zoom.test.tsx | 54 ++- .../chart-cartesian-internal.tsx | 3 + src/cartesian-chart/interfaces.ts | 52 +++ .../__tests__/chart-core-rendering.test.tsx | 3 + src/core/__tests__/chart-core-zoom.test.tsx | 3 +- src/core/__tests__/common.tsx | 30 +- src/core/chart-api/chart-extra-context.tsx | 5 +- src/core/chart-api/chart-extra-zoom.ts | 5 +- src/core/chart-api/index.tsx | 3 + src/core/chart-core.tsx | 3 +- src/core/components/core-zoom-controls.tsx | 2 +- src/core/i18n-utils.tsx | 50 ++- src/core/interfaces.ts | 73 ++++ src/core/internal-interfaces.ts | 27 -- src/test-utils/dom/cartesian-chart/index.ts | 30 ++ src/test-utils/dom/internal/core.ts | 29 ++ test/functional/cartesian-chart.test.ts | 4 +- 20 files changed, 666 insertions(+), 93 deletions(-) delete mode 100644 src/core/internal-interfaces.ts diff --git a/pages/03-core/simple-zooming.page.tsx b/pages/03-core/simple-zooming.page.tsx index ec75ccc8..e069deed 100644 --- a/pages/03-core/simple-zooming.page.tsx +++ b/pages/03-core/simple-zooming.page.tsx @@ -12,7 +12,6 @@ import SpaceBetween from "@cloudscape-design/components/space-between"; import { colorChartsBlue1400, colorChartsLineTick } from "@cloudscape-design/design-tokens"; import { CoreChartProps } from "../../lib/components/core/interfaces"; -import { InternalZoomProps } from "../../lib/components/core/internal-interfaces"; import CoreChart from "../../lib/components/internal-do-not-use/core-chart"; import { dateFormatter } from "../common/formatters"; import { PageSettings, PageSettingsForm, useChartSettings } from "../common/page-settings"; @@ -23,8 +22,6 @@ interface ThisPageSettings extends PageSettings { keepZoomingFrame: boolean; } -const ZoomCoreChart = CoreChart as React.ComponentType; - function randomInt(min: number, max: number) { return min + Math.floor(pseudoRandom() * (max - min)); } @@ -247,7 +244,7 @@ function Charts() { }} /> - { scatterChartRef.current = chart; }} diff --git a/pages/common/page-settings.tsx b/pages/common/page-settings.tsx index 850e296b..7708b5dc 100644 --- a/pages/common/page-settings.tsx +++ b/pages/common/page-settings.tsx @@ -16,7 +16,6 @@ import Select from "@cloudscape-design/components/select"; import SpaceBetween from "@cloudscape-design/components/space-between"; import { CartesianChartProps, PieChartProps } from "../../lib/components"; -import { InternalZoomProps } from "../../lib/components/core/internal-interfaces"; import { CoreChartProps } from "../../src/core/interfaces"; import { useHighcharts } from "./use-highcharts"; @@ -90,9 +89,9 @@ export function useChartSettings) => void; chartProps: { - cartesian: Omit & InternalZoomProps & { ref: React.Ref }; + cartesian: Omit & { ref: React.Ref }; pie: Omit & { ref: React.Ref }; - core: Omit & InternalZoomProps; + core: Omit; }; isEmpty: boolean; } { diff --git a/src/__tests__/__snapshots__/documenter.test.ts.snap b/src/__tests__/__snapshots__/documenter.test.ts.snap index c4af9741..fb793164 100644 --- a/src/__tests__/__snapshots__/documenter.test.ts.snap +++ b/src/__tests__/__snapshots__/documenter.test.ts.snap @@ -21,8 +21,73 @@ exports[`definition for cartesian-chart matches the snapshot > cartesian-chart 1 "detailType": "{ visibleSeries: Array; }", "name": "onVisibleSeriesChange", }, + { + "cancelable": false, + "description": "Called when the user changes the zoomed range. The detail's \`zoomRange\` is \`null\` when the zoom is reset to the +full data range.", + "detailInlineType": { + "name": "BaseZoomChangeDetail", + "properties": [ + { + "inlineType": { + "name": "BaseZoomRange", + "properties": [ + { + "inlineType": { + "name": "{ startValue: number; endValue: number; }", + "properties": [ + { + "name": "endValue", + "optional": false, + "type": "number", + }, + { + "name": "startValue", + "optional": false, + "type": "number", + }, + ], + "type": "object", + }, + "name": "x", + "optional": true, + "type": "{ startValue: number; endValue: number; }", + }, + ], + "type": "object", + }, + "name": "zoomRange", + "optional": false, + "type": "BaseZoomRange | null", + }, + ], + "type": "object", + }, + "detailType": "BaseZoomChangeDetail", + "name": "onZoomRangeChange", + }, ], "functions": [ + { + "description": "Enters zoom mode, in which the user selects the start and end of the range to zoom into. +Requires zoom to be enabled with the \`zoom\` property.", + "name": "enterZoomMode", + "parameters": [], + "returnType": "void", + }, + { + "description": "Exits zoom mode without zooming. A range the chart is already zoomed into is kept.", + "name": "exitZoomMode", + "parameters": [], + "returnType": "void", + }, + { + "description": "Resets the zoom to show the full data range. When the range is controlled with \`zoomRange\`, +it calls \`onZoomRangeChange\` with a \`null\` range.", + "name": "resetZoom", + "parameters": [], + "returnType": "void", + }, { "description": "Controls series visibility and works with both controlled and uncontrolled visibility modes.", "name": "setVisibleSeries", @@ -142,6 +207,11 @@ Supported Highcharts versions: 12.", "optional": true, "type": "string", }, + { + "name": "enterZoomModeButtonText", + "optional": true, + "type": "string", + }, { "name": "errorText", "optional": true, @@ -162,6 +232,16 @@ Supported Highcharts versions: 12.", "optional": true, "type": "string", }, + { + "name": "resetZoomButtonAriaLabel", + "optional": true, + "type": "string", + }, + { + "name": "resetZoomButtonText", + "optional": true, + "type": "string", + }, { "name": "seriesFilterLabel", "optional": true, @@ -187,6 +267,103 @@ Supported Highcharts versions: 12.", "optional": true, "type": "string", }, + { + "name": "zoomButtonDisabledReason", + "optional": true, + "type": "string", + }, + { + "name": "zoomControlsAriaLabel", + "optional": true, + "type": "string", + }, + { + "name": "zoomCursorAriaLabel", + "optional": true, + "type": "string", + }, + { + "inlineType": { + "name": "(value: string) => string", + "parameters": [ + { + "name": "value", + "type": "string", + }, + ], + "returnType": "string", + "type": "function", + }, + "name": "zoomModeEnteredAnnouncementText", + "optional": true, + "type": "((value: string) => string)", + }, + { + "name": "zoomModeExitedAnnouncementText", + "optional": true, + "type": "string", + }, + { + "inlineType": { + "name": "(startValue: string, endValue: string) => string", + "parameters": [ + { + "name": "startValue", + "type": "string", + }, + { + "name": "endValue", + "type": "string", + }, + ], + "returnType": "string", + "type": "function", + }, + "name": "zoomRangeChangeAnnouncementText", + "optional": true, + "type": "((startValue: string, endValue: string) => string)", + }, + { + "name": "zoomResetAnnouncementText", + "optional": true, + "type": "string", + }, + { + "inlineType": { + "name": "(startValue: string, endValue: string) => string", + "parameters": [ + { + "name": "startValue", + "type": "string", + }, + { + "name": "endValue", + "type": "string", + }, + ], + "returnType": "string", + "type": "function", + }, + "name": "zoomSelectionAnnouncementText", + "optional": true, + "type": "((startValue: string, endValue: string) => string)", + }, + { + "inlineType": { + "name": "(value: string) => string", + "parameters": [ + { + "name": "value", + "type": "string", + }, + ], + "returnType": "string", + "type": "function", + }, + "name": "zoomStartPointAnnouncementText", + "optional": true, + "type": "((value: string) => string)", + }, ], "type": "object", }, @@ -620,6 +797,74 @@ applies to the tooltip points values.", "optional": true, "type": "CartesianChartProps.YAxisOptions | [CartesianChartProps.YAxisWithId, CartesianChartProps.YAxisWithId]", }, + { + "description": "Zoom settings. When zoom is enabled, users can zoom into a range of the x-axis by dragging across the plot, +or by selecting the zoom button and choosing a start and end point with a click or the keyboard. +After zooming in, a reset button shows the full data range again. + +Supported options: +* \`enabled\` (optional, boolean) - Enables zoom. Defaults to \`false\`. +* \`hideZoomControls\` (optional, boolean) - Hides the built-in zoom and reset buttons. Use it only when you provide +your own controls that call the \`enterZoomMode\`, \`exitZoomMode\`, and \`resetZoom\` methods of the component's ref.", + "inlineType": { + "name": "BaseZoomOptions", + "properties": [ + { + "name": "enabled", + "optional": true, + "type": "boolean", + }, + { + "name": "hideZoomControls", + "optional": true, + "type": "boolean", + }, + ], + "type": "object", + }, + "name": "zoom", + "optional": true, + "type": "BaseZoomOptions", + }, + { + "description": "The zoomed range of the x-axis. By default, the range is managed by the component. When using this property, +manage state updates with \`onZoomRangeChange\`, and use \`null\` to show the full data range. Update the property as soon +as \`onZoomRangeChange\` is called, including when its \`zoomRange\` is \`null\` after a reset. + +Supported options: +* \`x\` (optional, object) - The zoomed x-axis range, as \`startValue\` and \`endValue\`. For datetime axes, the +values are timestamps in milliseconds.", + "inlineType": { + "name": "BaseZoomRange", + "properties": [ + { + "inlineType": { + "name": "{ startValue: number; endValue: number; }", + "properties": [ + { + "name": "endValue", + "optional": false, + "type": "number", + }, + { + "name": "startValue", + "optional": false, + "type": "number", + }, + ], + "type": "object", + }, + "name": "x", + "optional": true, + "type": "{ startValue: number; endValue: number; }", + }, + ], + "type": "object", + }, + "name": "zoomRange", + "optional": true, + "type": "BaseZoomRange | null", + }, ], "regions": [ { @@ -1232,6 +1477,53 @@ exports[`internal core API matches snapshot > internal-core-chart 1`] = ` "name": "onVisibleItemsChange", "systemTags": undefined, }, + { + "cancelable": false, + "deprecatedTag": undefined, + "description": "Called when the user changes the zoomed range. The detail's \`zoomRange\` is \`null\` when the zoom is reset to the +full data range.", + "detailInlineType": { + "name": "BaseZoomChangeDetail", + "properties": [ + { + "inlineType": { + "name": "BaseZoomRange", + "properties": [ + { + "inlineType": { + "name": "{ startValue: number; endValue: number; }", + "properties": [ + { + "name": "endValue", + "optional": false, + "type": "number", + }, + { + "name": "startValue", + "optional": false, + "type": "number", + }, + ], + "type": "object", + }, + "name": "x", + "optional": true, + "type": "{ startValue: number; endValue: number; }", + }, + ], + "type": "object", + }, + "name": "zoomRange", + "optional": false, + "type": "BaseZoomRange | null", + }, + ], + "type": "object", + }, + "detailType": "BaseZoomChangeDetail", + "name": "onZoomRangeChange", + "systemTags": undefined, + }, ], "functions": [], "name": "CoreChart", @@ -1889,6 +2181,87 @@ When set to "side", displays the title along the axis line.", "type": "ReadonlyArray", "visualRefreshTag": undefined, }, + { + "analyticsTag": undefined, + "defaultValue": undefined, + "deprecatedTag": undefined, + "description": "Zoom settings. When zoom is enabled, users can zoom into a range of the x-axis by dragging across the plot, +or by selecting the zoom button and choosing a start and end point with a click or the keyboard. + +Supported options: +* \`enabled\` (optional, boolean) - Enables zoom. Defaults to \`false\`. +* \`hideZoomControls\` (optional, boolean) - Hides the built-in zoom and reset buttons. Use it only when you provide +your own controls that call the \`enterZoomMode\`, \`exitZoomMode\`, and \`resetZoom\` methods. + +Zoom applies to the first x-axis, and requires \`options.xAxis\` to be defined.", + "i18nTag": undefined, + "inlineType": { + "name": "BaseZoomOptions", + "properties": [ + { + "name": "enabled", + "optional": true, + "type": "boolean", + }, + { + "name": "hideZoomControls", + "optional": true, + "type": "boolean", + }, + ], + "type": "object", + }, + "name": "zoom", + "optional": true, + "systemTags": undefined, + "type": "BaseZoomOptions", + "visualRefreshTag": undefined, + }, + { + "analyticsTag": undefined, + "defaultValue": undefined, + "deprecatedTag": undefined, + "description": "The zoomed range of the x-axis. By default, the range is managed by the component. When using this property, +manage state updates with \`onZoomRangeChange\`, and use \`null\` to show the full data range. Update the property as soon +as \`onZoomRangeChange\` is called, including when its \`zoomRange\` is \`null\` after a reset. + +Supported options: +* \`x\` (optional, object) - The zoomed x-axis range, as \`startValue\` and \`endValue\`. For datetime axes, the +values are timestamps in milliseconds.", + "i18nTag": undefined, + "inlineType": { + "name": "BaseZoomRange", + "properties": [ + { + "inlineType": { + "name": "{ startValue: number; endValue: number; }", + "properties": [ + { + "name": "endValue", + "optional": false, + "type": "number", + }, + { + "name": "startValue", + "optional": false, + "type": "number", + }, + ], + "type": "object", + }, + "name": "x", + "optional": true, + "type": "{ startValue: number; endValue: number; }", + }, + ], + "type": "object", + }, + "name": "zoomRange", + "optional": true, + "systemTags": undefined, + "type": "BaseZoomRange | null", + "visualRefreshTag": undefined, + }, ], "regions": [ { diff --git a/src/cartesian-chart/__tests__/cartesian-chart-zoom.test.tsx b/src/cartesian-chart/__tests__/cartesian-chart-zoom.test.tsx index 52939d3c..4c07cc8c 100644 --- a/src/cartesian-chart/__tests__/cartesian-chart-zoom.test.tsx +++ b/src/cartesian-chart/__tests__/cartesian-chart-zoom.test.tsx @@ -1,6 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { act } from "react"; import highcharts from "highcharts"; import { afterEach, describe, expect, test, vi } from "vitest"; @@ -9,12 +10,11 @@ import { KeyCode } from "@cloudscape-design/component-toolkit/internal"; import "@cloudscape-design/components/test-utils/dom"; import "highcharts/highcharts-more"; import { CartesianChartProps } from "../../../lib/components/cartesian-chart"; -import { InternalZoomProps } from "../../../lib/components/core/internal-interfaces"; -import { createChartWrapper as getChart, getXExtremes } from "../../core/__tests__/common"; +import { getXExtremes } from "../../core/__tests__/common"; import { stubPlotGeometry } from "../../core/__tests__/plot-geometry"; import { zoomMessages } from "../../core/__tests__/zoom-messages"; import { enterZoomMode, getCursorAttributes, pressCursorKey } from "../../core/__tests__/zoom-test-utils"; -import { renderCartesianChart } from "./common"; +import { getChart, ref, renderCartesianChart } from "./common"; const series: CartesianChartProps.SeriesOptions[] = [ { @@ -40,11 +40,10 @@ const defaultProps = { const onZoomRangeChange = vi.fn(); -type ZoomTestProps = Partial & - InternalZoomProps & { - highcharts: typeof highcharts; - i18nProvider?: Record>; - }; +type ZoomTestProps = Partial & { + highcharts: typeof highcharts; + i18nProvider?: Record>; +}; function renderZoomChart(props: ZoomTestProps) { const { rerender } = renderCartesianChart(props); @@ -175,3 +174,42 @@ describe("CartesianChart: zoom selection, with other series types", () => { expect(getChart().findZoomButton()).toBe(null); }); }); + +describe("CartesianChart: zoom API", () => { + test("zooms and resets through the ref", () => { + renderZoomChart({ ...defaultProps, zoom: { enabled: true, hideZoomControls: true }, onZoomRangeChange }); + act(() => ref.current!.enterZoomMode()); + expect(document.activeElement).toBe(getChart().findZoomCursor()!.getElement()); + pressCursorKey(KeyCode.enter); + pressCursorKey(KeyCode.right, 2); + pressCursorKey(KeyCode.enter); + expect(getXExtremes()).toEqual({ min: 0, max: 2 }); + + act(() => ref.current!.resetZoom()); + expect(getXExtremes()).toEqual({ min: 0, max: 4 }); + expect(onZoomRangeChange).toHaveBeenLastCalledWith(expect.objectContaining({ detail: { zoomRange: null } })); + }); + + test("exits zoom mode through the ref without zooming", () => { + renderZoomChart({ ...defaultProps, zoom: { enabled: true }, onZoomRangeChange }); + act(() => ref.current!.enterZoomMode()); + pressCursorKey(KeyCode.enter); + expect(getChart().findExitZoomButton()).not.toBe(null); + act(() => ref.current!.exitZoomMode()); + expect(getChart().findExitZoomButton()).toBe(null); + expect(getChart().findZoomButton()).not.toBe(null); + expect(getXExtremes()).toEqual({ min: 0, max: 4 }); + expect(onZoomRangeChange).not.toHaveBeenCalled(); + }); + + test("uses the zoom labels from i18nStrings", () => { + renderZoomChart({ + ...defaultProps, + zoom: { enabled: true }, + zoomRange: { x: { startValue: 1, endValue: 3 } }, + i18nStrings: { enterZoomModeButtonText: "Zoom in", resetZoomButtonText: "Show all" }, + }); + expect(getChart().findZoomButton()!.getElement()).toHaveTextContent("Zoom in"); + expect(getChart().findResetZoomButton()!.getElement()).toHaveTextContent("Show all"); + }); +}); diff --git a/src/cartesian-chart/chart-cartesian-internal.tsx b/src/cartesian-chart/chart-cartesian-internal.tsx index aaa50670..2d1eb862 100644 --- a/src/cartesian-chart/chart-cartesian-internal.tsx +++ b/src/cartesian-chart/chart-cartesian-internal.tsx @@ -99,6 +99,9 @@ export const InternalCartesianChart = forwardRef( useImperativeHandle(ref, () => ({ setVisibleSeries: (visibleSeriesIds) => apiRef.current?.setItemsVisible(visibleSeriesIds), showAllSeries: () => apiRef.current?.setItemsVisible(allSeriesIds), + enterZoomMode: () => apiRef.current?.enterZoomMode(), + exitZoomMode: () => apiRef.current?.exitZoomMode(), + resetZoom: () => apiRef.current?.resetZoom(), })); return ( diff --git a/src/cartesian-chart/interfaces.ts b/src/cartesian-chart/interfaces.ts index 87bc0210..596b2888 100644 --- a/src/cartesian-chart/interfaces.ts +++ b/src/cartesian-chart/interfaces.ts @@ -109,6 +109,35 @@ export interface CartesianChartProps */ sizeAxis?: CartesianChartProps.SizeAxisOptions | readonly CartesianChartProps.SizeAxisOptions[]; + /** + * Zoom settings. When zoom is enabled, users can zoom into a range of the x-axis by dragging across the plot, + * or by selecting the zoom button and choosing a start and end point with a click or the keyboard. + * After zooming in, a reset button shows the full data range again. + * + * Supported options: + * * `enabled` (optional, boolean) - Enables zoom. Defaults to `false`. + * * `hideZoomControls` (optional, boolean) - Hides the built-in zoom and reset buttons. Use it only when you provide + * your own controls that call the `enterZoomMode`, `exitZoomMode`, and `resetZoom` methods of the component's ref. + */ + zoom?: CartesianChartProps.ZoomOptions; + + /** + * The zoomed range of the x-axis. By default, the range is managed by the component. When using this property, + * manage state updates with `onZoomRangeChange`, and use `null` to show the full data range. Update the property as soon + * as `onZoomRangeChange` is called, including when its `zoomRange` is `null` after a reset. + * + * Supported options: + * * `x` (optional, object) - The zoomed x-axis range, as `startValue` and `endValue`. For datetime axes, the + * values are timestamps in milliseconds. + */ + zoomRange?: null | CartesianChartProps.ZoomRange; + + /** + * Called when the user changes the zoomed range. The detail's `zoomRange` is `null` when the zoom is reset to the + * full data range. + */ + onZoomRangeChange?: NonCancelableEventHandler; + /** * Specifies which series to show using their IDs. By default, all series are visible and managed by the component. * If a series doesn't have an ID, its name is used. When using this property, manage state updates with `onVisibleSeriesChange`. @@ -132,6 +161,23 @@ export namespace CartesianChartProps { * Use this when implementing clear-filter actions in no-match states. */ showAllSeries(): void; + + /** + * Enters zoom mode, in which the user selects the start and end of the range to zoom into. + * Requires zoom to be enabled with the `zoom` property. + */ + enterZoomMode(): void; + + /** + * Exits zoom mode without zooming. A range the chart is already zoomed into is kept. + */ + exitZoomMode(): void; + + /** + * Resets the zoom to show the full data range. When the range is controlled with `zoomRange`, + * it calls `onZoomRangeChange` with a `null` range. + */ + resetZoom(): void; } export type SeriesOptions = @@ -219,6 +265,12 @@ export namespace CartesianChartProps { export type FilterOptions = CoreTypes.BaseFilterOptions; export type NoDataOptions = CoreTypes.BaseNoDataOptions; + + export type ZoomOptions = CoreTypes.BaseZoomOptions; + + export type ZoomRange = CoreTypes.BaseZoomRange; + + export type ZoomChangeDetail = CoreTypes.BaseZoomChangeDetail; } // Internal types diff --git a/src/core/__tests__/chart-core-rendering.test.tsx b/src/core/__tests__/chart-core-rendering.test.tsx index 708c9075..ecc01cf8 100644 --- a/src/core/__tests__/chart-core-rendering.test.tsx +++ b/src/core/__tests__/chart-core-rendering.test.tsx @@ -43,6 +43,9 @@ describe("CoreChart: rendering", () => { highlightChartPoint: expect.any(Function), highlightChartGroup: expect.any(Function), clearChartHighlight: expect.any(Function), + enterZoomMode: expect.any(Function), + exitZoomMode: expect.any(Function), + resetZoom: expect.any(Function), }); }); diff --git a/src/core/__tests__/chart-core-zoom.test.tsx b/src/core/__tests__/chart-core-zoom.test.tsx index b9f83b9a..0cab912b 100644 --- a/src/core/__tests__/chart-core-zoom.test.tsx +++ b/src/core/__tests__/chart-core-zoom.test.tsx @@ -9,7 +9,6 @@ import { KeyCode } from "@cloudscape-design/component-toolkit/internal"; import "highcharts/highcharts-more"; import { CoreChartProps } from "../../../lib/components/core/interfaces"; -import { ZoomRange } from "../../../lib/components/core/internal-interfaces"; import { getSeriesData } from "../../../lib/components/internal/utils/highcharts"; import { CoreChartTestProps, @@ -64,7 +63,7 @@ const defaultProps: CoreChartTestProps = { zoom: { enabled: true }, }; -const zoomedRange: ZoomRange = { x: { startValue: 1, endValue: 3 } }; +const zoomedRange: CoreChartProps.ZoomRange = { x: { startValue: 1, endValue: 3 } }; const onZoomRangeChange = vi.fn(); afterEach(() => { diff --git a/src/core/__tests__/common.tsx b/src/core/__tests__/common.tsx index c8405afe..39208c7b 100644 --- a/src/core/__tests__/common.tsx +++ b/src/core/__tests__/common.tsx @@ -6,11 +6,8 @@ import { fireEvent, render } from "@testing-library/react"; import highcharts from "highcharts"; import { vi } from "vitest"; -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 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"; @@ -21,23 +18,13 @@ import CoreChartWrapper from "../../../lib/components/test-utils/dom/internal/co export class ExtendedTestWrapper extends CoreChartWrapper { findHighchartsTooltip = () => this.findByClassName("highcharts-tooltip"); - findZoomButton = () => this.findComponent(`.${testClasses["zoom-button"]}`, ButtonWrapper); - findExitZoomButton = () => this.findComponent(`.${testClasses["exit-zoom-button"]}`, ButtonWrapper); - findResetZoomButton = () => { - const button = this.findComponent(`.${testClasses["reset-zoom-button"]}`, ButtonWrapper); - return button && !button.getElement().closest("[hidden]") ? button : null; - }; - findZoomCursor = () => this.findByClassName(testClasses["zoom-cursor"]); } -// The core chart accepts the internal zoom properties, which are not part of its public interface yet. -const CoreChartWithZoom = CoreChart as React.ComponentType; - -export function StatefulChart(props: CoreChartProps & InternalZoomProps) { +export function StatefulChart(props: CoreChartProps) { const [visibleItems, setVisibleItems] = useState(props.visibleItems ?? []); const [zoomRange, setZoomRange] = useState(props.zoomRange); return ( - { @@ -54,17 +41,16 @@ export function StatefulChart(props: CoreChartProps & InternalZoomProps) { ); } -export type CoreChartTestProps = Partial & - InternalZoomProps & { - onLegendItemHighlight?: () => void; - i18nProvider?: Record>; - }; +export type CoreChartTestProps = Partial & { + onLegendItemHighlight?: () => void; + i18nProvider?: Record>; +}; export function renderChart( { i18nProvider, ...props }: CoreChartTestProps, - Component: React.ComponentType = CoreChartWithZoom, + Component: React.ComponentType = CoreChart, ) { - const ComponentWrapper = (props: CoreChartProps & InternalZoomProps) => { + const ComponentWrapper = (props: CoreChartProps) => { return i18nProvider ? ( diff --git a/src/core/chart-api/chart-extra-context.tsx b/src/core/chart-api/chart-extra-context.tsx index 47d5e053..5a6be715 100644 --- a/src/core/chart-api/chart-extra-context.tsx +++ b/src/core/chart-api/chart-extra-context.tsx @@ -7,7 +7,6 @@ import { NonCancelableEventHandler } from "../../internal/events"; import { getChartSeries, getSeriesData, SafeChart, SafeSeries } from "../../internal/utils/highcharts"; import { ChartLabels } from "../i18n-utils"; import { CoreChartProps, Rect } from "../interfaces"; -import { ZoomChangeDetail, ZoomRange } from "../internal-interfaces"; import { getGroupRect, isSeriesStacked } from "../utils"; // Chart API context is used for dependency injection for chart utilities. @@ -40,12 +39,12 @@ export namespace ChartExtraContext { onHighlight?: NonCancelableEventHandler; onClearHighlight?: NonCancelableEventHandler; onVisibleItemsChange?: NonCancelableEventHandler; - onZoomRangeChange?: NonCancelableEventHandler; + onZoomRangeChange?: NonCancelableEventHandler; } export interface State { visibleItems?: readonly string[]; - zoomRange?: null | ZoomRange; + zoomRange?: null | CoreChartProps.ZoomRange; } export interface DerivedState { diff --git a/src/core/chart-api/chart-extra-zoom.ts b/src/core/chart-api/chart-extra-zoom.ts index 80056541..a3e21f44 100644 --- a/src/core/chart-api/chart-extra-zoom.ts +++ b/src/core/chart-api/chart-extra-zoom.ts @@ -25,8 +25,7 @@ import { } from "../chart-zoom/zoom-state-machine"; import { createStopMapper, findNearestIndex, getCursorStops, getPageStep } from "../chart-zoom/zoom-utils"; import { getFormatter } from "../formatters"; -import { Rect } from "../interfaces"; -import { ZoomRange } from "../internal-interfaces"; +import { CoreChartProps, Rect } from "../interfaces"; import { isInsidePlot } from "../utils"; import { ChartExtraContext } from "./chart-extra-context"; @@ -621,7 +620,7 @@ export class ChartExtraZoom extends AsyncStore { }; } -function extremesFromRange(zoomRange: undefined | null | ZoomRange): null | ZoomExtremes { +function extremesFromRange(zoomRange: undefined | null | CoreChartProps.ZoomRange): null | ZoomExtremes { const x = zoomRange?.x; return x ? { min: Math.min(x.startValue, x.endValue), max: Math.max(x.startValue, x.endValue) } : null; } diff --git a/src/core/chart-api/index.tsx b/src/core/chart-api/index.tsx index 0a517d72..b5d87f20 100644 --- a/src/core/chart-api/index.tsx +++ b/src/core/chart-api/index.tsx @@ -285,6 +285,9 @@ export class ChartAPI { highlightChartPoint: (point: Highcharts.Point) => this.highlightChartPoint(point, { isApiCall: true }), highlightChartGroup: (group: readonly Highcharts.Point[]) => this.highlightChartGroup(group, { isApiCall: true }), clearChartHighlight: () => this.clearChartHighlight({ isApiCall: true }), + enterZoomMode: () => this.enterZoomMode(), + exitZoomMode: () => this.exitZoomMode(), + resetZoom: () => this.resetZoom(), }; } diff --git a/src/core/chart-core.tsx b/src/core/chart-core.tsx index 66f919ec..ab0ec0bf 100644 --- a/src/core/chart-core.tsx +++ b/src/core/chart-core.tsx @@ -35,7 +35,6 @@ 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 { getLegendsProps, getPointAccessibleDescription } from "./utils"; import styles from "./styles.css.js"; @@ -78,7 +77,7 @@ export function InternalCoreChart({ __internalRootRef, getItemOptions, ...rest -}: CoreChartProps & InternalBaseComponentProps & InternalZoomProps) { +}: CoreChartProps & InternalBaseComponentProps) { 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. diff --git a/src/core/components/core-zoom-controls.tsx b/src/core/components/core-zoom-controls.tsx index a432e94d..939c386b 100644 --- a/src/core/components/core-zoom-controls.tsx +++ b/src/core/components/core-zoom-controls.tsx @@ -45,7 +45,7 @@ export function ChartZoomControls({ api, labels }: { api: ChartAPI; labels: Char formAction="none" onClick={api.resetZoom} ariaLabel={labels.resetZoomButtonAriaLabel} - className={testClasses["reset-zoom-button"]} + className={zoomed && !zooming ? testClasses["reset-zoom-button"] : undefined} > {labels.resetZoomButtonText} diff --git a/src/core/i18n-utils.tsx b/src/core/i18n-utils.tsx index e9a07015..e6de9eb2 100644 --- a/src/core/i18n-utils.tsx +++ b/src/core/i18n-utils.tsx @@ -40,13 +40,15 @@ export function useChartI18n({ const i18n = useInternalI18n("[charts]"); const i18nPie = useInternalI18n("pie-chart"); // The disabled reason is not part of the typed "[charts]" namespace of the components package yet. - const i18nUntyped = i18n as unknown as (key: string, provided: undefined) => undefined | string; + const i18nUntyped = i18n as unknown as (key: string, provided: undefined | string) => undefined | string; const valueText = ( key: "i18nStrings.zoomModeEnteredAnnouncementText" | "i18nStrings.zoomStartPointAnnouncementText", - ) => i18n(key, undefined, (format) => (value: string) => format({ value })); + provided?: (value: string) => string, + ) => i18n(key, provided, (format) => (value: string) => format({ value })); const rangeText = ( key: "i18nStrings.zoomRangeChangeAnnouncementText" | "i18nStrings.zoomSelectionAnnouncementText", - ) => i18n(key, undefined, (format) => (startValue: string, endValue: string) => format({ startValue, endValue })); + provided?: (startValue: string, endValue: string) => string, + ) => i18n(key, provided, (format) => (startValue: string, endValue: string) => format({ startValue, endValue })); return { chartLabel: ariaLabel, chartDescription: ariaDescription, @@ -56,18 +58,36 @@ export function useChartI18n({ chartXAxisLabel: i18n("i18nStrings.xAxisAriaRoleDescription", i18nStrings?.xAxisRoleDescription), chartYAxisLabel: i18n("i18nStrings.yAxisAriaRoleDescription", i18nStrings?.yAxisRoleDescription), chartSegmentLabel: i18nPie("i18nStrings.segmentAriaRoleDescription", i18nStrings?.segmentRoleDescription), - enterZoomModeButtonText: i18n("i18nStrings.enterZoomModeButtonText", undefined), - zoomButtonDisabledReason: i18nUntyped("i18nStrings.zoomButtonDisabledReason", undefined), - resetZoomButtonText: i18n("i18nStrings.resetZoomButtonText", undefined), - resetZoomButtonAriaLabel: i18n("i18nStrings.resetZoomButtonAriaLabel", undefined), - zoomControlsAriaLabel: i18n("i18nStrings.zoomControlsAriaLabel", undefined), - zoomCursorAriaLabel: i18n("i18nStrings.zoomCursorAriaLabel", undefined), - zoomModeEnteredAnnouncementText: valueText("i18nStrings.zoomModeEnteredAnnouncementText"), - zoomStartPointAnnouncementText: valueText("i18nStrings.zoomStartPointAnnouncementText"), - zoomRangeChangeAnnouncementText: rangeText("i18nStrings.zoomRangeChangeAnnouncementText"), - zoomSelectionAnnouncementText: rangeText("i18nStrings.zoomSelectionAnnouncementText"), - zoomModeExitedAnnouncementText: i18n("i18nStrings.zoomModeExitedAnnouncementText", undefined), - zoomResetAnnouncementText: i18n("i18nStrings.zoomResetAnnouncementText", undefined), + enterZoomModeButtonText: i18n("i18nStrings.enterZoomModeButtonText", i18nStrings?.enterZoomModeButtonText), + zoomButtonDisabledReason: i18nUntyped( + "i18nStrings.zoomButtonDisabledReason", + i18nStrings?.zoomButtonDisabledReason, + ), + resetZoomButtonText: i18n("i18nStrings.resetZoomButtonText", i18nStrings?.resetZoomButtonText), + resetZoomButtonAriaLabel: i18n("i18nStrings.resetZoomButtonAriaLabel", i18nStrings?.resetZoomButtonAriaLabel), + zoomControlsAriaLabel: i18n("i18nStrings.zoomControlsAriaLabel", i18nStrings?.zoomControlsAriaLabel), + zoomCursorAriaLabel: i18n("i18nStrings.zoomCursorAriaLabel", i18nStrings?.zoomCursorAriaLabel), + zoomModeEnteredAnnouncementText: valueText( + "i18nStrings.zoomModeEnteredAnnouncementText", + i18nStrings?.zoomModeEnteredAnnouncementText, + ), + zoomStartPointAnnouncementText: valueText( + "i18nStrings.zoomStartPointAnnouncementText", + i18nStrings?.zoomStartPointAnnouncementText, + ), + zoomRangeChangeAnnouncementText: rangeText( + "i18nStrings.zoomRangeChangeAnnouncementText", + i18nStrings?.zoomRangeChangeAnnouncementText, + ), + zoomSelectionAnnouncementText: rangeText( + "i18nStrings.zoomSelectionAnnouncementText", + i18nStrings?.zoomSelectionAnnouncementText, + ), + zoomModeExitedAnnouncementText: i18n( + "i18nStrings.zoomModeExitedAnnouncementText", + i18nStrings?.zoomModeExitedAnnouncementText, + ), + zoomResetAnnouncementText: i18n("i18nStrings.zoomResetAnnouncementText", i18nStrings?.zoomResetAnnouncementText), itemMarkerLabel: (status = "default") => { switch (status) { case "warning": diff --git a/src/core/interfaces.ts b/src/core/interfaces.ts index 9c910817..57c9a918 100644 --- a/src/core/interfaces.ts +++ b/src/core/interfaces.ts @@ -160,6 +160,18 @@ export interface WithCartesianI18nStrings { * * `chartRoleDescription` (optional, string) - Accessible role description of the chart plot area, e.g. "interactive chart". * * `xAxisRoleDescription` (optional, string) - Accessible role description of the x axis, e.g. "x axis". * * `yAxisRoleDescription` (optional, string) - Accessible role description of the y axis, e.g. "y axis". + * * `enterZoomModeButtonText` (optional, string) - Visible label of the button that enters zoom mode. + * * `zoomButtonDisabledReason` (optional, string) - Reason shown when the zoom button is disabled because there is no narrower range to zoom into. + * * `resetZoomButtonText` (optional, string) - Visible label of the button that resets the zoom to the full data range. + * * `resetZoomButtonAriaLabel` (optional, string) - ARIA label of the button that resets the zoom. + * * `zoomControlsAriaLabel` (optional, string) - ARIA label of the zoom controls region. + * * `zoomCursorAriaLabel` (optional, string) - ARIA label of the zoom range cursor. + * * `zoomModeEnteredAnnouncementText` (optional, function) - Announcement when zoom mode is entered. Receives the formatted cursor value. + * * `zoomStartPointAnnouncementText` (optional, function) - Announcement when the start of the range is set. Receives the formatted start value. + * * `zoomSelectionAnnouncementText` (optional, function) - Accessible value of the zoom cursor while a range is being selected. Receives the formatted start and end values. + * * `zoomRangeChangeAnnouncementText` (optional, function) - Announcement when the chart zooms into a range. Receives the formatted start and end values. + * * `zoomModeExitedAnnouncementText` (optional, string) - Announcement when zoom mode is exited without zooming. + * * `zoomResetAnnouncementText` (optional, string) - Announcement when the zoom is reset to the full data range. */ i18nStrings?: CartesianI18nStrings; } @@ -187,6 +199,18 @@ export interface WithPieI18nStrings { export interface CartesianI18nStrings extends BaseI18nStrings { xAxisRoleDescription?: string; yAxisRoleDescription?: string; + enterZoomModeButtonText?: string; + zoomButtonDisabledReason?: string; + resetZoomButtonText?: string; + resetZoomButtonAriaLabel?: string; + zoomControlsAriaLabel?: string; + zoomCursorAriaLabel?: string; + zoomModeEnteredAnnouncementText?: (value: string) => string; + zoomStartPointAnnouncementText?: (value: string) => string; + zoomSelectionAnnouncementText?: (startValue: string, endValue: string) => string; + zoomRangeChangeAnnouncementText?: (startValue: string, endValue: string) => string; + zoomModeExitedAnnouncementText?: string; + zoomResetAnnouncementText?: string; } export interface PieI18nStrings extends BaseI18nStrings { @@ -198,6 +222,19 @@ export interface BaseFilterOptions { additionalFilters?: React.ReactNode; } +export interface BaseZoomOptions { + enabled?: boolean; + hideZoomControls?: boolean; +} + +export interface BaseZoomRange { + x?: { startValue: number; endValue: number }; +} + +export interface BaseZoomChangeDetail { + zoomRange: null | BaseZoomRange; +} + export interface BaseTooltipPointFormatted { key?: React.ReactNode; value?: React.ReactNode; @@ -392,6 +429,33 @@ export interface CoreChartProps * Use this property to add timeline navigation, range selectors, or other custom navigation elements. */ navigator?: React.ReactNode; + /** + * Zoom settings. When zoom is enabled, users can zoom into a range of the x-axis by dragging across the plot, + * or by selecting the zoom button and choosing a start and end point with a click or the keyboard. + * + * Supported options: + * * `enabled` (optional, boolean) - Enables zoom. Defaults to `false`. + * * `hideZoomControls` (optional, boolean) - Hides the built-in zoom and reset buttons. Use it only when you provide + * your own controls that call the `enterZoomMode`, `exitZoomMode`, and `resetZoom` methods. + * + * Zoom applies to the first x-axis, and requires `options.xAxis` to be defined. + */ + zoom?: CoreChartProps.ZoomOptions; + /** + * The zoomed range of the x-axis. By default, the range is managed by the component. When using this property, + * manage state updates with `onZoomRangeChange`, and use `null` to show the full data range. Update the property as soon + * as `onZoomRangeChange` is called, including when its `zoomRange` is `null` after a reset. + * + * Supported options: + * * `x` (optional, object) - The zoomed x-axis range, as `startValue` and `endValue`. For datetime axes, the + * values are timestamps in milliseconds. + */ + zoomRange?: null | CoreChartProps.ZoomRange; + /** + * Called when the user changes the zoomed range. The detail's `zoomRange` is `null` when the zoom is reset to the + * full data range. + */ + onZoomRangeChange?: NonCancelableEventHandler; /** * A custom slot below the chart plot and legend. */ @@ -466,6 +530,9 @@ export namespace CoreChartProps { highlightChartPoint(point: Highcharts.Point): void; highlightChartGroup(group: readonly Highcharts.Point[]): void; clearChartHighlight(): void; + enterZoomMode(): void; + exitZoomMode(): void; + resetZoom(): void; } /** @@ -620,6 +687,12 @@ export namespace CoreChartProps { } export type I18nStrings = CartesianI18nStrings & PieI18nStrings & CoreI18nStrings; + + export type ZoomOptions = BaseZoomOptions; + + export type ZoomRange = BaseZoomRange; + + export type ZoomChangeDetail = BaseZoomChangeDetail; } export interface CoreLegendProps { diff --git a/src/core/internal-interfaces.ts b/src/core/internal-interfaces.ts deleted file mode 100644 index 254b4b0d..00000000 --- a/src/core/internal-interfaces.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import type { NonCancelableEventHandler } from "../internal/events"; - -export interface ZoomOptions { - enabled?: boolean; - hideZoomControls?: boolean; -} - -// The range is nested under the axis it applies to, leaving room for a "y" range should zooming -// along the y-axis be supported later, without a breaking change to the property shape. -export interface ZoomRange { - x?: { startValue: number; endValue: number }; -} - -export interface ZoomChangeDetail { - zoomRange: ZoomRange | null; -} - -// The zoom properties accepted by the internal core chart. They are not part of any public component -// interface yet. -export interface InternalZoomProps { - zoom?: ZoomOptions; - zoomRange?: ZoomRange | null; - onZoomRangeChange?: NonCancelableEventHandler; -} diff --git a/src/test-utils/dom/cartesian-chart/index.ts b/src/test-utils/dom/cartesian-chart/index.ts index da825494..d7f5bdfd 100644 --- a/src/test-utils/dom/cartesian-chart/index.ts +++ b/src/test-utils/dom/cartesian-chart/index.ts @@ -1,12 +1,14 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { ButtonWrapper } from "@cloudscape-design/components/test-utils/dom"; import { ElementWrapper } from "@cloudscape-design/test-utils-core/dom"; import BaseChartWrapper from "../internal/base"; import { CartesianChartTooltipWrapper } from "./tooltip"; import testClasses from "../../../cartesian-chart/test-classes/styles.selectors.js"; +import coreTestClasses from "../../../core/test-classes/styles.selectors.js"; export default class CartesianChartWrapper extends BaseChartWrapper { static rootSelector: string = testClasses.root; @@ -24,4 +26,32 @@ export default class CartesianChartWrapper extends BaseChartWrapper { public findSeries(): Array { return this.findAllByClassName("highcharts-series"); } + + /** + * Finds the zoom button that enters zoom mode. + */ + public findZoomButton(): null | ButtonWrapper { + return this.findComponent(`.${coreTestClasses["zoom-button"]}`, ButtonWrapper); + } + + /** + * Finds the pressed zoom button that exits zoom mode, shown while a range is being selected. + */ + public findExitZoomButton(): null | ButtonWrapper { + return this.findComponent(`.${coreTestClasses["exit-zoom-button"]}`, ButtonWrapper); + } + + /** + * Finds the reset button, shown when the chart is zoomed in. + */ + public findResetZoomButton(): null | ButtonWrapper { + return this.findComponent(`.${coreTestClasses["reset-zoom-button"]}`, ButtonWrapper); + } + + /** + * Finds the zoom cursor, which holds the keyboard focus while a range is being selected. + */ + public findZoomCursor(): null | ElementWrapper { + return this.findByClassName(coreTestClasses["zoom-cursor"]); + } } diff --git a/src/test-utils/dom/internal/core.ts b/src/test-utils/dom/internal/core.ts index c14f4f6b..1f4b59db 100644 --- a/src/test-utils/dom/internal/core.ts +++ b/src/test-utils/dom/internal/core.ts @@ -1,6 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { ButtonWrapper } from "@cloudscape-design/components/test-utils/dom"; import ChartTooltipWrapper from "@cloudscape-design/components/test-utils/dom/internal/chart-tooltip"; import { ElementWrapper } from "@cloudscape-design/test-utils-core/dom"; @@ -38,6 +39,34 @@ export default class CoreChartWrapper extends BaseChartWrapper { public findHorizontalAxisTitle(): null | ElementWrapper { return this.find(`.highcharts-axis.${testClasses["axis-horizontal"]} > .highcharts-axis-title`); } + + /** + * Finds the zoom button that enters zoom mode. + */ + public findZoomButton(): null | ButtonWrapper { + return this.findComponent(`.${testClasses["zoom-button"]}`, ButtonWrapper); + } + + /** + * Finds the pressed zoom button that exits zoom mode, shown while a range is being selected. + */ + public findExitZoomButton(): null | ButtonWrapper { + return this.findComponent(`.${testClasses["exit-zoom-button"]}`, ButtonWrapper); + } + + /** + * Finds the reset button, shown when the chart is zoomed in. + */ + public findResetZoomButton(): null | ButtonWrapper { + return this.findComponent(`.${testClasses["reset-zoom-button"]}`, ButtonWrapper); + } + + /** + * Finds the zoom cursor, which holds the keyboard focus while a range is being selected. + */ + public findZoomCursor(): null | ElementWrapper { + return this.findByClassName(testClasses["zoom-cursor"]); + } } export class CoreChartLegendWrapper extends BaseChartLegendWrapper { diff --git a/test/functional/cartesian-chart.test.ts b/test/functional/cartesian-chart.test.ts index a12262b1..9bbfd4f6 100644 --- a/test/functional/cartesian-chart.test.ts +++ b/test/functional/cartesian-chart.test.ts @@ -8,8 +8,6 @@ import "../../lib/components/test-utils/selectors"; import createWrapper from "../../lib/components/test-utils/selectors"; import { setupTest } from "../utils"; -import testClasses from "../../lib/components/core/test-classes/styles.selectors.js"; - const w = createWrapper(); test.each([ @@ -46,7 +44,7 @@ test( setupTest("#/01-cartesian-chart/column-chart-test?zoom=true", async (page) => { const chart = w.findCartesianHighcharts('[data-testid="grouped-column-chart"]'); const plotBox = await page.getBoundingBox(chart.find(".highcharts-plot-background").toSelector()); - const resetButton = chart.find(`.${testClasses["reset-zoom-button"]}`).toSelector(); + const resetButton = chart.findResetZoomButton().toSelector(); await page.moveCursorTo(plotBox.left + plotBox.width * 0.2, plotBox.top + plotBox.height / 2); await page.dragCursorBy(Math.round(plotBox.width * 0.5), 0); From 71533ec90d163b303641fed89e2ceae02a34e5e2 Mon Sep 17 00:00:00 2001 From: Shivam Rungta Date: Wed, 18 Nov 2026 14:05:02 +0100 Subject: [PATCH 2/3] fix: Guard zoom entry and keep focus with hidden controls enterZoomMode now does nothing while zoom is disabled. Turning zoom off kept the cursor stops, so the call still entered zoom mode and locked the pointer. When the built-in zoom controls are hidden, the focus goes back to the element that entered zoom mode once a range is selected or zoom mode is cancelled, instead of dropping to the page body. --- .../__tests__/cartesian-chart-zoom.test.tsx | 31 ++++++++++++++++++- src/core/chart-api/chart-extra-zoom.ts | 22 ++++++++++--- 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/src/cartesian-chart/__tests__/cartesian-chart-zoom.test.tsx b/src/cartesian-chart/__tests__/cartesian-chart-zoom.test.tsx index 4c07cc8c..0e75669f 100644 --- a/src/cartesian-chart/__tests__/cartesian-chart-zoom.test.tsx +++ b/src/cartesian-chart/__tests__/cartesian-chart-zoom.test.tsx @@ -10,7 +10,8 @@ import { KeyCode } from "@cloudscape-design/component-toolkit/internal"; import "@cloudscape-design/components/test-utils/dom"; import "highcharts/highcharts-more"; import { CartesianChartProps } from "../../../lib/components/cartesian-chart"; -import { getXExtremes } from "../../core/__tests__/common"; +import { getSeriesData } from "../../../lib/components/internal/utils/highcharts"; +import { getCurrentChart, getXExtremes } from "../../core/__tests__/common"; import { stubPlotGeometry } from "../../core/__tests__/plot-geometry"; import { zoomMessages } from "../../core/__tests__/zoom-messages"; import { enterZoomMode, getCursorAttributes, pressCursorKey } from "../../core/__tests__/zoom-test-utils"; @@ -202,6 +203,34 @@ describe("CartesianChart: zoom API", () => { expect(onZoomRangeChange).not.toHaveBeenCalled(); }); + test.each([ + { name: "a range is selected", keys: [KeyCode.enter, KeyCode.right, KeyCode.right, KeyCode.enter] }, + { name: "zoom mode is cancelled", keys: [KeyCode.escape] }, + ])("returns the focus to the custom control when $name with the zoom controls hidden", ({ keys }) => { + renderZoomChart({ ...defaultProps, zoom: { enabled: true, hideZoomControls: true } }); + const customButton = document.createElement("button"); + customButton.dataset.testid = "outside"; + document.body.appendChild(customButton); + customButton.focus(); + act(() => ref.current!.enterZoomMode()); + keys.forEach((key) => pressCursorKey(key)); + expect(document.activeElement).toBe(customButton); + }); + + test("ignores enterZoomMode once zoom is disabled", async () => { + const { rerender } = renderZoomChart({ ...defaultProps, zoom: { enabled: true } }); + rerender({ ...defaultProps, zoom: { enabled: false } }); + act(() => ref.current!.enterZoomMode()); + vi.useFakeTimers(); + try { + act(() => getSeriesData(getCurrentChart().series[0])[2].onMouseOver()); + await act(() => vi.advanceTimersByTimeAsync(500)); + expect(getChart().findTooltip()).not.toBe(null); + } finally { + vi.useRealTimers(); + } + }); + test("uses the zoom labels from i18nStrings", () => { renderZoomChart({ ...defaultProps, diff --git a/src/core/chart-api/chart-extra-zoom.ts b/src/core/chart-api/chart-extra-zoom.ts index a3e21f44..df5933f4 100644 --- a/src/core/chart-api/chart-extra-zoom.ts +++ b/src/core/chart-api/chart-extra-zoom.ts @@ -71,6 +71,7 @@ export class ChartExtraZoom extends AsyncStore { private controlsElement: null | HTMLElement = null; private zoomButton: null | FocusableControl = null; private resetButton: null | FocusableControl = null; + private entryFocus: null | HTMLElement = null; private rangeBand = new SVGRendererSingle(); private rangeBorders = new SVGRendererSingle(); private selectionBand = new SVGRendererSingle(); @@ -159,6 +160,7 @@ export class ChartExtraZoom extends AsyncStore { if (!this.enabled) { this.localExtremes = null; this.interaction = INACTIVE_ZOOM_STATE; + this.entryFocus = null; this.pressClickPending = false; this.hideOverlay(); this.setCommon({ zooming: false }); @@ -174,7 +176,15 @@ export class ChartExtraZoom extends AsyncStore { }; public enterZoomMode = () => { + if (!this.enabled || isZooming(this.interaction)) { + return; + } + const activeElement = this.container?.ownerDocument.activeElement; + this.entryFocus = activeElement instanceof HTMLElement ? activeElement : null; this.dispatch({ type: "enter" }); + if (!isZooming(this.interaction)) { + this.entryFocus = null; + } }; public exitZoomMode = (reason: ZoomCancelReason) => { @@ -344,6 +354,10 @@ export class ChartExtraZoom extends AsyncStore { return; } this.interaction = state; + const entryFocus = this.entryFocus; + if (!isZooming(state)) { + this.entryFocus = null; + } if (isZooming(state) !== isZooming(previous)) { this.setCommon({ zooming: isZooming(state) }); if (isZooming(state)) { @@ -357,21 +371,21 @@ export class ChartExtraZoom extends AsyncStore { // The focus moves last, once the overlay shows the cursor at its position. for (const effect of effects) { if (effect.type === "focus") { - this.moveFocus(effect.target); + this.moveFocus(effect.target, entryFocus); } } } - private moveFocus(target: ZoomFocusTarget) { + private moveFocus(target: ZoomFocusTarget, fallback: null | HTMLElement = null) { switch (target) { case "cursor": this.cursorElement?.focus(); break; case "zoomButton": - this.zoomButton?.focus(); + (this.zoomButton ?? fallback)?.focus(); break; case "resetButton": - this.resetButton?.focus(); + (this.resetButton ?? fallback)?.focus(); break; } } From 5893ab0c5d5836094accf45c2bcedb90bd05f5d4 Mon Sep 17 00:00:00 2001 From: Shivam Rungta Date: Wed, 18 Nov 2026 14:37:57 +0100 Subject: [PATCH 3/3] docs: Say that the zoom range can be left to the chart The zoomRange docs now say up front that the property is optional, and that the chart keeps track of the zoomed range when it isn't set. --- .../__snapshots__/documenter.test.ts.snap | 14 ++++++++------ src/cartesian-chart/interfaces.ts | 7 ++++--- src/core/interfaces.ts | 7 ++++--- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/__tests__/__snapshots__/documenter.test.ts.snap b/src/__tests__/__snapshots__/documenter.test.ts.snap index fb793164..20dd0e7c 100644 --- a/src/__tests__/__snapshots__/documenter.test.ts.snap +++ b/src/__tests__/__snapshots__/documenter.test.ts.snap @@ -827,9 +827,10 @@ your own controls that call the \`enterZoomMode\`, \`exitZoomMode\`, and \`reset "type": "BaseZoomOptions", }, { - "description": "The zoomed range of the x-axis. By default, the range is managed by the component. When using this property, -manage state updates with \`onZoomRangeChange\`, and use \`null\` to show the full data range. Update the property as soon -as \`onZoomRangeChange\` is called, including when its \`zoomRange\` is \`null\` after a reset. + "description": "The zoomed range of the x-axis. This property is optional: when it isn't set, the component keeps track of the +zoomed range itself, and \`onZoomRangeChange\` still reports the changes. +When you set it, the range is controlled. Update it in \`onZoomRangeChange\` as soon as the event is called, +and use \`null\` to show the full data range, which the event passes after a reset. Supported options: * \`x\` (optional, object) - The zoomed x-axis range, as \`startValue\` and \`endValue\`. For datetime axes, the @@ -2221,9 +2222,10 @@ Zoom applies to the first x-axis, and requires \`options.xAxis\` to be defined." "analyticsTag": undefined, "defaultValue": undefined, "deprecatedTag": undefined, - "description": "The zoomed range of the x-axis. By default, the range is managed by the component. When using this property, -manage state updates with \`onZoomRangeChange\`, and use \`null\` to show the full data range. Update the property as soon -as \`onZoomRangeChange\` is called, including when its \`zoomRange\` is \`null\` after a reset. + "description": "The zoomed range of the x-axis. This property is optional: when it isn't set, the component keeps track of the +zoomed range itself, and \`onZoomRangeChange\` still reports the changes. +When you set it, the range is controlled. Update it in \`onZoomRangeChange\` as soon as the event is called, +and use \`null\` to show the full data range, which the event passes after a reset. Supported options: * \`x\` (optional, object) - The zoomed x-axis range, as \`startValue\` and \`endValue\`. For datetime axes, the diff --git a/src/cartesian-chart/interfaces.ts b/src/cartesian-chart/interfaces.ts index 596b2888..c96987bc 100644 --- a/src/cartesian-chart/interfaces.ts +++ b/src/cartesian-chart/interfaces.ts @@ -122,9 +122,10 @@ export interface CartesianChartProps zoom?: CartesianChartProps.ZoomOptions; /** - * The zoomed range of the x-axis. By default, the range is managed by the component. When using this property, - * manage state updates with `onZoomRangeChange`, and use `null` to show the full data range. Update the property as soon - * as `onZoomRangeChange` is called, including when its `zoomRange` is `null` after a reset. + * The zoomed range of the x-axis. This property is optional: when it isn't set, the component keeps track of the + * zoomed range itself, and `onZoomRangeChange` still reports the changes. + * When you set it, the range is controlled. Update it in `onZoomRangeChange` as soon as the event is called, + * and use `null` to show the full data range, which the event passes after a reset. * * Supported options: * * `x` (optional, object) - The zoomed x-axis range, as `startValue` and `endValue`. For datetime axes, the diff --git a/src/core/interfaces.ts b/src/core/interfaces.ts index 57c9a918..07ca4cb6 100644 --- a/src/core/interfaces.ts +++ b/src/core/interfaces.ts @@ -442,9 +442,10 @@ export interface CoreChartProps */ zoom?: CoreChartProps.ZoomOptions; /** - * The zoomed range of the x-axis. By default, the range is managed by the component. When using this property, - * manage state updates with `onZoomRangeChange`, and use `null` to show the full data range. Update the property as soon - * as `onZoomRangeChange` is called, including when its `zoomRange` is `null` after a reset. + * The zoomed range of the x-axis. This property is optional: when it isn't set, the component keeps track of the + * zoomed range itself, and `onZoomRangeChange` still reports the changes. + * When you set it, the range is controlled. Update it in `onZoomRangeChange` as soon as the event is called, + * and use `null` to show the full data range, which the event passes after a reset. * * Supported options: * * `x` (optional, object) - The zoomed x-axis range, as `startValue` and `endValue`. For datetime axes, the