Skip to content

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

TypeScript

fix(Slider): keep the thumb inside the component bounds at min and max (#5051)

Cindy Zhange07f38ff68a9
diff --git a/.changeset/slider-thumb-bounds.md b/.changeset/slider-thumb-bounds.md
new file mode 100644
index 0000000000..0e0f2a702a
--- /dev/null
+++ b/.changeset/slider-thumb-bounds.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Slider: the thumb no longer overhangs the component's own box at `min` and `max`. It was centred on the container edge at either extreme, leaving half of it (10px) outside the control, where a tight container clipped it or it overlapped the next element. Thumb travel is now inset by half a thumb at each end — the geometry a native `input[type=range]` uses — and the fill, the marks and the pointer-to-value mapping share that inset, so the thumb also stays under the pointer that grabbed it instead of jumping by up to half its width. Vertical sliders and both thumbs of a range slider are fixed the same way.
+
+@cixzhang
diff --git a/packages/core/src/Slider/Slider.test.tsx b/packages/core/src/Slider/Slider.test.tsx
index 2175e635bb..02b3ae4d47 100644
--- a/packages/core/src/Slider/Slider.test.tsx
+++ b/packages/core/src/Slider/Slider.test.tsx
@@ -81,8 +81,8 @@ describe('Slider', () => {
});
it.each([
- {value: 150, expectedValue: 100, expectedPosition: '100%'},
- {value: -50, expectedValue: 0, expectedPosition: '0%'},
+ {value: 150, expectedValue: 100, expectedPosition: 'calc(100% - 10px)'},
+ {value: -50, expectedValue: 0, expectedPosition: 'calc(0% + 10px)'},
])(
'clamps a controlled value of $value to $expectedValue',
({value, expectedValue, expectedPosition}) => {
@@ -90,11 +90,47 @@ describe('Slider', () => {
const slider = screen.getByRole('slider');
expect(slider).toHaveAttribute('aria-valuenow', String(expectedValue));
// Thumb positions via the logical `inset-inline-start` so it mirrors
- // under RTL (see RTL Phase 4). In LTR this resolves to the left edge.
+ // under RTL (see RTL Phase 4), offset by half a thumb so the extremes
+ // stay inside the component box.
expect(slider).toHaveStyle({insetInlineStart: expectedPosition});
},
);
+ // Regression: #5050 — at min/max the thumb centred on the container edge,
+ // so half of it (10px of a 20px thumb) hung outside the component.
+ it.each([
+ {value: 0, position: 'calc(0% + 10px)'},
+ {value: 50, position: 'calc(50% + 0px)'},
+ {value: 100, position: 'calc(100% - 10px)'},
+ ])(
+ 'insets the thumb at value $value so it stays in bounds',
+ ({value, position}) => {
+ render(<Slider label="Volume" value={value} min={0} max={100} />);
+ expect(screen.getByRole('slider')).toHaveStyle({
+ insetInlineStart: position,
+ });
+ },
+ );
+
+ it.each([
+ {value: 0, position: 'calc(0% + 10px)'},
+ {value: 100, position: 'calc(100% - 10px)'},
+ ])(
+ 'insets a vertical thumb at value $value so it stays in bounds',
+ ({value, position}) => {
+ render(
+ <Slider
+ label="Volume"
+ value={value}
+ min={0}
+ max={100}
+ orientation="vertical"
+ />,
+ );
+ expect(screen.getByRole('slider')).toHaveStyle({bottom: position});
+ },
+ );
+
it('range mode sets correct aria values on both thumbs', () => {
render(
<Slider
@@ -580,22 +616,23 @@ describe('Slider', () => {
/>,
);
const track = screen.getByRole('slider').parentElement!;
- track.getBoundingClientRect = () =>
- ({
- left: 0,
- top: 0,
- right: 200,
- bottom: 20,
- width: 200,
- height: 20,
- x: 0,
- y: 0,
- toJSON: () => {},
- });
+ track.getBoundingClientRect = () => ({
+ left: 0,
+ top: 0,
+ right: 200,
+ bottom: 20,
+ width: 200,
+ height: 20,
+ x: 0,
+ y: 0,
+ toJSON: () => {},
+ });
- // Click at 25% of the track from the left (x=50 of 200) → value 25 in LTR.
+ // Click at x=50 of a 200px track. The thumb's travel is the track minus
+ // half a thumb at each end (180px from x=10), so the fraction is
+ // (50 - 10) / 180 → value 22.
fireEvent.pointerDown(track, {clientX: 50, clientY: 10, pointerId: 1});
- expect(handleChange).toHaveBeenLastCalledWith(25);
+ expect(handleChange).toHaveBeenLastCalledWith(22);
});
it('mirrors a track click to the RTL value when the track is rtl', () => {
@@ -611,18 +648,17 @@ describe('Slider', () => {
/>,
);
const track = screen.getByRole('slider').parentElement!;
- track.getBoundingClientRect = () =>
- ({
- left: 0,
- top: 0,
- right: 200,
- bottom: 20,
- width: 200,
- height: 20,
- x: 0,
- y: 0,
- toJSON: () => {},
- });
+ track.getBoundingClientRect = () => ({
+ left: 0,
+ top: 0,
+ right: 200,
+ bottom: 20,
+ width: 200,
+ height: 20,
+ x: 0,
+ y: 0,
+ toJSON: () => {},
+ });
// Force the track's computed direction to rtl (isRtlElement reads this).
const realGetComputedStyle = window.getComputedStyle;
@@ -635,11 +671,11 @@ describe('Slider', () => {
return realGetComputedStyle(el, pseudo ?? undefined);
});
- // Same physical click at 25% from the left (x=50). Under RTL the inline
- // start is the right edge, so fraction = (right - x)/width = 150/200 = 0.75
- // → value 75 (the mirror of the LTR value 25).
+ // Same physical click at x=50. Under RTL the inline start is the right
+ // edge, so the fraction is (right - 10 - x) / 180 = 140/180 → value 78
+ // (the mirror of the LTR value 22).
fireEvent.pointerDown(track, {clientX: 50, clientY: 10, pointerId: 1});
- expect(handleChange).toHaveBeenLastCalledWith(75);
+ expect(handleChange).toHaveBeenLastCalledWith(78);
gcsSpy.mockRestore();
});
diff --git a/packages/core/src/Slider/Slider.tsx b/packages/core/src/Slider/Slider.tsx
index f0496614b1..4ba8a505bc 100644
--- a/packages/core/src/Slider/Slider.tsx
+++ b/packages/core/src/Slider/Slider.tsx
@@ -366,6 +366,44 @@ function getPercent(val: number, min: number, max: number): number {
return ((val - min) / (max - min)) * 100;
}
+/**
+ * Thumb travel is inset by half a thumb at each end — the geometry a native
+ * `input[type=range]` uses — so the thumb stays inside the component box at
+ * min and max instead of overhanging it by half its width (#5050). The fill
+ * and the marks map through the same inset, and `travelFraction` inverts it,
+ * so the thumb tracks the pointer that grabbed it. Both directions read
+ * THUMB_SIZE, so a theme cannot resize the thumb through CSS alone.
+ */
+const THUMB_INSET = THUMB_SIZE / 2;
+
+function insetPosition(percent: number): string {
+ return cssLength(percent, THUMB_INSET - (percent / 100) * THUMB_SIZE);
+}
+
+/** Distance between two inset positions; the inset itself cancels out. */
+function insetSpan(fromPercent: number, toPercent: number): string {
+ const delta = toPercent - fromPercent;
+ return cssLength(delta, -(delta / 100) * THUMB_SIZE);
+}
+
+/** Inverse of `insetPosition`: an offset from the box start back to 0–1. */
+function travelFraction(offset: number, size: number): number {
+ const travel = size - THUMB_SIZE;
+ if (travel > 0) {
+ return (offset - THUMB_INSET) / travel;
+ }
+ // Narrower than the thumb, so there is no travel to map onto: fall back to
+ // the raw fraction rather than dividing by zero.
+ return size > 0 ? offset / size : 0;
+}
+
+function cssLength(percent: number, px: number): string {
+ // Percentages of the box and step arithmetic both carry binary
+ // floating-point error into the DOM (`calc(33% + 3.3999999999999995px)`).
+ const round = (n: number) => Number(n.toFixed(3));
+ return `calc(${round(percent)}% ${px < 0 ? '-' : '+'} ${Math.abs(round(px))}px)`;
+}
+
// =============================================================================
// Component
// =============================================================================
@@ -483,17 +521,21 @@ export function Slider({ref, ...props}: SliderProps) {
}
const rect = track.getBoundingClientRect();
+ // Inverse of `insetPosition`: the pointer maps onto the thumb's travel
+ // (the box minus half a thumb at each end), so pressing on the thumb
+ // leaves it where it is instead of jumping.
let percent: number;
if (isHorizontal) {
// In RTL the inline-start (value = min) is the right edge, so measure
// the pointer fraction from the right instead of the left. Detected
// from the track's computed direction (lazy, only on pointer move).
- percent = isRtlElement(track)
- ? (rect.right - clientX) / rect.width
- : (clientX - rect.left) / rect.width;
+ percent = travelFraction(
+ isRtlElement(track) ? rect.right - clientX : clientX - rect.left,
+ rect.width,
+ );
} else {
// Vertical: bottom = min, top = max
- percent = 1 - (clientY - rect.top) / rect.height;
+ percent = 1 - travelFraction(clientY - rect.top, rect.height);
}
percent = clamp(percent, 0, 1);
const raw = min + percent * (max - min);
@@ -723,8 +765,8 @@ export function Slider({ref, ...props}: SliderProps) {
const percent = getPercent(val, min, max);
const positionStyle = isHorizontal
- ? {insetInlineStart: `${percent}%`}
- : {bottom: `${percent}%`, left: '50%'};
+ ? {insetInlineStart: insetPosition(percent)}
+ : {bottom: insetPosition(percent), left: '50%'};
// In range mode each thumb keeps a short individual name that composes
// with the group label (announced via the group's aria-labelledby), per
@@ -809,22 +851,23 @@ export function Slider({ref, ...props}: SliderProps) {
return thumbElement;
};
- // Filled track position
+ // Filled track position — ends at the thumb centre, so it uses the same
+ // inset mapping as the thumb.
const filledStyle = (() => {
if (isRange) {
const [v0, v1] = values;
const p0 = getPercent(v0, min, max);
const p1 = getPercent(v1, min, max);
if (isHorizontal) {
- return {insetInlineStart: `${p0}%`, width: `${p1 - p0}%`};
+ return {insetInlineStart: insetPosition(p0), width: insetSpan(p0, p1)};
}
- return {bottom: `${p0}%`, height: `${p1 - p0}%`};
+ return {bottom: insetPosition(p0), height: insetSpan(p0, p1)};
}
const p = getPercent(values[0], min, max);
if (isHorizontal) {
- return {insetInlineStart: '0%', width: `${p}%`};
+ return {insetInlineStart: '0%', width: insetPosition(p)};
}
- return {bottom: '0%', height: `${p}%`};
+ return {bottom: '0%', height: insetPosition(p)};
})();
// Text value display
@@ -949,8 +992,8 @@ export function Slider({ref, ...props}: SliderProps) {
{marks.map(mark => {
const percent = getPercent(mark.value, min, max);
const markPos = isHorizontal
- ? {insetInlineStart: `${percent}%`}
- : {bottom: `${percent}%`};
+ ? {insetInlineStart: insetPosition(percent)}
+ : {bottom: insetPosition(percent)};
return (
<div key={mark.value}>
<div