An open source design system that's fully customizable and agent ready
TypeScript
fix(Slider): hardening — style clobber, a11y, pointer handling (#882)
Joeydae44d1b7abc
diff --git a/packages/core/src/Slider/XDSSlider.test.tsx b/packages/core/src/Slider/XDSSlider.test.tsxindex eb27920513..75fe2b3572 100644--- a/packages/core/src/Slider/XDSSlider.test.tsx+++ b/packages/core/src/Slider/XDSSlider.test.tsx@@ -8,36 +8,32 @@*/import {describe, it, expect, vi} from 'vitest';-import {render, screen, act} from '@testing-library/react';+import {render, screen, act, fireEvent} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {XDSSlider} from './XDSSlider';describe('XDSSlider', () => {- it('renders with label', () => {- render(<XDSSlider label="Volume" value={50} />);- expect(screen.getByText('Volume')).toBeInTheDocument();- });+ // --- Aria labels ---- it('single value mode renders one slider thumb', () => {+ it('single thumb uses label as aria-label', () => {render(<XDSSlider label="Volume" value={50} />);- const sliders = screen.getAllByRole('slider');- expect(sliders).toHaveLength(1);+ const slider = screen.getByRole('slider');+ expect(slider).toHaveAttribute('aria-label', 'Volume');});- it('range mode renders two slider thumbs', () => {+ it('range thumbs have correct aria-labels', () => {render(<XDSSlider label="Price range" value={[20, 80] as [number, number]} />,);const sliders = screen.getAllByRole('slider');- expect(sliders).toHaveLength(2);- });-- it('sets aria-valuemin, aria-valuemax, aria-valuenow', () => {- render(<XDSSlider label="Volume" value={50} min={0} max={100} />);- const slider = screen.getByRole('slider');- expect(slider).toHaveAttribute('aria-valuemin', '0');- expect(slider).toHaveAttribute('aria-valuemax', '100');- expect(slider).toHaveAttribute('aria-valuenow', '50');+ expect(sliders[0]).toHaveAttribute(+ 'aria-label',+ 'Price range, minimum value',+ );+ expect(sliders[1]).toHaveAttribute(+ 'aria-label',+ 'Price range, maximum value',+ );});it('sets aria-valuetext with formatValue', () => {@@ -48,88 +44,130 @@ describe('XDSSlider', () => {expect(slider).toHaveAttribute('aria-valuetext', '72°F');});- it('does not set aria-valuetext without formatValue', () => {- render(<XDSSlider label="Volume" value={50} />);+ it('uses custom min and max', () => {+ render(<XDSSlider label="Temperature" value={72} min={60} max={90} />);const slider = screen.getByRole('slider');- expect(slider).not.toHaveAttribute('aria-valuetext');+ expect(slider).toHaveAttribute('aria-valuemin', '60');+ expect(slider).toHaveAttribute('aria-valuemax', '90');+ expect(slider).toHaveAttribute('aria-valuenow', '72');});- it('disables thumbs when isDisabled is true', () => {- render(<XDSSlider label="Volume" value={50} isDisabled />);+ it('range mode sets correct aria values on both thumbs', () => {+ render(+ <XDSSlider+ label="Range"+ value={[25, 75] as [number, number]}+ min={0}+ max={100}+ />,+ );+ const sliders = screen.getAllByRole('slider');+ expect(sliders[0]).toHaveAttribute('aria-valuenow', '25');+ expect(sliders[1]).toHaveAttribute('aria-valuenow', '75');+ });++ it('sets aria-orientation for vertical', () => {+ render(<XDSSlider label="Volume" value={50} orientation="vertical" />);const slider = screen.getByRole('slider');- expect(slider).toHaveAttribute('aria-disabled', 'true');- expect(slider).toHaveAttribute('tabIndex', '-1');+ expect(slider).toHaveAttribute('aria-orientation', 'vertical');});- it('arrow right increases value by step', async () => {- const user = userEvent.setup();- const handleChange = vi.fn();+ it('sets aria-invalid when status type is error', () => {render(- <XDSSlider label="Volume" value={50} step={5} onChange={handleChange} />,+ <XDSSlider+ label="Volume"+ value={50}+ status={{type: 'error', message: 'Value too high'}}+ />,);const slider = screen.getByRole('slider');- act(() => {- slider.focus();- });- await user.keyboard('{ArrowRight}');- expect(handleChange).toHaveBeenCalledWith(55);+ expect(slider).toHaveAttribute('aria-invalid', 'true');});- it('arrow left decreases value by step', async () => {- const user = userEvent.setup();- const handleChange = vi.fn();+ it('associates description via aria-describedby', () => {render(- <XDSSlider label="Volume" value={50} step={5} onChange={handleChange} />,+ <XDSSlider+ label="Volume"+ value={50}+ description="Adjust the volume level"+ />,);const slider = screen.getByRole('slider');- act(() => {- slider.focus();- });- await user.keyboard('{ArrowLeft}');- expect(handleChange).toHaveBeenCalledWith(45);+ const describedby = slider.getAttribute('aria-describedby');+ expect(describedby).toBeTruthy();+ const descEl = document.getElementById(describedby!.split(' ')[0]);+ expect(descEl).toHaveTextContent('Adjust the volume level');});- it('Home key sets value to min', async () => {- const user = userEvent.setup();- const handleChange = vi.fn();+ it('associates status message via aria-describedby', () => {render(<XDSSliderlabel="Volume"value={50}- min={10}- max={100}- onChange={handleChange}+ description="Adjust the volume level"+ status={{type: 'error', message: 'Too loud'}}/>,);const slider = screen.getByRole('slider');- act(() => {- slider.focus();- });- await user.keyboard('{Home}');- expect(handleChange).toHaveBeenCalledWith(10);+ const describedby = slider.getAttribute('aria-describedby');+ expect(describedby).toBeTruthy();+ // Should have at least two IDs (description + status message)+ const ids = describedby!.split(' ');+ expect(ids.length).toBeGreaterThanOrEqual(2);});- it('End key sets value to max', async () => {- const user = userEvent.setup();+ it('decorative track elements have aria-hidden', () => {+ const {container} = render(<XDSSlider label="Volume" value={50} />);+ const ariaHidden = container.querySelectorAll('[aria-hidden="true"]');+ expect(ariaHidden.length).toBeGreaterThanOrEqual(2);+ });++ // --- Disabled guards ---++ it('disables thumbs when isDisabled is true', () => {+ render(<XDSSlider label="Volume" value={50} isDisabled />);+ const slider = screen.getByRole('slider');+ expect(slider).toHaveAttribute('aria-disabled', 'true');+ expect(slider).toHaveAttribute('tabIndex', '-1');+ });++ it('does not fire onChange on pointer down when disabled', () => {const handleChange = vi.fn();render(<XDSSliderlabel="Volume"value={50}min={0}- max={90}+ max={100}onChange={handleChange}+ isDisabled/>,);const slider = screen.getByRole('slider');- act(() => {- slider.focus();+ const trackContainer = slider.parentElement!;++ trackContainer.getBoundingClientRect = () => ({+ left: 0,+ top: 0,+ right: 200,+ bottom: 20,+ width: 200,+ height: 20,+ x: 0,+ y: 0,+ toJSON: () => {},+ });++ fireEvent.pointerDown(trackContainer, {+ clientX: 100,+ clientY: 10,+ pointerId: 1,});- await user.keyboard('{End}');- expect(handleChange).toHaveBeenCalledWith(90);++ expect(handleChange).not.toHaveBeenCalled();});- it('does not change value on keyboard when disabled', () => {+ it('does not fire onChange on keyboard when disabled', () => {const handleChange = vi.fn();render(<XDSSlider@@ -140,113 +178,219 @@ describe('XDSSlider', () => {/>,);const slider = screen.getByRole('slider');- // Disabled slider has tabIndex=-1, so it won't receive keyboard events- // via normal tabbing. We verify the aria-disabled attribute instead.- expect(slider).toHaveAttribute('aria-disabled', 'true');- expect(slider).toHaveAttribute('tabIndex', '-1');+ fireEvent.keyDown(slider, {key: 'ArrowRight'});+ expect(handleChange).not.toHaveBeenCalled();});- it('renders marks', () => {+ // --- onChangeEnd on keyboard ---++ it('fires onChangeEnd on keyboard ArrowRight', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ const handleChangeEnd = vi.fn();render(<XDSSliderlabel="Volume"value={50}- marks={[{value: 0}, {value: 50}, {value: 100}]}+ step={5}+ onChange={handleChange}+ onChangeEnd={handleChangeEnd}/>,);- const marks = screen.getAllByTestId('slider-mark');- expect(marks).toHaveLength(3);+ const slider = screen.getByRole('slider');+ act(() => {+ slider.focus();+ });+ await user.keyboard('{ArrowRight}');+ expect(handleChange).toHaveBeenCalledWith(55);+ expect(handleChangeEnd).toHaveBeenCalledWith(55);});- it('renders mark labels', () => {+ it('fires onChangeEnd on keyboard Home/End with correct value', async () => {+ const user = userEvent.setup();+ const handleChangeEnd = vi.fn();render(<XDSSliderlabel="Volume"value={50}- marks={[- {value: 0, label: 'Low'},- {value: 100, label: 'High'},- ]}+ min={0}+ max={100}+ onChange={vi.fn()}+ onChangeEnd={handleChangeEnd}/>,);- expect(screen.getByText('Low')).toBeInTheDocument();- expect(screen.getByText('High')).toBeInTheDocument();+ const slider = screen.getByRole('slider');+ act(() => {+ slider.focus();+ });+ await user.keyboard('{Home}');+ expect(handleChangeEnd).toHaveBeenCalledWith(0);});- it('renders status messages', () => {+ it('fires onChangeEnd with correct value for range mode on keyboard', async () => {+ const user = userEvent.setup();+ const handleChangeEnd = vi.fn();render(<XDSSlider- label="Volume"- value={50}- status={{type: 'error', message: 'Value too high'}}+ label="Range"+ value={[20, 80] as [number, number]}+ min={0}+ max={100}+ step={5}+ onChange={vi.fn()}+ onChangeEnd={handleChangeEnd}/>,);- expect(screen.getByText('Value too high')).toBeInTheDocument();+ const sliders = screen.getAllByRole('slider');+ act(() => {+ sliders[0].focus();+ });+ await user.keyboard('{ArrowRight}');+ expect(handleChangeEnd).toHaveBeenCalledWith([25, 80]);});- it('sets aria-invalid when status type is error', () => {+ // --- Pointer handling ---++ it('fires onChangeEnd on pointer up after pointer down', () => {+ const handleChange = vi.fn();+ const handleChangeEnd = vi.fn();render(<XDSSliderlabel="Volume"value={50}- status={{type: 'error', message: 'Value too high'}}+ min={0}+ max={100}+ onChange={handleChange}+ onChangeEnd={handleChangeEnd}/>,);const slider = screen.getByRole('slider');- expect(slider).toHaveAttribute('aria-invalid', 'true');- });+ const trackContainer = slider.parentElement!;- it('applies data-testid', () => {- render(<XDSSlider label="Volume" value={50} data-testid="volume-slider" />);- expect(screen.getByTestId('volume-slider')).toBeInTheDocument();- });+ trackContainer.getBoundingClientRect = () => ({+ left: 0,+ top: 0,+ right: 200,+ bottom: 20,+ width: 200,+ height: 20,+ x: 0,+ y: 0,+ toJSON: () => {},+ });- it('sets aria-orientation for vertical', () => {- render(<XDSSlider label="Volume" value={50} orientation="vertical" />);- const slider = screen.getByRole('slider');- expect(slider).toHaveAttribute('aria-orientation', 'vertical');+ fireEvent.pointerDown(trackContainer, {+ clientX: 100,+ clientY: 10,+ pointerId: 1,+ });+ fireEvent.pointerUp(trackContainer, {+ clientX: 100,+ clientY: 10,+ pointerId: 1,+ });++ expect(handleChangeEnd).toHaveBeenCalledTimes(1);});- it('sets aria-orientation for horizontal', () => {- render(<XDSSlider label="Volume" value={50} />);+ it('focuses closest thumb on track click', () => {+ render(+ <XDSSlider+ label="Volume"+ value={50}+ min={0}+ max={100}+ onChange={vi.fn()}+ />,+ );const slider = screen.getByRole('slider');- expect(slider).toHaveAttribute('aria-orientation', 'horizontal');+ const trackContainer = slider.parentElement!;++ trackContainer.getBoundingClientRect = () => ({+ left: 0,+ top: 0,+ right: 200,+ bottom: 20,+ width: 200,+ height: 20,+ x: 0,+ y: 0,+ toJSON: () => {},+ });++ fireEvent.pointerDown(trackContainer, {+ clientX: 100,+ clientY: 10,+ pointerId: 1,+ });++ expect(document.activeElement).toBe(slider);});- it('range thumbs have correct aria-labels', () => {+ // --- Mark label click snapping ---++ it('clicking a mark label snaps to that mark value, not pointer position', () => {+ const handleChange = vi.fn();render(- <XDSSlider label="Price range" value={[20, 80] as [number, number]} />,+ <XDSSlider+ label="Volume"+ value={50}+ min={0}+ max={100}+ onChange={handleChange}+ marks={[{value: 100, label: '100'}]}+ />,);- const sliders = screen.getAllByRole('slider');- expect(sliders[0]).toHaveAttribute('aria-label', 'Minimum value');- expect(sliders[1]).toHaveAttribute('aria-label', 'Maximum value');- });+ const markLabel = screen.getByTestId('slider-mark-label');- it('single thumb uses label as aria-label', () => {- render(<XDSSlider label="Volume" value={50} />);- const slider = screen.getByRole('slider');- expect(slider).toHaveAttribute('aria-label', 'Volume');+ // Simulate a click on the left edge of the "100" label — pointer X would+ // map to ~99 if calculated from position, but should snap to 100.+ fireEvent.pointerDown(markLabel, {clientX: 1, clientY: 10, pointerId: 1});++ expect(handleChange).toHaveBeenCalledWith(100);});- it('uses custom min and max', () => {- render(<XDSSlider label="Temperature" value={72} min={60} max={90} />);+ // --- Boundary clamping ---++ it('clamps value at max boundary', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSSlider+ label="Volume"+ value={99}+ min={0}+ max={100}+ step={5}+ onChange={handleChange}+ />,+ );const slider = screen.getByRole('slider');- expect(slider).toHaveAttribute('aria-valuemin', '60');- expect(slider).toHaveAttribute('aria-valuemax', '90');- expect(slider).toHaveAttribute('aria-valuenow', '72');+ act(() => {+ slider.focus();+ });+ await user.keyboard('{ArrowRight}');+ expect(handleChange).toHaveBeenCalledWith(100);});- it('range mode sets correct aria values on both thumbs', () => {+ it('clamps value at min boundary', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();render(<XDSSlider- label="Range"- value={[25, 75] as [number, number]}+ label="Volume"+ value={1}min={0}max={100}+ step={5}+ onChange={handleChange}/>,);- const sliders = screen.getAllByRole('slider');- expect(sliders[0]).toHaveAttribute('aria-valuenow', '25');- expect(sliders[1]).toHaveAttribute('aria-valuenow', '75');+ const slider = screen.getByRole('slider');+ act(() => {+ slider.focus();+ });+ await user.keyboard('{ArrowLeft}');+ expect(handleChange).toHaveBeenCalledWith(0);});});diff --git a/packages/core/src/Slider/XDSSlider.tsx b/packages/core/src/Slider/XDSSlider.tsxindex 1107c9e973..e204dd8935 100644--- a/packages/core/src/Slider/XDSSlider.tsx+++ b/packages/core/src/Slider/XDSSlider.tsx@@ -203,7 +203,10 @@ const styles = stylex.create({backgroundColor: colorVars['--color-accent'],transform: 'translate(-50%, -50%)',transitionProperty: 'background-color, box-shadow',- transitionDuration: durationVars['--duration-fast'],+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },transitionTimingFunction: easeVars['--ease-standard'],outline: 'none',cursor: 'grab',@@ -224,14 +227,14 @@ const styles = stylex.create({},},},- thumbFocusWithin: {+ thumbFocusVisible: {outline: {default: 'none',- ':focus-within': `2px solid ${colorVars['--color-ring-focus']}`,+ ':focus-visible': `2px solid ${colorVars['--color-ring-focus']}`,},outlineOffset: {default: '0',- ':focus-within': '2px',+ ':focus-visible': '2px',},},thumbDisabled: {@@ -299,6 +302,7 @@ function clamp(val: number, min: number, max: number): number {}function snapToStep(val: number, min: number, step: number): number {+ if (step <= 0) return val;const steps = Math.round((val - min) / step);return min + steps * step;}@@ -374,6 +378,9 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {? (value as [number, number]): [value as number];+ const valuesRef = useRef(values);+ valuesRef.current = values;+const getValueFromPosition = useCallback((clientX: number, clientY: number): number => {const track = trackRef.current;@@ -450,25 +457,50 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {],);- const fireChangeEnd = useCallback(() => {- if (isRange) {- (onChangeEnd as XDSSliderRangeProps['onChangeEnd'])?.(- values as unknown as [number, number],- );- } else {- (onChangeEnd as XDSSliderSingleProps['onChangeEnd'])?.(values[0]);- }- }, [isRange, values, onChangeEnd]);+ const onChangeEndRef = useRef(onChangeEnd);+ onChangeEndRef.current = onChangeEnd;++ const fireChangeEnd = useCallback(+ (newValues?: number[]) => {+ const currentValues = newValues ?? valuesRef.current;+ const cb = onChangeEndRef.current;+ if (isRange) {+ (cb as XDSSliderRangeProps['onChangeEnd'])?.(+ currentValues as unknown as [number, number],+ );+ } else {+ (cb as XDSSliderSingleProps['onChangeEnd'])?.(currentValues[0]);+ }+ },+ [isRange],+ );// Pointer handlersconst handlePointerDown = useCallback((e: PointerEvent<HTMLDivElement>) => {if (isDisabled) return;e.preventDefault();- const newVal = getValueFromPosition(e.clientX, e.clientY);++ // If the click originated from a mark element, snap to that mark's value+ // instead of calculating from pointer position (avoids off-by-one when+ // clicking on wide labels like "100").+ const markEl = (e.target as HTMLElement).closest<HTMLElement>(+ '[data-mark-value]',+ );+ const newVal = markEl+ ? Number(markEl.dataset.markValue)+ : getValueFromPosition(e.clientX, e.clientY);const thumbIndex = getClosestThumb(newVal);draggingThumbRef.current = thumbIndex;updateValue(thumbIndex, newVal);++ // Focus the closest thumb+ const track = trackRef.current;+ if (track) {+ const thumbs = track.querySelectorAll<HTMLElement>('[role="slider"]');+ thumbs[thumbIndex]?.focus();+ }+if (typeof (e.currentTarget as HTMLElement).setPointerCapture === 'function') {@@ -530,9 +562,38 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {}e.preventDefault();+ const clamped = clamp(snapToStep(newVal, min, step), min, max);updateValue(thumbIndex, newVal);++ // Compute exact post-update values so onChangeEnd reports the correct+ // value even before React batches the state update.+ if (isRange) {+ const newValues = [...values] as [number, number];+ newValues[thumbIndex] = clamped;+ const minGap = minStepsBetweenThumbs * step;+ if (thumbIndex === 0) {+ newValues[0] = Math.min(newValues[0], newValues[1] - minGap);+ } else {+ newValues[1] = Math.max(newValues[1], newValues[0] + minGap);+ }+ newValues[0] = clamp(newValues[0], min, max);+ newValues[1] = clamp(newValues[1], min, max);+ fireChangeEnd(newValues);+ } else {+ fireChangeEnd([clamped]);+ }},- [isDisabled, values, step, min, max, updateValue],+ [+ isDisabled,+ isRange,+ values,+ step,+ min,+ max,+ minStepsBetweenThumbs,+ updateValue,+ fireChangeEnd,+ ],);// Format display value@@ -552,8 +613,8 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {const thumbLabel = isRange? thumbIndex === 0- ? 'Minimum value'- : 'Maximum value'+ ? `${label}, minimum value`+ : `${label}, maximum value`: label;const useTooltip = valueDisplay === 'tooltip';@@ -562,6 +623,7 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {const thumbElement = (<divkey={thumbIndex}+ id={!isRange ? id : undefined}role="slider"tabIndex={isDisabled ? -1 : 0}aria-valuemin={min}@@ -573,7 +635,6 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {aria-invalid={status?.type === 'error' ? true : undefined}aria-label={thumbLabel}aria-describedby={ariaDescribedBy}- style={positionStyle}onKeyDown={e => handleKeyDown(thumbIndex, e)}{...mergeProps(xdsClassName('slider-thumb', {@@ -584,9 +645,11 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {styles.thumb,isHorizontal ? styles.thumbHorizontal : styles.thumbVertical,!isDisabled && styles.thumbHover,- !isDisabled && styles.thumbFocusWithin,+ !isDisabled && styles.thumbFocusVisible,isDisabled && styles.thumbDisabled,),+ undefined,+ positionStyle,)}/>);@@ -680,9 +743,11 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {node;}}}+ {...(isRange ? {role: 'group', 'aria-label': label} : undefined)}onPointerDown={handlePointerDown}onPointerMove={handlePointerMove}onPointerUp={handlePointerUp}+ onPointerCancel={handlePointerUp}{...stylex.props(styles.trackContainer,isHorizontal@@ -692,6 +757,7 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {)}>{/* Background track */}<div+ aria-hidden="true"{...mergeProps(xdsClassName('slider-track', {orientation}),stylex.props(@@ -703,18 +769,20 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {{/* Filled track */}<div- style={filledStyle}+ aria-hidden="true"{...stylex.props(styles.filledTrack,isHorizontal? styles.filledTrackHorizontal: styles.filledTrackVertical,)}+ style={filledStyle}/>{/* Marks */}{marks && (<div+ aria-hidden="true"{...stylex.props(styles.marksContainer,isHorizontal@@ -730,24 +798,26 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {<div key={mark.value}><divdata-testid="slider-mark"- style={markPos}+ data-mark-value={mark.value}{...stylex.props(styles.mark,isHorizontal? styles.markHorizontal: styles.markVertical,)}+ style={markPos}/>{mark.label && (<spandata-testid="slider-mark-label"- style={markPos}+ data-mark-value={mark.value}{...stylex.props(styles.markLabel,isHorizontal? styles.markLabelHorizontal: styles.markLabelVertical,- )}>+ )}+ style={markPos}>{mark.label}</span>)}