An open source design system that's fully customizable and agent ready
TypeScript
fix(lab): ThreeDChart accessible name, pausable rotation, keyboard camera (#4381)
Baraa Hamodi6272b7a53f62
diff --git a/packages/lab/src/ThreeD/ThreeDChart.test.tsx b/packages/lab/src/ThreeD/ThreeDChart.test.tsxnew file mode 100644index 0000000000..9ca7a5ad1f--- /dev/null+++ b/packages/lab/src/ThreeD/ThreeDChart.test.tsx@@ -0,0 +1,251 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';+import {render, screen, act, fireEvent} from '@testing-library/react';+import {ThreeDChart} from './ThreeDChart';+import {use3D} from './ThreeDContext';++const data = [+ {x: 0, y: 0, z: 0},+ {x: 10, y: 20, z: 30},+];++/** Renders the current camera angles so tests can observe rotation. */+function CameraProbe() {+ const {camera} = use3D();+ return (+ <>+ <text data-testid="azimuth">{camera.azimuth}</text>+ <text data-testid="elevation">{camera.elevation}</text>+ </>+ );+}++function azimuth(): number {+ return Number(screen.getByTestId('azimuth').textContent);+}++function elevation(): number {+ return Number(screen.getByTestId('elevation').textContent);+}++// Capture the ResizeObserver callback so tests can drive the reported width.+let resizeCallback: ResizeObserverCallback | undefined;++// Manual rAF queue: callbacks are collected and only run when the test+// flushes them, so we can observe whether the rotation loop is scheduled.+let rafCallbacks: Map<number, FrameRequestCallback>;+let nextRafId: number;+let cancelSpy: ReturnType<typeof vi.fn>;++beforeEach(() => {+ resizeCallback = undefined;+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ constructor(cb: ResizeObserverCallback) {+ resizeCallback = cb;+ }+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );++ rafCallbacks = new Map();+ nextRafId = 0;+ cancelSpy = vi.fn((id: number) => {+ rafCallbacks.delete(id);+ });+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {+ nextRafId += 1;+ rafCallbacks.set(nextRafId, cb);+ return nextRafId;+ });+ vi.stubGlobal('cancelAnimationFrame', cancelSpy);+});++afterEach(() => {+ vi.unstubAllGlobals();+});++function reportWidth(width: number) {+ act(() => {+ resizeCallback?.(+ [{contentRect: {width}} as unknown as ResizeObserverEntry],+ {} as ResizeObserver,+ );+ });+}++function flushFrame(now: number) {+ const callbacks = [...rafCallbacks.values()];+ rafCallbacks.clear();+ act(() => {+ callbacks.forEach(cb => cb(now));+ });+}++/** matchMedia stub where prefers-reduced-motion: reduce matches. */+function stubReducedMotion() {+ vi.stubGlobal('matchMedia', (query: string): MediaQueryList => {+ return {+ matches: query === '(prefers-reduced-motion: reduce)',+ media: query,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => false,+ } as unknown as MediaQueryList;+ });+}++function renderChart(props: Partial<Parameters<typeof ThreeDChart>[0]> = {}) {+ const result = render(+ <ThreeDChart data={data} xKey="x" yKey="y" zKey="z" {...props}>+ <CameraProbe />+ </ThreeDChart>,+ );+ reportWidth(600);+ return result;+}++describe('ThreeDChart accessible name', () => {+ it('exposes role="img" with a default label derived from the data keys', () => {+ renderChart();+ expect(+ screen.getByRole('img', {name: '3D chart of y by x and z'}),+ ).toBeInTheDocument();+ });++ it('uses the label prop when provided', () => {+ renderChart({label: 'Revenue by region and quarter'});+ expect(+ screen.getByRole('img', {name: 'Revenue by region and quarter'}),+ ).toBeInTheDocument();+ });++ it('is not a tab stop when static (no interaction, no rotation)', () => {+ renderChart();+ expect(screen.getByRole('img')).not.toHaveAttribute('tabindex');+ });+});++describe('ThreeDChart auto-rotation', () => {+ it('rotates the camera when autoRotate is set', () => {+ renderChart({autoRotate: 1});+ expect(rafCallbacks.size).toBe(1);+ flushFrame(100);+ expect(azimuth()).toBeGreaterThan(35);+ });++ it('does not start the rotation loop under prefers-reduced-motion', () => {+ stubReducedMotion();+ renderChart({autoRotate: 1});+ expect(rafCallbacks.size).toBe(0);+ expect(azimuth()).toBe(35);+ });++ it('pauses rotation while hovered and resumes on leave', () => {+ renderChart({autoRotate: 1});+ expect(rafCallbacks.size).toBe(1);++ fireEvent.mouseOver(screen.getByRole('img'));+ expect(cancelSpy).toHaveBeenCalled();+ expect(rafCallbacks.size).toBe(0);++ const before = azimuth();+ flushFrame(200);+ expect(azimuth()).toBe(before);++ fireEvent.mouseOut(screen.getByRole('img'));+ expect(rafCallbacks.size).toBe(1);+ });++ it('pauses rotation while focused and resumes on blur', () => {+ renderChart({autoRotate: 1});+ expect(rafCallbacks.size).toBe(1);++ fireEvent.focus(screen.getByRole('img'));+ expect(cancelSpy).toHaveBeenCalled();+ expect(rafCallbacks.size).toBe(0);++ fireEvent.blur(screen.getByRole('img'));+ expect(rafCallbacks.size).toBe(1);+ });++ it('is focusable when auto-rotating so keyboard users can pause it', () => {+ renderChart({autoRotate: 1});+ expect(screen.getByRole('img')).toHaveAttribute('tabindex', '0');+ });+});++describe('ThreeDChart keyboard camera', () => {+ it('is focusable when interactive', () => {+ renderChart({interactive: true});+ expect(screen.getByRole('img')).toHaveAttribute('tabindex', '0');+ });++ it('rotates yaw with ArrowLeft/ArrowRight', () => {+ renderChart({interactive: true});+ const svg = screen.getByRole('img');++ fireEvent.keyDown(svg, {key: 'ArrowRight'});+ expect(azimuth()).toBe(45);++ fireEvent.keyDown(svg, {key: 'ArrowLeft'});+ fireEvent.keyDown(svg, {key: 'ArrowLeft'});+ expect(azimuth()).toBe(25);+ });++ it('rotates pitch with ArrowUp/ArrowDown', () => {+ renderChart({interactive: true});+ const svg = screen.getByRole('img');++ fireEvent.keyDown(svg, {key: 'ArrowUp'});+ expect(elevation()).toBe(35);++ fireEvent.keyDown(svg, {key: 'ArrowDown'});+ fireEvent.keyDown(svg, {key: 'ArrowDown'});+ expect(elevation()).toBe(15);+ });++ it('clamps pitch to the same [-89, 89] range as pointer drag', () => {+ renderChart({interactive: true, elevation: 85});+ const svg = screen.getByRole('img');++ fireEvent.keyDown(svg, {key: 'ArrowUp'});+ expect(elevation()).toBe(89);+ fireEvent.keyDown(svg, {key: 'ArrowUp'});+ expect(elevation()).toBe(89);+ });++ it('clamps pitch at the lower bound', () => {+ renderChart({interactive: true, elevation: -85});+ const svg = screen.getByRole('img');++ fireEvent.keyDown(svg, {key: 'ArrowDown'});+ expect(elevation()).toBe(-89);+ });++ it('prevents default on arrow keys so the page does not scroll', () => {+ renderChart({interactive: true});+ const svg = screen.getByRole('img');++ // fireEvent returns false when preventDefault() was called.+ expect(fireEvent.keyDown(svg, {key: 'ArrowRight'})).toBe(false);+ expect(fireEvent.keyDown(svg, {key: 'ArrowUp'})).toBe(false);+ // Non-camera keys are left alone.+ expect(fireEvent.keyDown(svg, {key: 'Enter'})).toBe(true);+ });++ it('ignores arrow keys when not interactive', () => {+ renderChart({autoRotate: 1});+ const svg = screen.getByRole('img');++ expect(fireEvent.keyDown(svg, {key: 'ArrowRight'})).toBe(true);+ expect(azimuth()).toBe(35);+ });+});diff --git a/packages/lab/src/ThreeD/ThreeDChart.tsx b/packages/lab/src/ThreeD/ThreeDChart.tsxindex 0d0c171c33..61ab906c2b 100644--- a/packages/lab/src/ThreeD/ThreeDChart.tsx+++ b/packages/lab/src/ThreeD/ThreeDChart.tsx@@ -2,12 +2,15 @@/*** @file ThreeDChart.tsx- * @output Root 3D chart container — projected SVG with depth sorting+ * @output Root 3D chart container — projected SVG with depth sorting,+ * accessible name, pointer + keyboard camera controls, and pausable+ * auto-rotation (respects prefers-reduced-motion)* @position Parent component; all 3D marks read from its context*/import {type CSSProperties,+ type KeyboardEvent as ReactKeyboardEvent,type ReactNode,useMemo,useRef,@@ -16,6 +19,7 @@ import {useLayoutEffect,useCallback,} from 'react';+import {useMediaQuery} from '@astryxdesign/core/hooks';import {ThreeDProvider} from './ThreeDContext';import type {Camera, ProjectedPoint} from './types';@@ -31,11 +35,25 @@ export interface ThreeDChartProps {azimuth?: number;elevation?: number;interactive?: boolean;- /** Auto-rotate speed in degrees per frame (default: 0 = off) */+ /**+ * Auto-rotate speed in degrees per frame (default: 0 = off).+ *+ * Rotation pauses while the chart is hovered or focused, and is disabled+ * entirely when the user has `prefers-reduced-motion: reduce` set. Pass 0+ * (or omit) to turn it off.+ */autoRotate?: number;+ /**+ * Accessible label for the chart. Defaults to a description derived from+ * the data keys, e.g. "3D chart of sales by month and region".+ */+ label?: string;children: ReactNode;}+/** Degrees the camera rotates per arrow-key press. */+const KEYBOARD_STEP_DEGREES = 10;+function computeDomain(data: Record<string, unknown>[],key: string,@@ -69,10 +87,16 @@ export function ThreeDChart({elevation: elevationProp = 25,interactive = false,autoRotate = 0,+ label,children,}: ThreeDChartProps) {const containerRef = useRef<HTMLDivElement>(null);const [containerWidth, setContainerWidth] = useState(0);+ const [hovered, setHovered] = useState(false);+ const [focused, setFocused] = useState(false);+ const prefersReducedMotion = useMediaQuery(+ '(prefers-reduced-motion: reduce)',+ );const [camera, setCamera] = useState<Camera>({azimuth: azimuthProp,elevation: elevationProp,@@ -168,9 +192,48 @@ export function ThreeDChart({dragRef.current = null;}, []);- // Auto-rotation — throttled to ~20fps to avoid overwhelming React with re-renders+ // Keyboard camera: arrow keys rotate yaw/pitch with the same clamps as+ // pointer drag (WCAG 2.1.1 — every pointer operation needs a keyboard+ // equivalent). preventDefault stops the page from scrolling while focused.+ const handleKeyDown = useCallback(+ (e: ReactKeyboardEvent<SVGSVGElement>) => {+ if (!interactive) {+ return;+ }+ let deltaAzimuth = 0;+ let deltaElevation = 0;+ switch (e.key) {+ case 'ArrowLeft':+ deltaAzimuth = -KEYBOARD_STEP_DEGREES;+ break;+ case 'ArrowRight':+ deltaAzimuth = KEYBOARD_STEP_DEGREES;+ break;+ case 'ArrowUp':+ deltaElevation = KEYBOARD_STEP_DEGREES;+ break;+ case 'ArrowDown':+ deltaElevation = -KEYBOARD_STEP_DEGREES;+ break;+ default:+ return;+ }+ e.preventDefault();+ setCamera(prev => ({+ azimuth: prev.azimuth + deltaAzimuth,+ elevation: Math.max(-89, Math.min(89, prev.elevation + deltaElevation)),+ }));+ },+ [interactive],+ );++ // Auto-rotation — throttled to ~20fps to avoid overwhelming React with+ // re-renders. Disabled under prefers-reduced-motion (WCAG 2.3.3) and+ // paused while the chart is hovered or focused (WCAG 2.2.2).+ const rotationActive =+ autoRotate !== 0 && !prefersReducedMotion && !hovered && !focused;useEffect(() => {- if (autoRotate === 0) {+ if (!rotationActive) {return;}let raf: number;@@ -187,7 +250,7 @@ export function ThreeDChart({};raf = requestAnimationFrame(tick);return () => cancelAnimationFrame(raf);- }, [autoRotate]);+ }, [autoRotate, rotationActive]);const ctx = useMemo(() => ({@@ -226,16 +289,31 @@ export function ThreeDChart({userSelect: interactive ? 'none' : undefined,};+ const accessibleLabel = label ?? `3D chart of ${yKey} by ${xKey} and ${zKey}`;+ // Focusable when there is something keyboard users can do with it:+ // rotate the camera (interactive) or pause the auto-rotation.+ const focusable = interactive || autoRotate !== 0;+return (<div ref={containerRef} style={containerStyle}>{containerWidth > 0 && (<svg+ role="img"+ aria-label={accessibleLabel}+ tabIndex={focusable ? 0 : undefined}width={containerWidth}height={height}+ onKeyDown={handleKeyDown}+ onFocus={() => setFocused(true)}+ onBlur={() => setFocused(false)}+ onMouseEnter={() => setHovered(true)}onMouseDown={e => handleStart(e.clientX, e.clientY)}onMouseMove={e => handleMove(e.clientX, e.clientY)}onMouseUp={handleEnd}- onMouseLeave={handleEnd}+ onMouseLeave={() => {+ setHovered(false);+ handleEnd();+ }}onTouchStart={e => {const t = e.touches[0];if (t) {