Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions apps/docs/content/1.component/elastic-slider.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,10 @@ value. That means:
bigger jump, and Home and End go to `min` and `max`.
- **Screen readers.** They read the label and the formatted value from
`aria-valuetext`, e.g. "Monthly budget, slider, $7,500".
- **Focus.** Keyboard focus draws a ring around the ruler. Pressing the ruler
focuses the input too, so the keys work straight after a drag.
- **Focus.** The ring around the ruler only shows for keyboard focus. Pressing
or dragging with the mouse focuses the input without the ring, so the keys
still work straight after a drag, and the ring comes back on the first key
press.

The minus and plus are real buttons labelled "Decrease Monthly budget by
$100" and "Increase Monthly budget by $100".
2 changes: 1 addition & 1 deletion apps/docs/public/r/elastic-slider.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions apps/docs/registry/__sources__.generated.ts

Large diffs are not rendered by default.

27 changes: 25 additions & 2 deletions apps/docs/registry/tweenui/elastic-slider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ const LIFT = { idle: 0.6, hover: 1.1, drag: 1.7 };
const STEP_BUTTON =
'grid size-9 cursor-pointer place-items-center transition-colors duration-200 hover:bg-current/10 focus-visible:bg-current/10 focus-visible:outline-none disabled:cursor-not-allowed disabled:hover:bg-transparent';

const matchesFocusVisible = (element: HTMLElement) => {
try {
return element.matches(':focus-visible');
} catch {
return true;
}
};

const clamp = (value: number, low: number, high: number) => Math.min(high, Math.max(low, value));

export const rubberBand = (overdrag: number) =>
Expand Down Expand Up @@ -101,6 +109,8 @@ const ElasticSlider = ({

const [innerValue, setInnerValue] = useState(defaultValue);
const [dragging, setDragging] = useState(false);
const [keyboardFocus, setKeyboardFocus] = useState(false);
const pointerFocus = useRef(false);
const [reduced, setReduced] = useState(false);

const value = clamp(controlledValue ?? innerValue, min, max);
Expand Down Expand Up @@ -249,7 +259,10 @@ const ElasticSlider = ({
if (disabled || (event.pointerType === 'mouse' && event.button !== 0)) return;
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
setKeyboardFocus(false);
pointerFocus.current = true;
inputRef.current?.focus({ preventScroll: true });
pointerFocus.current = false;
setDragging(true);
setLift('drag');
track(event.clientX);
Expand Down Expand Up @@ -363,11 +376,21 @@ const ElasticSlider = ({
disabled={disabled}
aria-valuetext={formatText(value)}
onChange={(event) => commit(Number(event.target.value))}
className="peer sr-only"
onFocus={(event) =>
setKeyboardFocus(!pointerFocus.current && matchesFocusVisible(event.currentTarget))
}
onKeyDown={() => setKeyboardFocus(true)}
onBlur={() => setKeyboardFocus(false)}
className="sr-only"
/>
<div
aria-hidden="true"
className="pointer-events-none absolute -inset-x-3 -inset-y-1 rounded-xl outline-2 outline-transparent peer-focus-visible:outline-current"
data-elastic-focus-ring
data-visible={keyboardFocus || undefined}
className={cn(
'pointer-events-none absolute -inset-x-3 -inset-y-1 rounded-xl outline-2 outline-transparent',
keyboardFocus && 'outline-current'
)}
/>
<div ref={railRef} aria-hidden="true" className="absolute inset-0">
{Array.from({ length: ticks }, (_, index) => (
Expand Down
74 changes: 58 additions & 16 deletions apps/docs/tests/elastic-slider.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { act, fireEvent, render, screen } from '@testing-library/react';
import gsap from 'gsap';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import ElasticSlider, { MAX_STRETCH, rubberBand } from '@/registry/tweenui/elastic-slider';

vi.mock('@number-flow/react', () => ({
Expand Down Expand Up @@ -45,6 +45,24 @@ const Budget = (props: { onValueChange?: (value: number) => void; defaultValue?:
/>
);

beforeAll(() => {
if (!('PointerEvent' in window)) {
class PointerEventPolyfill extends MouseEvent {
pointerId: number;
pointerType: string;
constructor(type: string, init: PointerEventInit = {}) {
super(type, init);
this.pointerId = init.pointerId ?? 1;
this.pointerType = init.pointerType ?? 'mouse';
}
}
Object.defineProperty(window, 'PointerEvent', {
value: PointerEventPolyfill,
configurable: true,
});
}
});

const lastTickX = (container: HTMLElement) => {
const ticks = container.querySelectorAll('[data-elastic-tick]');
const last = ticks[ticks.length - 1];
Expand Down Expand Up @@ -108,27 +126,51 @@ describe('Elastic Slider', () => {
expect(screen.getByRole('slider')).toHaveValue('7600');
});

describe('focus ring', () => {
const ring = (container: HTMLElement) => container.querySelector('[data-elastic-focus-ring]');

beforeEach(() => {
Element.prototype.setPointerCapture = vi.fn();
});

it('shows when the slider is focused from the keyboard', () => {
const { container } = render(<Budget />);
act(() => screen.getByRole('slider').focus());
expect(ring(container)).toHaveAttribute('data-visible');
});

it('stays hidden when the ruler is pressed with the mouse', () => {
const { container } = render(<Budget />);
const track = container.querySelector('[data-elastic-track]');
if (!track) throw new Error('track not found');
fireEvent.pointerDown(track, { clientX: 0, pointerId: 1, button: 0, pointerType: 'mouse' });
expect(screen.getByRole('slider')).toHaveFocus();
expect(ring(container)).not.toHaveAttribute('data-visible');
});

it('comes back once a key is pressed after a drag', () => {
const { container } = render(<Budget />);
const track = container.querySelector('[data-elastic-track]');
if (!track) throw new Error('track not found');
fireEvent.pointerDown(track, { clientX: 0, pointerId: 1, button: 0, pointerType: 'mouse' });
fireEvent.keyDown(screen.getByRole('slider'), { key: 'ArrowRight' });
expect(ring(container)).toHaveAttribute('data-visible');
});

it('hides again on blur', () => {
const { container } = render(<Budget />);
act(() => screen.getByRole('slider').focus());
act(() => screen.getByRole('slider').blur());
expect(ring(container)).not.toHaveAttribute('data-visible');
});
});

describe('stretch past the ends', () => {
let now = 0;
beforeEach(() => {
gsap.ticker.remove(gsap.updateRoot);
now = gsap.ticker.time;
Element.prototype.setPointerCapture = vi.fn();
if (!('PointerEvent' in window)) {
class PointerEventPolyfill extends MouseEvent {
pointerId: number;
pointerType: string;
constructor(type: string, init: PointerEventInit = {}) {
super(type, init);
this.pointerId = init.pointerId ?? 1;
this.pointerType = init.pointerType ?? 'mouse';
}
}
Object.defineProperty(window, 'PointerEvent', {
value: PointerEventPolyfill,
configurable: true,
});
}
});
afterEach(() => {
gsap.ticker.add(gsap.updateRoot);
Expand Down
Loading