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
39 changes: 25 additions & 14 deletions apps/docs/content/1.component/elastic-slider.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,14 @@ export default function Page() {
the value when you leave, on a 500ms `power3.out` ease.
- **Indicator.** Follows the value on a 400ms `power3.out` ease, so button
presses and arrow keys glide instead of jumping.
- **Stretch.** Overdrag runs through a rubber-band curve that tops out at
28px. The ruler is pinned at the far end, so ticks near your pointer move
the most. On release it springs back on `elastic.out(1, 0.32)` over 900ms.
- **Buttons.** The icon pops on `back.out`. At the limit the ruler kicks
14px toward the button and springs back.
- **Stretch.** The stretch is how the slider tells you you've hit the
limit. Overdrag runs through a rubber-band curve that never goes past
10px, however far you pull, and each extra pixel of pull stretches it
less. The ruler is pinned at the far end, so ticks near your pointer move
the most. On release it settles back in 320ms on `power3.out`, in one
move with no wobble.
- **Buttons.** The icon pops on `back.out`. At the limit the ruler gives a
6px kick toward the button and settles back.

## Props

Expand Down Expand Up @@ -104,14 +107,22 @@ The accent comes from `--elastic-accent`. Override it with a class, e.g.
## Accessibility

::note
Under `prefers-reduced-motion: reduce` the ticks stay flat, the ruler never
stretches, the indicator jumps straight to the value and the digits change
without rolling.
Under `prefers-reduced-motion: reduce` the ruler never stretches and the
ticks stay flat. The indicator jumps straight to the value and stops at the
limit, and the digits change without rolling. The slider listens for the
setting, so switching it while the page is open takes effect right away.
::

Under the ruler sits a real `<input type="range">` with a `<label>`, so arrow
keys, Page Up and Down, Home and End, and screen readers all work natively.
`aria-valuetext` reads the formatted value, such as "$7,500". The minus and
plus are real buttons labelled "Decrease Monthly budget by $100" and
"Increase Monthly budget by $100". Pressing the ruler focuses the input, and
keyboard focus draws a ring around it.
The drawing is only a picture: under it sits a real, native
`<input type="range">` with a `<label>`, and its value is the slider's
value. That means:

- **Keyboard.** Arrow keys move one `step`, Page Up and Page Down move a
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.

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.

42 changes: 26 additions & 16 deletions apps/docs/registry/tweenui/elastic-slider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ import { cn } from '@/lib/utils';

gsap.registerPlugin(useGSAP);

const prefersReducedMotion = () =>
typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)';

const MAX_STRETCH = 28;
export const MAX_STRETCH = 10;
const EDGE_BUMP = 6;
const WAVE_WIDTH = 30;
const LIFT = { idle: 0.6, hover: 1.1, drag: 1.7 };

Expand All @@ -28,8 +28,8 @@ const STEP_BUTTON =

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

const rubberBand = (overdrag: number) =>
Math.sign(overdrag) * MAX_STRETCH * (1 - Math.exp(-Math.abs(overdrag) / (MAX_STRETCH * 2.5)));
export const rubberBand = (overdrag: number) =>
Math.sign(overdrag) * MAX_STRETCH * (1 - Math.exp(-Math.abs(overdrag) / (MAX_STRETCH * 4)));

const decimalsOf = (step: number) => {
const [, fraction = ''] = String(step).split('.');
Expand Down Expand Up @@ -134,26 +134,34 @@ const ElasticSlider = ({
});
}, []);

useEffect(() => {
if (typeof window === 'undefined' || !window.matchMedia) return;
const query = window.matchMedia(REDUCED_MOTION_QUERY);
const sync = () => setReduced(query.matches);
sync();
query.addEventListener('change', sync);
return () => query.removeEventListener('change', sync);
}, []);

useGSAP(
() => {
const isReduced = prefersReducedMotion();
setReduced(isReduced);
const width = railRef.current?.offsetWidth ?? 0;
motion.current.progress = progress;
motion.current.focus = progress * width;
motion.current.lift = isReduced ? 0 : LIFT.idle;
motion.current.stretch = 0;
motion.current.lift = reduced ? 0 : LIFT.idle;
moveTo.current = gsap.quickTo(motion.current, 'progress', {
duration: isReduced ? 0 : 0.4,
duration: reduced ? 0 : 0.4,
ease: 'power3.out',
onUpdate: render,
});
focusTo.current = gsap.quickTo(motion.current, 'focus', {
duration: isReduced ? 0 : 0.5,
duration: reduced ? 0 : 0.5,
ease: 'power3.out',
onUpdate: render,
});
liftTo.current = gsap.quickTo(motion.current, 'lift', {
duration: isReduced ? 0 : 0.45,
duration: reduced ? 0 : 0.45,
ease: 'power2.out',
onUpdate: render,
});
Expand All @@ -165,7 +173,7 @@ const ElasticSlider = ({
observer.observe(rail);
return () => observer.disconnect();
},
{ scope: rootRef, dependencies: [ticks] }
{ scope: rootRef, dependencies: [ticks, reduced] }
);

useEffect(() => {
Expand All @@ -192,8 +200,8 @@ const ElasticSlider = ({
if (reduced) return;
gsap.to(motion.current, {
stretch: amount,
duration: release ? 0.9 : 0.2,
ease: release ? 'elastic.out(1, 0.32)' : 'power3.out',
duration: release ? 0.32 : 0.18,
ease: 'power3.out',
overwrite: 'auto',
onUpdate: render,
});
Expand All @@ -202,8 +210,8 @@ const ElasticSlider = ({
const bump = (direction: number) => {
if (reduced) return;
gsap.to(motion.current, {
stretch: direction * 14,
duration: 0.14,
stretch: direction * EDGE_BUMP,
duration: 0.12,
ease: 'power2.out',
overwrite: 'auto',
onUpdate: render,
Expand Down Expand Up @@ -336,6 +344,7 @@ const ElasticSlider = ({
'relative mt-5 h-14',
disabled ? 'cursor-not-allowed' : dragging ? 'cursor-grabbing' : 'cursor-grab'
)}
data-elastic-track
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerLeave={() => !dragging && settle()}
Expand Down Expand Up @@ -364,6 +373,7 @@ const ElasticSlider = ({
{Array.from({ length: ticks }, (_, index) => (
<span
key={index}
data-elastic-tick
ref={(node) => {
tickRefs.current[index] = node;
}}
Expand Down
110 changes: 103 additions & 7 deletions apps/docs/tests/elastic-slider.test.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,37 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import ElasticSlider from '@/registry/tweenui/elastic-slider';
import { act, fireEvent, render, screen } from '@testing-library/react';
import gsap from 'gsap';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import ElasticSlider, { MAX_STRETCH, rubberBand } from '@/registry/tweenui/elastic-slider';

vi.mock('@number-flow/react', () => ({
default: ({ value }: { value: number }) => <span>{value}</span>,
}));

let reduceMotion = false;
const motionListeners = new Set<() => void>();

const setReducedMotion = (reduce: boolean) => {
reduceMotion = reduce;
window.matchMedia = vi.fn().mockImplementation((query: string) => ({
matches: query.includes('reduce') ? reduce : false,
get matches() {
return query.includes('reduce') ? reduceMotion : false;
},
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addEventListener: (_: string, listener: () => void) => motionListeners.add(listener),
removeEventListener: (_: string, listener: () => void) => motionListeners.delete(listener),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
})) as unknown as typeof window.matchMedia;
};

const switchReducedMotion = (reduce: boolean) =>
act(() => {
reduceMotion = reduce;
motionListeners.forEach((listener) => listener());
});

const Budget = (props: { onValueChange?: (value: number) => void; defaultValue?: number }) => (
<ElasticSlider
label="Monthly budget"
Expand All @@ -32,8 +45,17 @@ const Budget = (props: { onValueChange?: (value: number) => void; defaultValue?:
/>
);

const lastTickX = (container: HTMLElement) => {
const ticks = container.querySelectorAll('[data-elastic-tick]');
const last = ticks[ticks.length - 1];
return last ? Number(gsap.getProperty(last, 'x')) : NaN;
};

describe('Elastic Slider', () => {
beforeEach(() => setReducedMotion(false));
beforeEach(() => {
motionListeners.clear();
setReducedMotion(false);
});

it('renders a labelled native range input', () => {
render(<Budget />);
Expand Down Expand Up @@ -85,4 +107,78 @@ describe('Elastic Slider', () => {
fireEvent.click(screen.getByRole('button', { name: /Increase/ }));
expect(screen.getByRole('slider')).toHaveValue('7600');
});

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);
});

const wait = (ms: number) =>
act(() => {
now += ms / 1000;
gsap.updateRoot(now);
});

const pullPastEnd = (container: HTMLElement, clientX: number) => {
const track = container.querySelector('[data-elastic-track]');
if (!track) throw new Error('track not found');
fireEvent.pointerDown(track, { clientX, pointerId: 1, button: 0, pointerType: 'mouse' });
wait(1000);
};

it('stays small however far the pointer goes', () => {
expect(MAX_STRETCH).toBeGreaterThanOrEqual(8);
expect(MAX_STRETCH).toBeLessThanOrEqual(12);
[1, 40, 200, 2000, 1e6].forEach((pull) => {
expect(Math.abs(rubberBand(pull))).toBeLessThanOrEqual(MAX_STRETCH);
expect(Math.abs(rubberBand(-pull))).toBeLessThanOrEqual(MAX_STRETCH);
});
expect(rubberBand(400) - rubberBand(200)).toBeLessThan(rubberBand(200) - rubberBand(0));
});

it('stretches the ruler within the cap when dragged past max', () => {
const { container } = render(<Budget />);
pullPastEnd(container, 5000);
const stretch = lastTickX(container);
expect(stretch).toBeGreaterThan(0);
expect(stretch).toBeLessThanOrEqual(MAX_STRETCH);
expect(screen.getByRole('slider')).toHaveValue('20000');
});

it('does not stretch under reduced motion', () => {
setReducedMotion(true);
const { container } = render(<Budget />);
pullPastEnd(container, 5000);
expect(lastTickX(container)).toBe(0);
expect(screen.getByRole('slider')).toHaveValue('20000');
});

it('stops stretching as soon as reduced motion is switched on', () => {
const { container } = render(<Budget />);
switchReducedMotion(true);
pullPastEnd(container, 5000);
expect(lastTickX(container)).toBe(0);
});
});
});
Loading