import { useState, type CSSProperties } from "react";
import { NotchSlider } from "./NotchSlider";
import "./example.css";
interface NotchSliderExampleProps {
preview?: boolean;
previewActive?: boolean;
style?: CSSProperties;
}
export default function NotchSliderExample({ preview = false, previewActive = false, style }: NotchSliderExampleProps) {
const [orientation, setOrientation] = useState<"vertical" | "horizontal">("vertical");
const [tone, setTone] = useState(0);
const contrasting = tone >= 50;
const horizontal = orientation === "horizontal";
return (
<div className={`zoom-example${preview ? " zoom-example--preview" : ""}`} inert={preview}>
<div className="zoom-example-stage">
<NotchSlider
style={style}
defaultValue={preview ? 3 : 4}
orientation={orientation}
surfaceTone={tone}
lifted={preview && previewActive}
wheel={preview ? false : "page"}
/>
</div>
{!preview && <div className="zoom-example-actions">
<button
type="button"
className="zoom-example-action zoom-example-orientation"
aria-label={`Switch to ${horizontal ? "vertical" : "horizontal"}`}
onClick={() => setOrientation(horizontal ? "vertical" : "horizontal")}
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M5 8C6.38324 5.60879 9.03887 4 12 4C16.4183 4 20 7.58172 20 12" />
<path d="M5 4V8H9" />
<path d="M19.0117 20V16H15.0117" />
<path d="M4 12C4 16.4183 7.58172 20 12 20C14.9611 20 17.6168 18.3912 19 16" />
</svg>
</button>
<button
type="button"
className="zoom-example-action zoom-example-tone"
aria-label="Contrasting grabber"
aria-pressed={contrasting}
onClick={() => {
const next = contrasting ? 0 : 100;
setTone(next);
}}
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M12 8C9.79086 8 8 9.79086 8 12C8 14.2091 9.79086 16 12 16V8Z" fill="currentColor" />
<path fillRule="evenodd" clipRule="evenodd" d="M12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2ZM12 8C14.2091 8 16 9.79086 16 12C16 14.2091 14.2091 16 12 16V20C7.58172 20 4 16.4183 4 12C4 7.58172 7.58172 4 12 4V8Z" fill="currentColor" />
</svg>
</button>
</div>}
</div>
);
}
.zoom-example {
display: grid;
justify-items: center;
grid-template-rows: var(--zoom-length, 340px) 44px;
gap: 24px;
width: var(--zoom-length, 340px);
height: calc(var(--zoom-length, 340px) + 68px);
flex-shrink: 0;
color: light-dark(#171717, #ededed);
}
/* Both orientations occupy the same square; the center and button never move. */
.zoom-example-stage { display: grid; place-items: center; width: var(--zoom-length, 340px); height: var(--zoom-length, 340px); }
.zoom-example--preview { grid-template-rows: 340px; gap: 0; height: 340px; }
.zoom-example-actions { display: flex; align-items: center; gap: 8px; height: 44px; }
.zoom-example-action {
display: grid;
place-items: center;
width: 44px;
height: 44px;
padding: 0;
border: 0;
border-radius: 50%;
background: transparent;
color: color-mix(in srgb, currentColor 55%, transparent);
cursor: pointer;
transition: background-color 150ms ease, transform 150ms ease;
}
.zoom-example-tone[aria-pressed="true"] { color: currentColor; }
.zoom-example-action svg { flex-shrink: 0; }
.zoom-example-action:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; }
.zoom-example-action:active { transform: scale(0.94); }
@media (hover: hover) and (pointer: fine) {
.zoom-example-action:hover { background: light-dark(rgb(0 0 0 / 5%), rgb(255 255 255 / 7%)); }
}
@media (prefers-reduced-motion: reduce) {
.zoom-example-action { transition: none; }
.zoom-example-action:active { transform: none; }
}
import { useId, useLayoutEffect, useRef, type CSSProperties } from "react";
import { clampNotchValue, initNotchSlider, type NotchSliderChange } from "./controller";
import "./NotchSlider.css";
type NotchSliderStyle = CSSProperties & {
/** Total end-to-end length, including the two 44px buttons. Defaults to 340px. */
"--zoom-length"?: string;
"--zoom-foreground"?: string;
"--zoom-background"?: string;
};
export interface NotchSliderProps {
/** Half steps select minor ticks; whole steps select only major ticks. */
step?: 0.5 | 1;
orientation?: "vertical" | "horizontal";
/** Show pickup feedback without initiating a drag, for inert previews. */
lifted?: boolean;
/** 0 uses the page surface; 100 uses its contrasting foreground. */
surfaceTone?: number;
defaultValue?: number;
onValueChange?: (value: number, change: NotchSliderChange) => void;
formatValue?: (value: number) => string;
label?: string;
increaseLabel?: string;
decreaseLabel?: string;
controls?: string;
/** Opt in to Command-wheel over this control or the page. */
wheel?: false | "control" | "page";
id?: string;
className?: string;
style?: NotchSliderStyle;
}
/** Seven stops by default, from smallest (bottom/left) to largest (top/right). */
export function NotchSlider({
defaultValue = 4, step = 0.5, orientation = "vertical", lifted = false, surfaceTone = 0, onValueChange, formatValue,
label = "Notch slider", increaseLabel = "Increase", decreaseLabel = "Decrease",
controls, wheel = false, id, className = "", style,
}: NotchSliderProps) {
const root = useRef<HTMLDivElement>(null);
const grooveFilterId = `zoom-groove-${useId()}`;
const horizontal = orientation === "horizontal";
const tone = Math.min(100, Math.max(0, surfaceTone));
const surfaceStyle = {
"--zoom-thumb-tone": `${tone}%`,
"--zoom-thumb-glaze-top": tone < 50
? "light-dark(rgb(255 255 255 / 85%), rgb(255 255 255 / 6%))"
: "light-dark(rgb(255 255 255 / 10%), rgb(255 255 255 / 85%))",
"--zoom-thumb-glaze-middle": tone < 50
? "light-dark(rgb(255 255 255 / 25%), transparent)"
: "light-dark(transparent, rgb(255 255 255 / 25%))",
"--zoom-thumb-glaze-bottom": tone < 50
? "light-dark(rgb(0 0 0 / 4%), rgb(0 0 0 / 10%))"
: "light-dark(rgb(0 0 0 / 10%), rgb(0 0 0 / 4%))",
"--zoom-thumb-grip-color": `color-mix(in srgb, var(${tone < 50 ? "--zoom-foreground" : "--zoom-background"}) 65%, transparent)`,
"--zoom-thumb-grip-highlight": tone < 50
? "light-dark(rgb(255 255 255 / 80%), rgb(255 255 255 / 12%))"
: "light-dark(rgb(255 255 255 / 12%), rgb(255 255 255 / 80%))",
...style,
} as CSSProperties;
const initialValue = useRef(clampNotchValue(defaultValue, step)).current;
const currentValue = useRef(initialValue);
const callbacks = useRef({ onValueChange, formatValue });
callbacks.current = { onValueChange, formatValue };
useLayoutEffect(() => {
if (!root.current) return;
const controller = initNotchSlider(root.current, {
defaultValue: currentValue.current,
orientation,
step,
formatValue: value => callbacks.current.formatValue?.(value) ?? `${value} of 4`,
onValueChange: (value, change) => {
currentValue.current = value;
callbacks.current.onValueChange?.(value, change);
},
wheelTarget: wheel === "page" ? document : wheel === "control" ? root.current : undefined,
});
return () => controller?.dispose();
}, [initialValue, wheel, orientation, step]);
function renderButton(increase: boolean) {
return (
<button key={increase ? "in" : "out"} type="button" className="pg-zoom-button"
data-zoom={increase ? "in" : "out"} aria-label={increase ? increaseLabel : decreaseLabel}
disabled={initialValue === (increase ? 4 : 1)}>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
<path d={increase ? "M8 3v10M3 8h10" : "M3 8h10"} stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
</button>
);
}
return (
<div ref={root} id={id} data-orientation={orientation} data-lifted={lifted || undefined} className={`pg-notch-slider ${className}`} style={surfaceStyle} role="group" aria-label={label}>
{renderButton(orientation === "vertical")}
<div key="slider" className="pg-zoom-slider" role="slider" tabIndex={0} aria-label={label}
aria-orientation={orientation} aria-valuemin={1} aria-valuemax={4}
aria-valuenow={initialValue} aria-valuetext={formatValue?.(initialValue) ?? `${initialValue} of 4`}
aria-controls={controls}>
<div className="pg-zoom-rail" aria-hidden="true">
<svg className="pg-zoom-groove" viewBox={horizontal ? "0 0 218 6" : "0 0 6 218"}>
<defs>
<filter id={grooveFilterId} filterUnits="userSpaceOnUse" x="-3" y="-3"
width={horizontal ? 224 : 12} height={horizontal ? 12 : 224} colorInterpolationFilters="sRGB">
<feOffset in="SourceAlpha" dx="0.4" dy="0.75" result="offset" />
<feComposite in="offset" in2="SourceAlpha" operator="out" result="lip" />
<feFlood className="pg-zoom-groove-lip" />
<feComposite in2="lip" operator="in" result="highlight" />
<feGaussianBlur in="offset" stdDeviation="0.35" result="softOffset" />
<feComposite in="SourceAlpha" in2="softOffset" operator="out" result="inset" />
<feFlood className="pg-zoom-groove-shadow" />
<feComposite in2="inset" operator="in" result="shadow" />
<feMerge>
<feMergeNode in="highlight" />
<feMergeNode in="SourceGraphic" />
<feMergeNode in="shadow" />
</feMerge>
</filter>
</defs>
{/* Shade the combined silhouette so no edge crosses a rail/notch junction. */}
<g filter={`url(#${grooveFilterId})`}>
<g transform={horizontal ? "matrix(0 1 1 0 0 0)" : undefined}>
<rect data-zoom-stem x="2" y="1" width="2" height="216" />
{(step === 1 ? [0, 2, 4, 6] : [0, 1, 2, 3, 4, 5, 6]).map(tick => (
<rect key={tick} data-zoom-tick={tick} x={tick % 2 ? 1 : 0} y={tick * 36}
width={tick % 2 ? 4 : 6} height="2" rx="1" />
))}
</g>
</g>
</svg>
</div>
<span className="pg-zoom-thumb" aria-hidden="true" style={{ transform: `translate${horizontal ? "X" : "Y"}(calc((var(--zoom-length, 340px) - 124px) * ${(horizontal ? initialValue - 1 : 4 - initialValue) / 3}))` }}>
<span className="pg-zoom-thumb-face"><span className="pg-zoom-grip" /></span>
</span>
</div>
{renderButton(orientation === "horizontal")}
</div>
);
}
.pg-notch-slider {
--zoom-foreground: light-dark(#171717, #ededed);
--zoom-background: light-dark(#fff, #0d0d0d);
--zoom-cut-shadow: light-dark(rgb(0 0 0 / 20%), rgb(0 0 0 / 75%));
--zoom-cut-lip: light-dark(rgb(255 255 255 / 90%), rgb(255 255 255 / 12%));
--zoom-thumb-surface-base: light-dark(var(--zoom-background), color-mix(in srgb, var(--zoom-foreground) 10%, var(--zoom-background)));
position: relative;
width: 44px;
color: var(--zoom-foreground);
user-select: none;
-webkit-user-select: none;
}
.pg-notch-slider *, .pg-notch-slider *::before, .pg-notch-slider *::after { box-sizing: border-box; }
.pg-zoom-button {
position: relative;
display: flex;
width: 44px;
height: 44px;
flex-shrink: 0;
align-items: center;
justify-content: center;
border: 0;
padding: 0;
border-radius: 50%;
color: color-mix(in srgb, var(--zoom-foreground) 60%, var(--zoom-background));
background: transparent;
cursor: pointer;
touch-action: none;
-webkit-touch-callout: none;
transition: transform 150ms ease-out, color 150ms ease;
}
.pg-zoom-button svg {
flex-shrink: 0;
/* A shaded upper edge and a light lower lip give the glyphs a shallow cut. */
filter: drop-shadow(0 -0.5px 0 var(--zoom-cut-shadow))
drop-shadow(0 1px 0 var(--zoom-cut-lip));
}
.pg-zoom-button:disabled {
color: color-mix(in srgb, var(--zoom-foreground) 24%, transparent);
cursor: default;
}
.pg-zoom-button:active:not(:disabled) { transform: scale(0.9); }
.pg-zoom-slider {
position: relative;
width: 44px;
height: calc(var(--zoom-length, 340px) - 88px);
border-radius: 12px;
touch-action: none;
cursor: grab;
}
.pg-notch-slider[data-dragging="true"] .pg-zoom-slider { cursor: grabbing; }
.pg-zoom-rail {
position: absolute;
top: 18px;
bottom: 18px;
left: 21px;
width: 2px;
pointer-events: none;
}
.pg-zoom-groove {
position: absolute;
top: -1px;
left: -2px;
width: 6px;
height: calc(100% + 2px);
overflow: visible;
fill: light-dark(
color-mix(in srgb, var(--zoom-foreground) 10%, var(--zoom-background)),
color-mix(in srgb, var(--zoom-foreground) 18%, var(--zoom-background))
);
}
.pg-zoom-groove-lip { flood-color: var(--zoom-cut-lip); }
.pg-zoom-groove-shadow { flood-color: var(--zoom-cut-shadow); }
.pg-zoom-thumb {
position: absolute;
top: calc(18px - var(--zoom-thumb-height, 22px) / 2);
left: calc(22px - var(--zoom-thumb-width, 28px) / 2);
width: var(--zoom-thumb-width, 28px);
height: var(--zoom-thumb-height, 22px);
border-radius: var(--zoom-thumb-radius, 8px);
pointer-events: none;
transform: translateY(0px);
}
/* Travel belongs to the outer thumb; pickup never scales its track position. */
.pg-zoom-thumb-face {
position: absolute;
inset: 0;
display: grid;
place-items: center;
border-radius: inherit;
isolation: isolate;
transform: scale(1);
transition: transform 180ms cubic-bezier(0.215, 0.61, 0.355, 1);
background: var(--zoom-thumb-background,
linear-gradient(
var(--zoom-thumb-glaze-top, light-dark(rgb(255 255 255 / 85%), rgb(255 255 255 / 6%))),
var(--zoom-thumb-glaze-middle, light-dark(rgb(255 255 255 / 25%), transparent)) 48%,
var(--zoom-thumb-glaze-bottom, light-dark(rgb(0 0 0 / 4%), rgb(0 0 0 / 10%)))),
color-mix(in srgb, var(--zoom-foreground) var(--zoom-thumb-tone, 0%), var(--zoom-thumb-surface-base)));
box-shadow: var(--zoom-thumb-shadow,
inset 0 1px 0 light-dark(rgb(255 255 255 / 60%), rgb(255 255 255 / 12%)),
inset 0 -1px 1px light-dark(rgb(0 0 0 / 16%), rgb(0 0 0 / 30%)),
0 0 0 1px color-mix(in srgb, var(--zoom-foreground) 10%, transparent),
0 1px 8px -1px light-dark(rgb(0 0 0 / 8.1%), rgb(0 0 0 / 20.25%)),
0 7px 10px -3px light-dark(rgb(0 0 0 / 8.1%), rgb(0 0 0 / 27%)));
}
.pg-zoom-thumb-face::before {
content: "";
position: absolute;
inset: 0;
z-index: -1;
border-radius: inherit;
box-shadow:
0 5px 8px -2px light-dark(rgb(0 0 0 / 8%), rgb(0 0 0 / 24%)),
0 10px 16px -4px light-dark(rgb(0 0 0 / 6%), rgb(0 0 0 / 30%));
opacity: 0;
transition: opacity 180ms cubic-bezier(0.215, 0.61, 0.355, 1);
}
.pg-notch-slider:is([data-dragging="true"], [data-lifted="true"]) .pg-zoom-thumb-face {
transform: scale(1.05);
transition-duration: 140ms;
}
.pg-notch-slider:is([data-dragging="true"], [data-lifted="true"]) .pg-zoom-thumb-face::before {
opacity: 1;
transition-duration: 140ms;
}
.pg-zoom-grip {
position: relative;
width: 10px;
height: 4px;
}
.pg-zoom-grip::before,
.pg-zoom-grip::after {
content: "";
position: absolute;
left: 0;
right: 0;
height: 1px;
border-radius: 1px;
background: var(--zoom-thumb-grip-color, color-mix(in srgb, var(--zoom-foreground) 65%, transparent));
/* A shaded upper edge and a light lower lip cut both grip marks into the face. */
box-shadow: 0 -0.5px 0.5px rgb(0 0 0 / 20%),
0 1px 0 var(--zoom-thumb-grip-highlight, light-dark(rgb(255 255 255 / 80%), rgb(255 255 255 / 12%)));
}
.pg-zoom-grip::before { top: 0; }
.pg-zoom-grip::after { bottom: 0; }
.pg-zoom-button:focus-visible,
.pg-zoom-slider:focus-visible {
outline: 2px solid color-mix(in srgb, var(--zoom-foreground) 60%, transparent);
outline-offset: 3px;
}
.pg-zoom-slider[data-pointer-focus] { outline: none; }
@media (hover: hover) and (pointer: fine) {
.pg-zoom-button:hover:not(:disabled) { color: var(--zoom-foreground); }
}
@media (prefers-reduced-motion: reduce) {
.pg-zoom-button { transition: none; }
.pg-zoom-button:active:not(:disabled) { transform: none; }
.pg-zoom-thumb-face, .pg-zoom-thumb-face::before { transition: none; }
.pg-notch-slider:is([data-dragging="true"], [data-lifted="true"]) .pg-zoom-thumb-face { transform: scale(1); }
}
/* Horizontal reads from minus on the left to plus on the right. */
.pg-notch-slider[data-orientation="horizontal"] {
display: flex;
flex-direction: row;
width: var(--zoom-length, 340px);
height: 44px;
}
.pg-notch-slider[data-orientation="horizontal"] .pg-zoom-slider { width: calc(var(--zoom-length, 340px) - 88px); height: 44px; flex-shrink: 0; }
.pg-notch-slider[data-orientation="horizontal"] .pg-zoom-rail {
top: 21px;
bottom: auto;
left: 18px;
right: 18px;
width: auto;
height: 2px;
}
.pg-notch-slider[data-orientation="horizontal"] .pg-zoom-groove {
top: -2px;
left: -1px;
width: calc(100% + 2px);
height: 6px;
}
.pg-notch-slider[data-orientation="horizontal"] .pg-zoom-thumb {
top: calc(22px - var(--zoom-thumb-height, 22px) / 2);
left: calc(18px - var(--zoom-thumb-width, 28px) / 2);
}
import { animate } from "motion";
export interface NotchSliderChange { instant: boolean }
export interface NotchSliderOptions {
step?: 0.5 | 1;
orientation?: "vertical" | "horizontal";
defaultValue?: number;
formatValue?: (value: number) => string;
onValueChange?: (value: number, change: NotchSliderChange) => void;
isEnabled?: () => boolean;
wheelTarget?: HTMLElement | Document;
}
export function clampNotchValue(value: number, step: 0.5 | 1 = 0.5) {
return Number.isFinite(value) ? Math.max(1, Math.min(4, Math.round(value / step) * step)) : 4;
}
/** Attach to one control. The host owns the content being resized. */
export function initNotchSlider(control: HTMLElement, options: NotchSliderOptions = {}) {
const slider = control.querySelector<HTMLElement>('[role="slider"]');
const rail = control.querySelector<HTMLElement>(".pg-zoom-rail");
const thumb = control.querySelector<HTMLElement>(".pg-zoom-thumb");
const larger = control.querySelector<HTMLButtonElement>('[data-zoom="in"]');
const smaller = control.querySelector<HTMLButtonElement>('[data-zoom="out"]');
if (!slider || !rail || !thumb || !larger || !smaller) return;
const step = options.step ?? 0.5;
const horizontal = options.orientation === "horizontal";
const events = new AbortController();
const { signal } = events;
const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)");
const enabled = () => control.getClientRects().length > 0
&& !control.closest("[inert]") && (options.isEnabled?.() ?? true);
let thumbAnimation: ReturnType<typeof animate> | undefined;
let rebounding = false;
let value = clampNotchValue(options.defaultValue ?? 4, step);
let pointerId: number | undefined;
let overdrag = 0;
const groove = rail.querySelector<SVGSVGElement>(".pg-zoom-groove");
const grooveFilter = groove?.querySelector("filter");
const stem = groove?.querySelector("[data-zoom-stem]");
const ticks = groove?.querySelectorAll<SVGRectElement>("[data-zoom-tick]");
let measuredLength = 0;
function resizeTrack() {
const length = horizontal ? rail!.clientWidth : rail!.clientHeight;
if (!length || length === measuredLength) return;
measuredLength = length;
// Rebuild the shared silhouette at its actual size rather than stretching
// the notch thickness, corner radii, or engraved lighting with the track.
groove?.setAttribute("viewBox", horizontal ? `0 0 ${length + 2} 6` : `0 0 6 ${length + 2}`);
grooveFilter?.setAttribute("width", String(horizontal ? length + 8 : 12));
grooveFilter?.setAttribute("height", String(horizontal ? 12 : length + 8));
stem?.setAttribute("height", String(length));
ticks?.forEach(tick => tick.setAttribute("y", String(Number(tick.dataset.zoomTick) * length / 6)));
endDrag();
syncControl(true);
}
function syncButtons() {
// Keep the held button enabled so the endpoint doesn't steal focus/capture.
larger!.disabled = value === 4 && buttonHold?.button !== larger;
smaller!.disabled = value === 1 && buttonHold?.button !== smaller;
}
function thumbDistance() {
return horizontal
? (value - 1) * rail!.clientWidth / 3
: (4 - value) * rail!.clientHeight / 3;
}
function renderPosition(position: number) {
thumb!.style.transform = `translate${horizontal ? "X" : "Y"}(${position}px)`;
}
function syncControl(instant = false) {
const label = options.formatValue?.(value) ?? `${value} of 4`;
// Larger values sit higher vertically and farther right horizontally.
slider!.setAttribute("aria-valuenow", String(value));
slider!.setAttribute("aria-valuetext", label);
syncButtons();
syncThumb(instant);
}
function syncThumb(instant = false) {
thumbAnimation?.stop();
rebounding = false;
const target = thumbDistance() + overdrag;
if (instant || reducedMotion.matches) {
renderPosition(target);
} else {
// Animate a number so an interrupted DOM animation cannot overwrite a
// direct pointer update with a queued transform from the previous frame.
const current = new DOMMatrixReadOnly(getComputedStyle(thumb!).transform);
thumbAnimation = animate(horizontal ? current.m41 : current.m42, target, {
type: "spring", visualDuration: 0.2, bounce: 0.24,
onUpdate: renderPosition,
});
}
}
function setValue(next: number, instant = false, notify = true) {
next = clampNotchValue(next, step);
if (next === value) return;
value = next;
syncControl(instant);
if (notify) options.onValueChange?.(value, { instant });
}
// Advance as the existing snap settles, keeping the notch rhythm brisk.
const holdDelay = 350;
const repeatInterval = 200;
let repeatTimer: ReturnType<typeof setTimeout> | undefined;
let buttonHold: {
button: HTMLButtonElement;
direction: number;
pointerId?: number;
key?: string;
} | undefined;
function stopButtonHold() {
clearTimeout(repeatTimer);
repeatTimer = undefined;
const previous = buttonHold;
buttonHold = undefined;
syncButtons();
if (rebounding) syncThumb(previous?.key !== undefined);
if (previous?.pointerId !== undefined && previous.button.hasPointerCapture(previous.pointerId)) {
previous.button.releasePointerCapture(previous.pointerId);
}
}
function reboundAtEnd(direction: number) {
thumbAnimation?.stop();
rebounding = true;
const current = new DOMMatrixReadOnly(getComputedStyle(thumb!).transform);
// The same 200ms / 0.24-bounce spring, expressed as physics so it accepts
// an outward impulse. It travels about 5px and returns to the fixed value.
thumbAnimation = animate(horizontal ? current.m41 : current.m42, thumbDistance(), {
type: "spring", stiffness: 685, damping: 40,
velocity: direction * (horizontal ? 1 : -1) * 300,
onUpdate: renderPosition,
});
}
function stepHeldButton() {
const hold = buttonHold;
if (!hold || hold.button.disabled || !enabled()) {
stopButtonHold();
return false;
}
const next = clampNotchValue(value + hold.direction * step, step);
if (next === value) {
if (!reducedMotion.matches && hold.key === undefined) reboundAtEnd(hold.direction);
} else {
setValue(next, hold.key !== undefined);
}
// A host callback may cancel or replace this controller during a step.
if (buttonHold !== hold) return false;
return true;
}
function repeatButton() {
if (stepHeldButton()) repeatTimer = setTimeout(repeatButton, repeatInterval);
}
function bindStepButton(button: HTMLButtonElement, direction: number) {
let suppressPointerClick = false;
button.addEventListener("pointerdown", (event) => {
if (!event.isPrimary || event.button !== 0 || button.disabled || !enabled()) return;
stopButtonHold();
endDrag();
suppressPointerClick = true;
buttonHold = { button, direction, pointerId: event.pointerId };
button.setPointerCapture(event.pointerId);
if (stepHeldButton()) repeatTimer = setTimeout(repeatButton, holdDelay);
}, { signal });
const endPress = (event: PointerEvent) => {
if (buttonHold?.button === button && buttonHold.pointerId === event.pointerId) stopButtonHold();
};
button.addEventListener("pointerup", endPress, { signal });
button.addEventListener("pointercancel", endPress, { signal });
button.addEventListener("lostpointercapture", endPress, { signal });
button.addEventListener("pointerleave", endPress, { signal });
button.addEventListener("pointermove", (event) => {
if (buttonHold?.button !== button || buttonHold.pointerId !== event.pointerId) return;
// Pointer capture keeps release reliable; explicitly detect leaving its bounds.
const rect = button.getBoundingClientRect();
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) {
stopButtonHold();
}
}, { signal });
button.addEventListener("contextmenu", (event) => {
if (buttonHold?.button === button) event.preventDefault();
}, { signal });
button.addEventListener("keydown", (event) => {
if ((event.key !== " " && event.key !== "Enter") || event.metaKey || event.ctrlKey || event.altKey) return;
event.preventDefault();
if (event.repeat || button.disabled || !enabled()) return;
stopButtonHold();
endDrag();
buttonHold = { button, direction, key: event.key };
if (stepHeldButton()) repeatTimer = setTimeout(repeatButton, holdDelay);
}, { signal });
button.addEventListener("keyup", (event) => {
if (event.key !== " " && event.key !== "Enter") return;
event.preventDefault();
if (buttonHold?.button === button && buttonHold.key === event.key) stopButtonHold();
}, { signal });
button.addEventListener("blur", () => {
if (buttonHold?.button === button) stopButtonHold();
}, { signal });
button.addEventListener("click", (event) => {
// Pointer presses already stepped on down; preserve synthesized/AT clicks.
if (event.detail !== 0 && suppressPointerClick) {
suppressPointerClick = false;
return;
}
if (!button.disabled && enabled()) setValue(value + direction * step, event.detail === 0);
}, { signal });
}
bindStepButton(larger, 1);
bindStepButton(smaller, -1);
document.addEventListener("visibilitychange", () => {
if (document.hidden) stopButtonHold();
}, { signal });
slider.addEventListener("keydown", (event) => {
if (event.metaKey || event.ctrlKey || event.altKey) return;
stopButtonHold();
delete slider.dataset.pointerFocus;
const values: Record<string, number> = {
ArrowUp: value + step, ArrowRight: value + step,
ArrowDown: value - step, ArrowLeft: value - step,
Home: 1, End: 4,
};
if (!(event.key in values)) return;
event.preventDefault();
setValue(values[event.key], true);
}, { signal });
slider.addEventListener("blur", () => {
delete slider.dataset.pointerFocus;
}, { signal });
function setFromPointer(event: PointerEvent) {
const rect = rail!.getBoundingClientRect();
const length = horizontal ? rect.width : rect.height;
if (!length) return;
const position = horizontal
? (event.clientX - rect.left) / length * 3
: (event.clientY - rect.top) / length * 3;
if (position < 0 || position > 3) {
const edge = position < 0 ? 0 : 3;
const localLength = horizontal ? rail!.clientWidth : rail!.clientHeight;
const distance = (position - edge) * localLength / 3;
// Same exponential resistance curve as the Draggable input demo.
// A 12px limit and 36px resistance keep this small handle close to its rail.
overdrag = Math.sign(distance) * 12 * (1 - Math.exp(-Math.abs(distance) / 36));
setValue(horizontal ? edge + 1 : 4 - edge);
// Follow the pointer directly while stretched; only the return is sprung.
syncControl(true);
return;
}
const wasOverdragging = overdrag !== 0;
overdrag = 0;
// A little hysteresis avoids chatter when hovering at a boundary between stops.
if (Math.abs(position - (horizontal ? value - 1 : 4 - value)) < 0.56 * step) {
if (wasOverdragging) syncControl();
return;
}
const snapped = Math.round(position / step) * step;
setValue(horizontal ? snapped + 1 : 4 - snapped);
}
slider.addEventListener("pointerdown", (event) => {
if (!event.isPrimary || event.button !== 0 || !enabled()) return;
stopButtonHold();
// Let native pointer focus clear keyboard focus-visible state. Cancelling
// pointerdown and focusing manually can preserve/inherit that outline.
// An already-focused slider may retain :focus-visible until it blurs.
slider.dataset.pointerFocus = "true";
pointerId = event.pointerId;
slider.setPointerCapture(pointerId);
control.dataset.dragging = "true";
setFromPointer(event);
}, { signal });
slider.addEventListener("pointermove", (event) => {
if (event.pointerId === pointerId) setFromPointer(event);
}, { signal });
function endDrag() {
const capturedPointer = pointerId;
pointerId = undefined;
if (capturedPointer !== undefined && slider!.hasPointerCapture(capturedPointer)) slider!.releasePointerCapture(capturedPointer);
delete control!.dataset.dragging;
if (overdrag !== 0) {
overdrag = 0;
syncControl();
}
}
slider.addEventListener("pointerup", endDrag, { signal });
slider.addEventListener("pointercancel", endDrag, { signal });
slider.addEventListener("lostpointercapture", endDrag, { signal });
// One deliberate step per wheel burst. The idle gap separates gestures so a
// trackpad's decaying momentum cannot run through all four layouts.
const wheelIdle = 180;
let lastWheel = -Infinity;
let lastPlainWheel = -Infinity;
let wheelDistance = 0;
let wheelDirection = 0;
let stepped = false;
let commandDuringScroll = false;
function resetWheel() {
lastWheel = -Infinity;
wheelDistance = 0;
wheelDirection = 0;
stepped = false;
commandDuringScroll = false;
}
document.addEventListener("keydown", (event) => {
if (event.key === "Meta" && !event.repeat) {
resetWheel();
commandDuringScroll = performance.now() - lastPlainWheel < wheelIdle;
}
}, { signal });
document.addEventListener("keyup", (event) => {
if (event.key === "Meta") resetWheel();
}, { signal });
window.addEventListener("blur", () => { resetWheel(); endDrag(); stopButtonHold(); }, { signal });
options.wheelTarget?.addEventListener("wheel", (rawEvent) => {
const event = rawEvent as WheelEvent;
const now = performance.now();
if (!event.metaKey) {
lastPlainWheel = now;
return;
}
if (!enabled() || event.ctrlKey || event.altKey || event.shiftKey || event.defaultPrevented || !event.cancelable) return;
if (event.target instanceof Element && event.target.closest('input, textarea, select, [contenteditable="true"]')) return;
if (Math.abs(event.deltaX) > Math.abs(event.deltaY) || event.deltaY === 0) return;
const freshGesture = now - lastWheel > wheelIdle;
if (commandDuringScroll) {
// Let the pre-existing scroll finish. A subsequent fresh gesture may resize.
if (freshGesture && now - lastPlainWheel > wheelIdle) commandDuringScroll = false;
else { lastWheel = now; return; }
}
if (freshGesture) {
wheelDistance = 0;
wheelDirection = 0;
stepped = false;
}
lastWheel = now;
event.preventDefault();
if (stepped) return;
const direction = Math.sign(event.deltaY);
if (direction !== wheelDirection) wheelDistance = 0;
wheelDirection = direction;
const unit = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? 16
: event.deltaMode === WheelEvent.DOM_DELTA_PAGE ? innerHeight : 1;
wheelDistance += Math.abs(event.deltaY) * unit;
if (wheelDistance < 40) return;
stepped = true;
setValue(value - direction * step);
}, { signal, passive: false });
reducedMotion.addEventListener("change", () => syncControl(true), { signal });
control.dataset.ready = "true";
resizeTrack();
syncControl(true);
const resizeObserver = new ResizeObserver(resizeTrack);
resizeObserver.observe(rail);
return {
setValue,
cancelInteraction() { endDrag(); resetWheel(); stopButtonHold(); },
dispose() {
stopButtonHold();
resizeObserver.disconnect();
events.abort();
endDrag();
thumbAnimation?.stop();
delete control.dataset.ready;
},
};
}
# Notch slider
A vertical or horizontal, seven-stop React control with spring snapping, pointer capture, keyboard input, and an optional Command-wheel shortcut. The Playground demo uses seven stops; the index reuses the same component with four stops to control gallery density.
## Get started
Requires React and React DOM (the demo uses React 19) and Motion:
```sh
npm install motion
```
Copy `NotchSlider.tsx`, `NotchSlider.css`, and `controller.ts` into the same folder. No Astro, Tailwind, site styles, or icon library is required. In frameworks with server components, place the component behind a client boundary. The component imports its stylesheet and inherits `color-scheme`; set `color-scheme: light dark` on your page for system appearance.
```tsx
import { useState } from "react";
import { NotchSlider } from "./NotchSlider";
export default function Gallery() {
const [columns, setColumns] = useState(1);
return <>
<div id="gallery" style={{ display: "grid", gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}>
{/* Your cards */}
</div>
<NotchSlider
defaultValue={4}
step={1}
controls="gallery"
label="Card size"
increaseLabel="Larger cards"
decreaseLabel="Smaller cards"
formatValue={value => `${5 - value} ${value === 4 ? "column" : "columns"}`}
onValueChange={value => setColumns(5 - value)}
/>
</>;
}
```
The standalone demo shows just the slider with orientation and contrasting-grabber buttons in a fixed-size stage. To run it, also copy `example.tsx` and `example.css` and render `<NotchSliderExample />`.
## Styling
The defaults use a 28 × 22px grabber with an 8px radius and 45% shadow strength. Light mode has a brighter white face with a gentle three-stop glaze, a 60% upper highlight, and a softened 16% lower inset shadow. Dark mode uses a charcoal face with softer reflected light, the same geometry, and contrasting engraved grip marks. Contact and ambient shadows retain the tuned 1/8/−1px and 7/10/−3px offset/blur/spread values in both themes.
Its grabber accepts CSS overrides on the control root: `--zoom-thumb-width`, `--zoom-thumb-height`, `--zoom-thumb-radius`, `--zoom-thumb-background`, and `--zoom-thumb-shadow`. Changing dimensions preserves the grabber's center on the selected stop.
Use `surfaceTone={100}` for the contrasting grabber variant, or the default `surfaceTone={0}` for the page-surface variant. Both adapt to light and dark mode, including the engraved grip marks. The half-filled circle button switches between these endpoints.
## Values and placement
The control manages its own value. `defaultValue` initializes it once, from 1 (smallest size, bottom/left) through 4 (largest size, top/right). Values are rounded and clamped. The default `step={0.5}` makes all seven notches selectable, including the three smaller intermediate ticks. Use `step={1}` for the four major stops, as in the gallery example above. `onValueChange(value, { instant })` runs as each stop changes; `instant` is true for keyboard changes so hosts can skip layout animation. To map size to grid density, use `columns = 5 - value`.
`formatValue` supplies the slider's accessible value text. `label`, `increaseLabel`, and `decreaseLabel` provide accessible names; `controls` identifies the content it manipulates. Multiple instances work independently.
Set `orientation="horizontal"` for a left-to-right control with minus on the left and plus on the right. The default is `"vertical"`. Changing orientation preserves the current value. The component defaults to 44 × 340px vertically and 340 × 44px horizontally, and stays in normal flow. Set `--zoom-length` on the control or its parent to shorten its track without scaling the 28 × 22px grabber or 44px buttons. Notches, engraving, and the selected position update when the rail resizes; a resize ends any active drag without changing its value.
The example reserves the same square for both orientations, with a fixed row of buttons below it, so neither the center nor the buttons shift. The Playground detail host sizes this square between 268px and 340px using the available width and height. At the minimum, minor stops stay 24px apart. Short viewports scroll the preview with room reserved below the controls for fixed navigation. Catalog previews retain their original 340px stage and scale as artwork. Your host controls placement, backdrop, and scrolling. Override `--zoom-foreground` and `--zoom-background` with the `style` prop or a `className`. The catalog's floating halo and mobile breakpoint are intentionally host concerns.
## Interaction
- Press + or − to step once immediately. Hold for 350ms to begin repeating every 200ms, with a brief settling pause at each notch. Continuing to hold at an endpoint gives the grabber a small outward bump that springs back on each repeat, without changing the value. Release or move off the button to stop; cancellation, focus loss, and disposal also stop repetition and settle the grabber. Endpoint buttons become disabled after release. Space and Enter use the same cadence with immediate positioning; keyboard input and reduced motion skip the endpoint bumps.
- Holding the grabber lifts its face to 1.05× with a softer shadow; releasing or cancelling settles it back. This visual layer is independent of track travel, so snapping and overdrag stay centered. Reduced motion uses instant shadow feedback without scaling.
- Drag beyond either end for up to 12px of resisted overdrag, using the same exponential curve as the Draggable input demo. The value stays at its endpoint; release, cancellation, or loss of capture springs the handle back. Reduced motion returns it immediately.
- Drag or click the rail to choose a stop. Updates happen immediately, with a small spring on the handle. Pointer capture lets you finish a drag outside the rail.
- Plus/minus move one stop. Arrow Up/Right increases size, Down/Left decreases it. Home selects the minimum; End selects the maximum.
- Keyboard focus stays visible; pointer dragging suppresses its ring until keyboard input resumes.
- Reduced motion positions the handle immediately.
- `wheel="control"` enables Command-wheel over the control. `wheel="page"` enables it across the page. It is off by default; enable page scope on only one active instance. A gesture threshold and momentum guard allow one step per wheel burst. Ordinary scroll, Ctrl/pinch zoom, modified gestures, and text editing remain native. A hidden or inert instance does not intercept the shortcut.
- All listeners and animations are cleaned up when the component unmounts.
## Framework-independent controller
The React component renders the markup and initializes `initNotchSlider(root, options)` from `controller.ts`. Hosts can render the markup without hydration and initialize this controller directly. Pass a root element, `orientation`, `step`, `defaultValue`, `onValueChange`, `formatValue`, optional `isEnabled`, and optional `wheelTarget` (an element or document). The returned object provides `setValue(value, instant?, notify?)` and `dispose()`. Always call `dispose()` when removing the host. Host-driven changes can use `notify=false` to avoid calling the change callback again.
The index renders this component from `src/components/PlaygroundZoom.astro` with `step={1}`. Its host controller in `src/lib/playground-zoom.ts` maps values to whole-column layouts, preserves scroll anchoring, and disables the control on small screens. The catalog thumbnail is a separate inert instance, so it never changes gallery density.