import { useEffect, useMemo, useRef, useState } from 'react'; import './VerticalSlider.css'; type StepFn = (value: number) => number; type QuantizeFn = (value: number) => number; type Scale = 'linear' | 'log'; type VerticalSliderProps = { min: number; max: number; step?: StepFn; quantize?: QuantizeFn; /** * Optional discrete value set (must be sorted ascending). When provided, * this takes full precedence over `step`/`quantize`/`scale`: the slider * only ever lands on entries from this array. `min`/`max` are used to * slice out the applicable sub-range of `values` (e.g. per-filter-type * Q ranges that all share one master Q table) — both bounds should be * exact members of `values`. Thumb position and drag/keyboard/wheel * navigation are index-based rather than value-based, since spacing in * the array need not be uniform or log-uniform. */ values?: readonly number[]; value: number; onChange?: (value: number) => Promise; onInput?: (value: number) => void; unit?: string | ((value: number) => string); formatValue?: (value: number, decimals: number) => string; showTicks?: boolean; /** 'linear' (default) or 'log'. Log scale requires min > 0 and max > 0. Ignored when `values` is set. */ scale?: Scale; className?: string; style?: React.CSSProperties; /** Greys out the slider and blocks all interaction. */ disabled?: boolean; }; const defaultStep: StepFn = () => 0.1; function formatValueDefault(v: number, decimals: number) { return v.toFixed(decimals); } const TOUCH_INTENT_PX = 20; const MIN_TICKS = 3; const MAX_TICK_SPACING_PX = 16; const WHEEL_COMMIT_DELAY_MS = 250; const NAV_KEYS = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']; function getDecimals(n: number) { const s = n.toString(); const i = s.indexOf('.'); return i === -1 ? 0 : s.length - i - 1; } // --- scale helpers ----------------------------------------------------- /** Guards against log(0) / log(negative); falls back to a tiny positive epsilon. */ function safeLogBound(n: number) { return n > 0 ? n : Number.EPSILON; } /** Binary search for the index of the array entry closest to v. Assumes arr is sorted ascending and non-empty. */ function closestIndex(arr: readonly number[], v: number) { let lo = 0; let hi = arr.length - 1; if (v <= arr[0]) return 0; if (v >= arr[hi]) return hi; while (lo < hi) { const mid = (lo + hi) >> 1; if (arr[mid] === v) return mid; if (arr[mid] < v) lo = mid + 1; else hi = mid; } const a = arr[lo - 1]; const b = arr[lo]; return v - a <= b - v ? lo - 1 : lo; } /** Maps a real value to a 0..1 position, honoring the chosen scale (or index position within `list`). */ function valueToPercent( v: number, min: number, max: number, scale: Scale, list: readonly number[] | null ) { if (list && list.length > 1) { return closestIndex(list, v) / (list.length - 1); } if (scale === 'log') { const logMin = Math.log(safeLogBound(min)); const logMax = Math.log(safeLogBound(max)); if (logMax === logMin) return 0; const logV = Math.log(safeLogBound(v)); return (logV - logMin) / (logMax - logMin); } if (max === min) return 0; return (v - min) / (max - min); } /** Maps a 0..1 position back to a real value, honoring the chosen scale (or nearest index within `list`). */ function percentToValue( percent: number, min: number, max: number, scale: Scale, list: readonly number[] | null ) { if (list && list.length > 1) { const idx = Math.round(percent * (list.length - 1)); return list[Math.min(list.length - 1, Math.max(0, idx))]; } if (scale === 'log') { const logMin = Math.log(safeLogBound(min)); const logMax = Math.log(safeLogBound(max)); return Math.exp(logMin + percent * (logMax - logMin)); } return min + percent * (max - min); } /** * Builds a StepFn that yields roughly `points` evenly-spaced steps between * `min` and `max` on a logarithmic scale — e.g. makeLogStep(19.7, 20160, 300) * gives ~300 points across a 20 Hz - 20 kHz range, with step size growing * proportionally to the current value (fine resolution at low frequencies, * coarser at high ones — matches how the ear perceives frequency). * * This is an approximation used to size keyboard/wheel nudges — it does NOT * guarantee landing on the same exact grid a real device would produce. * Pair it with `quantize` (see makeLogQuantize) when you need the slider to * always land exactly on the device's own value set. */ export function makeLogStep(min: number, max: number, points: number): StepFn { const ratio = Math.pow(max / min, 1 / Math.max(1, points)); const stepSize = ratio - 1; return (value: number) => Math.max(min, value) * stepSize; } /** * Builds a QuantizeFn that snaps to the exact same log-spaced grid a device * using a `raw` 0..points index would produce, e.g. for a frequency raw * value stored as: * raw = round(log(Hz / min) / log(max / min) * points) * Hz = min * (max / min) ** (raw / points) * makeLogQuantize(19.7, 20160, 300) reproduces exactly that 301-point set * (raw 0..300), so the slider only ever settles on values the device itself * would encode/decode to — no drift from an approximate step size. */ export function makeLogQuantize(min: number, max: number, points: number): QuantizeFn { const logRatio = Math.log(max / min); return (value: number) => { const v = Math.max(min, Math.min(max, value)); const raw = Math.round((Math.log(v / min) / logRatio) * points); const clampedRaw = Math.min(points, Math.max(0, raw)); return min * Math.pow(max / min, clampedRaw / points); }; } export default function VerticalSlider({ min, max, step = defaultStep, quantize, values, value, onChange, onInput, unit = '', formatValue, showTicks = true, scale = 'linear', disabled = false, className, style, }: VerticalSliderProps) { const [editingText, setEditingText] = useState(null); const [displayValue, setDisplayValue] = useState(value); const [tickCount, setTickCount] = useState(MIN_TICKS); const inputRef = useRef(null); const sliderRef = useRef(null); const trackRef = useRef(null); const thumbRef = useRef(null); // --- shared interaction state (all three input methods use these) ------ /** Latest value shown locally. Source of truth for "where is the thumb right now". */ const latestValue = useRef(value); /** Always points at the latest `value` prop, safe to read from async code. */ const valueRef = useRef(value); valueRef.current = value; /** Always points at the latest `onChange`, so queued commits never use a stale closure. */ const onChangeRef = useRef(onChange); onChangeRef.current = onChange; const onInputRef = useRef(onInput); onInputRef.current = onInput; /** Last value the parent confirmed (or the last prop we synced from). Used to skip no-op commits. */ const lastCommitted = useRef(value); /** Newest value waiting to be sent. Newer values overwrite older ones (latest-wins). */ const pendingCommit = useRef(null); const commitInFlight = useRef(false); // --- per-input-method "is the user still doing something" flags -------- const dragging = useRef(false); const activePointerId = useRef(null); const pendingTouch = useRef<{ id: number; x: number; y: number } | null>(null); const keysHeld = useRef>(new Set()); const wheelTimeout = useRef | null>(null); if (scale === 'log' && !values && (min <= 0 || max <= 0)) { // eslint-disable-next-line no-console console.warn( 'VerticalSlider: scale="log" requires min > 0 and max > 0. Falling back to linear behavior for out-of-range bounds.' ); } // Slice the discrete value set down to the applicable [min, max] sub-range. // Falls back to the full array if the slice is empty (e.g. misconfigured bounds). const listValues = useMemo(() => { if (!values || values.length === 0) return null; const filtered = values.filter((v) => v >= min && v <= max); return filtered.length > 0 ? filtered : values; }, [values, min, max]); /** True while the user is mid-gesture or a commit is pending/in flight. */ function isBusy() { return ( dragging.current || keysHeld.current.size > 0 || wheelTimeout.current !== null || commitInFlight.current || pendingCommit.current !== null ); } /** Same as isBusy() but ignores commit state: is the user's hand still on the control? */ function isUserActive() { return dragging.current || keysHeld.current.size > 0 || wheelTimeout.current !== null; } function rollbackToProp() { const v = valueRef.current; latestValue.current = v; lastCommitted.current = v; setDisplayValue(v); onInputRef.current?.(v); } /** * Single serialized commit pipeline shared by drag, keyboard, wheel and text entry. * * - Only one onChange is ever in flight. * - While one is in flight, newer values just overwrite `pendingCommit` * (latest-wins); the loop picks them up as soon as the current call returns. * - Nothing here clears per-gesture state, so a slow commit can never * clobber a gesture that started after it was sent. * - Rollback only happens once the queue is drained, the last commit * failed, and the user isn't touching the control anymore. */ async function flushCommits() { if (commitInFlight.current) return; commitInFlight.current = true; let lastFailed = false; try { while (pendingCommit.current !== null) { const sent = pendingCommit.current; pendingCommit.current = null; if (sent === lastCommitted.current) { lastFailed = false; continue; } let success: boolean | undefined; try { success = await onChangeRef.current?.(sent); } catch { success = false; } if (success === false) { lastFailed = true; } else { lastFailed = false; lastCommitted.current = sent; } } } finally { commitInFlight.current = false; } if (lastFailed && !isUserActive() && pendingCommit.current === null) { rollbackToProp(); } } function enqueueCommit(next: number) { pendingCommit.current = next; void flushCommits(); } /** Commits whatever the thumb currently shows, if it differs from what the parent last confirmed. */ function commitLatestIfChanged() { if (latestValue.current !== lastCommitted.current) { enqueueCommit(latestValue.current); } } // Sync from the `value` prop only when the user isn't interacting, so stale // echoes from a slow round trip can't yank the thumb backwards. useEffect(() => { if (isBusy() || editingText !== null) return; latestValue.current = value; lastCommitted.current = value; setDisplayValue(value); // eslint-disable-next-line react-hooks/exhaustive-deps }, [value]); useEffect(() => { const el = trackRef.current; if (!el || typeof ResizeObserver === 'undefined') return; const recompute = () => { const h = el.clientHeight; if (!h) return; const n = Math.max(MIN_TICKS, Math.ceil(h / MAX_TICK_SPACING_PX) + 1); setTickCount(n); }; recompute(); const observer = new ResizeObserver(recompute); observer.observe(el); return () => observer.disconnect(); }, []); useEffect(() => { if (!disabled) return; dragging.current = false; activePointerId.current = null; pendingTouch.current = null; keysHeld.current.clear(); pendingCommit.current = null; if (wheelTimeout.current) { clearTimeout(wheelTimeout.current); wheelTimeout.current = null; } setEditingText(null); setDisplayValue(value); latestValue.current = value; onInput?.(value); // eslint-disable-next-line react-hooks/exhaustive-deps }, [disabled]); useEffect(() => { return () => { if (wheelTimeout.current) clearTimeout(wheelTimeout.current); }; }, []); const decimals = useMemo(() => { if (listValues) return Math.min(3, getDecimals(displayValue)); return Math.min(3, getDecimals(step(displayValue))); }, [listValues, step, displayValue]); const formattedValue = (formatValue ?? formatValueDefault)(displayValue, decimals); const displayUnit = typeof unit === 'function' ? unit(displayValue) : unit; function normalizeValue(input: number) { const clamped = Math.min(max, Math.max(min, input)); if (listValues) { return listValues[closestIndex(listValues, clamped)]; } if (quantize) { return Number(Math.min(max, Math.max(min, quantize(clamped))).toFixed(6)); } const currentStep = step(clamped); const snapped = min + Math.round((clamped - min) / currentStep) * currentStep; return Number(Math.min(max, Math.max(min, snapped)).toFixed(6)); } /** Updates the local (optimistic) value only. Does not commit. */ function updateValue(input: number) { const next = normalizeValue(input); latestValue.current = next; setDisplayValue(next); onInputRef.current?.(next); } /** Returns the value one step up (+1) or down (-1) from `base`. */ function nudge(base: number, direction: 1 | -1) { if (listValues) { const idx = closestIndex(listValues, base); const nextIdx = Math.min(listValues.length - 1, Math.max(0, idx + direction)); return listValues[nextIdx]; } return normalizeValue(base + direction * step(base)); } // --- keyboard ---------------------------------------------------------- function handleKeyDown(e: React.KeyboardEvent) { if (disabled) return; if (!NAV_KEYS.includes(e.key)) return; e.preventDefault(); keysHeld.current.add(e.key); const direction: 1 | -1 = e.key === 'ArrowUp' || e.key === 'ArrowRight' ? 1 : -1; // Base off our own latest local value, never the `value` prop: the prop // may still be stale if a previous commit hasn't round-tripped yet. updateValue(nudge(latestValue.current, direction)); } function handleKeyUp(e: React.KeyboardEvent) { if (disabled) return; if (!NAV_KEYS.includes(e.key)) return; keysHeld.current.delete(e.key); // Commit once every arrow key has been released. if (keysHeld.current.size === 0) { commitLatestIfChanged(); } } function handleSliderBlur() { // A keyup can be lost if focus leaves while a key is held. Treat blur as release. if (keysHeld.current.size > 0) { keysHeld.current.clear(); } if (!dragging.current) commitLatestIfChanged(); } // --- wheel ------------------------------------------------------------- function handleWheel(e: WheelEvent) { if (disabled) return; e.preventDefault(); // deltaY < 0 means scrolling up/away from the user — treat that as // increasing the value, matching the vertical slider's "up = more". const direction: 1 | -1 = e.deltaY < 0 ? 1 : -1; updateValue(nudge(latestValue.current, direction)); if (wheelTimeout.current) clearTimeout(wheelTimeout.current); wheelTimeout.current = setTimeout(() => { wheelTimeout.current = null; commitLatestIfChanged(); }, WHEEL_COMMIT_DELAY_MS); } useEffect(() => { const el = sliderRef.current; if (!el) return; // React attaches onWheel passively by default, so preventDefault() // wouldn't stop the page from scrolling underneath the slider — attach // natively with { passive: false } instead. el.addEventListener('wheel', handleWheel, { passive: false }); return () => el.removeEventListener('wheel', handleWheel); }); // --- pointer / mouse --------------------------------------------------- function handlePointerMove(e: React.PointerEvent) { const pending = pendingTouch.current; if (pending && e.pointerId === pending.id) { const dx = e.clientX - pending.x; const dy = e.clientY - pending.y; if (Math.abs(dx) < TOUCH_INTENT_PX && Math.abs(dy) < TOUCH_INTENT_PX) return; pendingTouch.current = null; if (Math.abs(dy) > Math.abs(dx)) { // Vertical intent: start the drag now dragging.current = true; activePointerId.current = e.pointerId; e.currentTarget.setPointerCapture(e.pointerId); valueFromPointer(e.clientY); } // Horizontal intent: do nothing, the browser scrolls the strip return; } if (!dragging.current || e.pointerId !== activePointerId.current) return; valueFromPointer(e.clientY); } function valueFromPointer(clientY: number) { if (!sliderRef.current) return; const rect = sliderRef.current.getBoundingClientRect(); const percent = 1 - (clientY - rect.top) / rect.height; const raw = percentToValue(Math.min(1, Math.max(0, percent)), min, max, scale, listValues); updateValue(raw); } function startDrag(e: React.PointerEvent) { if (disabled) return; // Touch: don't move anything yet. Wait to see if the gesture is vertical // (fader) or horizontal (the strip scrolling). if (e.pointerType === 'touch') { if (dragging.current || pendingTouch.current) return; pendingTouch.current = { id: e.pointerId, x: e.clientX, y: e.clientY }; return; } if (e.pointerType === 'mouse' && e.button !== 0) return; // Ignore a second pointer (multi-touch) while one is already dragging. if (dragging.current) return; const target = e.currentTarget; dragging.current = true; activePointerId.current = e.pointerId; target.setPointerCapture(e.pointerId); valueFromPointer(e.clientY); } function endDrag(e: React.PointerEvent) { if (pendingTouch.current?.id === e.pointerId) { pendingTouch.current = null; return; } if (!dragging.current || e.pointerId !== activePointerId.current) return; // Release the gesture synchronously. The old code awaited onChange first, // so a quick second click could start a new drag that the first drag's // late cleanup then cancelled (dragging = false) mid-gesture. dragging.current = false; activePointerId.current = null; const target = e.currentTarget; if (target.hasPointerCapture(e.pointerId)) { target.releasePointerCapture(e.pointerId); } commitLatestIfChanged(); } // --- text input -------------------------------------------------------- function commitEditing() { const text = editingText; setEditingText(null); if (disabled) return; if (text === null || text === '' || text === '-') return; const parsed = Number(text); if (Number.isNaN(parsed)) return; updateValue(parsed); commitLatestIfChanged(); } const percent = valueToPercent(displayValue, min, max, scale, listValues); return (
{showTicks && (
{Array.from({ length: tickCount }).map((_, i) => ( ))}
)}
{showTicks && (
{Array.from({ length: tickCount }).map((_, i) => ( ))}
)}
setEditingText(displayValue.toFixed(decimals))} // plain number while editing onChange={(e) => setEditingText(e.target.value)} onBlur={commitEditing} onKeyDown={(e) => { if (e.key === 'Enter') inputRef.current?.blur(); if (e.key === 'Escape') { setEditingText(null); inputRef.current?.blur(); } }} /> {displayUnit && {' ' + displayUnit}}
); }