Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(core): Slider draws the focus ring for keyboard focus only (#5463)

Cindy Zhang1f8525ff721f
diff --git a/.changeset/slider-keyboard-only-focus-ring.md b/.changeset/slider-keyboard-only-focus-ring.md
new file mode 100644
index 0000000000..998007b536
--- /dev/null
+++ b/.changeset/slider-keyboard-only-focus-ring.md
@@ -0,0 +1,22 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Slider: dragging the thumb with a mouse no longer draws the keyboard focus ring
+
+The thumb is a `div[role="slider"]`, and the track's `pointerdown` handler
+calls `preventDefault()` and then focuses the thumb from script. Chromium
+treats that script focus as focus-visible, so `:focus-visible` matched on
+mouse-down and every drag came with a 2px accent ring — measured in Chromium,
+not inferred.
+
+`:focus-visible` stays the CSS condition; it is now narrowed by the existing
+`interactionModality` utility, the same way PanelSearchInput and Selector
+narrow theirs. Keyboard focus rings exactly as before, and a mouse grab of a
+thumb that already had the ring drops it.
+
+One deliberate difference from the text-input cases: a keypress after a mouse
+drag brings the ring back. A text field has a caret to show where input is
+going, and a slider thumb has nothing else.
+
+@cixzhang
diff --git a/packages/core/src/Slider/Slider.test.tsx b/packages/core/src/Slider/Slider.test.tsx
index 02b3ae4d47..5436247d9c 100644
--- a/packages/core/src/Slider/Slider.test.tsx
+++ b/packages/core/src/Slider/Slider.test.tsx
@@ -13,7 +13,10 @@ import {useState} from 'react';
import {describe, it, expect, vi, beforeEach} from 'vitest';
import {render, screen, act, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import * as stylex from '@stylexjs/stylex';
import {Slider} from './Slider';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {__resetInteractionModalityForTest} from '../utils/interactionModality';
// Mock showPopover/hidePopover (not implemented in jsdom) so the tooltip layer
// reflects its open state via a `popover-open` attribute the tests can assert.
@@ -854,7 +857,7 @@ describe('Slider', () => {
/>,
);
const thumb = screen.getByRole('slider');
- thumb.focus();
+ act(() => thumb.focus());
await user.keyboard('{ArrowRight}');
expect(onChange).not.toHaveBeenCalled();
});
@@ -902,4 +905,106 @@ describe('Slider', () => {
]).toEqual([]);
});
});
+
+ describe('focus ring modality', () => {
+ beforeEach(() => {
+ __resetInteractionModalityForTest();
+ });
+
+ // The ring is a stylex class, so derive it from the same source the
+ // component applies rather than hardcoding a hash.
+ const RING = stylex
+ .props(focusOutlineStyles.focusVisible)
+ .className!.split(' ');
+ const isRinged = (el: HTMLElement) =>
+ RING.every(c => el.classList.contains(c));
+
+ // The track has no layout in jsdom; pointer maths needs a real rect.
+ const grabTrack = (thumb: HTMLElement) => {
+ const track = thumb.parentElement!;
+ track.getBoundingClientRect = () => ({
+ left: 0,
+ top: 0,
+ right: 200,
+ bottom: 20,
+ width: 200,
+ height: 20,
+ x: 0,
+ y: 0,
+ toJSON: () => {},
+ });
+ fireEvent.pointerDown(track, {clientX: 100, clientY: 10, pointerId: 1});
+ };
+
+ it('rings when the thumb is reached with the keyboard', async () => {
+ const user = userEvent.setup();
+ render(<Slider label="Volume" value={50} onChange={vi.fn()} />);
+ await user.tab();
+ expect(isRinged(screen.getByRole('slider'))).toBe(true);
+ });
+
+ it('does not ring when the thumb is grabbed with the mouse', () => {
+ render(<Slider label="Volume" value={50} onChange={vi.fn()} />);
+ const thumb = screen.getByRole('slider');
+ grabTrack(thumb);
+ expect(thumb).toHaveFocus();
+ expect(isRinged(thumb)).toBe(false);
+ });
+
+ it('drops the ring when the mouse grabs a thumb that already had it', async () => {
+ const user = userEvent.setup();
+ render(<Slider label="Volume" value={50} onChange={vi.fn()} />);
+ await user.tab();
+ const thumb = screen.getByRole('slider');
+ expect(isRinged(thumb)).toBe(true);
+ // Already focused, so focus() fires no focus event.
+ grabTrack(thumb);
+ expect(isRinged(thumb)).toBe(false);
+ });
+
+ it('brings the ring back when an arrow key follows a mouse drag', () => {
+ render(<Slider label="Volume" value={50} onChange={vi.fn()} />);
+ const thumb = screen.getByRole('slider');
+ grabTrack(thumb);
+ expect(isRinged(thumb)).toBe(false);
+ fireEvent.keyDown(thumb, {key: 'ArrowRight'});
+ expect(isRinged(thumb)).toBe(true);
+ });
+
+ it('leaves the ring off for a modifier chord after a mouse drag', () => {
+ render(<Slider label="Volume" value={50} onChange={vi.fn()} />);
+ const thumb = screen.getByRole('slider');
+ grabTrack(thumb);
+ // Copying or reloading is not navigation, and the mouse is still on it.
+ fireEvent.keyDown(thumb, {key: 'c', metaKey: true});
+ expect(isRinged(thumb)).toBe(false);
+ });
+
+ it('drops the ring on blur', async () => {
+ const user = userEvent.setup();
+ render(<Slider label="Volume" value={50} onChange={vi.fn()} />);
+ await user.tab();
+ const thumb = screen.getByRole('slider');
+ expect(isRinged(thumb)).toBe(true);
+ act(() => thumb.blur());
+ expect(isRinged(thumb)).toBe(false);
+ });
+
+ it('rings the range thumb the keyboard reached, not its sibling', async () => {
+ const user = userEvent.setup();
+ render(
+ <Slider
+ label="Price"
+ value={[20, 80] as [number, number]}
+ onChange={vi.fn()}
+ />,
+ );
+ await user.tab();
+ await user.tab();
+ const thumbs = screen.getAllByRole('slider');
+ expect(thumbs[1]).toHaveFocus();
+ expect(isRinged(thumbs[1])).toBe(true);
+ expect(isRinged(thumbs[0])).toBe(false);
+ });
+ });
});
diff --git a/packages/core/src/Slider/Slider.tsx b/packages/core/src/Slider/Slider.tsx
index 715ea846bd..9f274dd91a 100644
--- a/packages/core/src/Slider/Slider.tsx
+++ b/packages/core/src/Slider/Slider.tsx
@@ -17,11 +17,13 @@
*/
import {
+ useEffect,
useId,
useMemo,
useRef,
useState,
useCallback,
+ type FocusEvent,
type KeyboardEvent,
type PointerEvent,
} from 'react';
@@ -42,6 +44,10 @@ import {VisuallyHidden} from '../VisuallyHidden';
import type {InputStatus} from '../Field/types';
import {mergeProps, rtlStyles} from '../utils';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {
+ getInteractionModality,
+ trackInteractionModality,
+} from '../utils/interactionModality';
import {isRtlElement} from '../hooks/isRtlElement';
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
@@ -493,6 +499,36 @@ export function Slider({ref, ...props}: SliderProps) {
const draggingThumbRef = useRef<number | null>(null);
const [draggingThumb, setDraggingThumb] = useState<number | null>(null);
+ // A thumb is a div[role="slider"], and `handlePointerDown` focuses it from
+ // script after preventDefault — which Chromium treats as focus-visible, so
+ // dragging with a mouse drew the keyboard ring (measured: `:focus-visible`
+ // true on pointerdown). Gate the ring on how the user last interacted; the
+ // CSS condition stays `:focus-visible`, this only narrows it.
+ const [keyboardFocusThumb, setKeyboardFocusThumb] = useState<number | null>(
+ null,
+ );
+
+ useEffect(() => {
+ trackInteractionModality();
+ }, []);
+
+ const handleThumbFocus = useCallback(
+ (thumbIndex: number, _e: FocusEvent<HTMLDivElement>) => {
+ // A disabled thumb draws no ring even when it stays focusable for its
+ // reason tooltip, so there is nothing to track for one.
+ setKeyboardFocusThumb(
+ !isDisabled && getInteractionModality() === 'keyboard'
+ ? thumbIndex
+ : null,
+ );
+ },
+ [isDisabled],
+ );
+
+ const handleThumbBlur = useCallback((_e: FocusEvent<HTMLDivElement>) => {
+ setKeyboardFocusThumb(null);
+ }, []);
+
// Disabled-reason tooltip. This is a *separate* useTooltip instance from the
// per-thumb value bubble (the `<Tooltip>` component below): it anchors to the
// track container and fires on hover/focus of the whole control. Disabled
@@ -679,6 +715,10 @@ export function Slider({ref, ...props}: SliderProps) {
const thumbs = track.querySelectorAll<HTMLElement>('[role="slider"]');
thumbs[thumbIndex]?.focus();
}
+ // Also clear it explicitly: focusing an already-focused thumb fires no
+ // focus event, so a thumb the user had tabbed to would keep its ring
+ // through the drag.
+ setKeyboardFocusThumb(null);
if (
typeof (e.currentTarget as HTMLElement).setPointerCapture === 'function'
@@ -717,6 +757,13 @@ export function Slider({ref, ...props}: SliderProps) {
if (isDisabled) {
return;
}
+ // Unlike a text field, a thumb has no caret to show where input is
+ // going, so a keypress after a mouse drag must bring the ring back.
+ // Ask the utility rather than assuming: a modifier chord (⌘R, ⌃C) is
+ // not navigation and must not re-ring a thumb the mouse is holding.
+ if (getInteractionModality() === 'keyboard') {
+ setKeyboardFocusThumb(thumbIndex);
+ }
const currentVal = values[thumbIndex];
let newVal: number;
@@ -843,6 +890,8 @@ export function Slider({ref, ...props}: SliderProps) {
aria-labelledby={!isRange ? labelID : undefined}
aria-describedby={ariaDescribedBy}
onKeyDown={e => handleKeyDown(thumbIndex, e)}
+ onFocus={e => handleThumbFocus(thumbIndex, e)}
+ onBlur={handleThumbBlur}
{...mergeProps(
themeProps('slider-thumb', {
orientation,
@@ -854,7 +903,9 @@ export function Slider({ref, ...props}: SliderProps) {
? styles.thumbHorizontal
: rtlStyles.centerInline('50%'),
!isDisabled && styles.thumbHover,
- !isDisabled && focusOutlineStyles.focusVisible,
+ !isDisabled &&
+ keyboardFocusThumb === thumbIndex &&
+ focusOutlineStyles.focusVisible,
isDisabled && styles.thumbDisabled,
),
undefined,