fix: remove rollback on rapid sliders changes

This commit is contained in:
2026-10-25 16:37:28 +01:00
parent e5a570c017
commit 4ca7410ad8
3 changed files with 794 additions and 466 deletions
+211 -154
View File
@@ -51,6 +51,8 @@ function formatValueDefault(v: number, decimals: number) {
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();
@@ -182,19 +184,38 @@ export default function VerticalSlider({
style,
}: VerticalSliderProps) {
const [editingText, setEditingText] = useState<string | null>(null);
const [displayValue, setDisplayValue] = useState(value);
const [tickCount, setTickCount] = useState(MIN_TICKS);
const inputRef = useRef<HTMLInputElement>(null);
const sliderRef = useRef<HTMLDivElement>(null);
const trackRef = useRef<HTMLDivElement>(null);
const keyboardValue = useRef<number | null>(null);
const [displayValue, setDisplayValue] = useState(value);
const dragValue = useRef(value);
const dragging = useRef(false);
const thumbRef = useRef<HTMLDivElement>(null);
const keyboardEditing = useRef(false);
const wheelValue = useRef<number | null>(null);
const wheelEditing = useRef(false);
const wheelCommitTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const [tickCount, setTickCount] = useState(MIN_TICKS);
// --- 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<number | null>(null);
const commitInFlight = useRef(false);
// --- per-input-method "is the user still doing something" flags --------
const dragging = useRef(false);
const activePointerId = useRef<number | null>(null);
const keysHeld = useRef<Set<string>>(new Set());
const wheelTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
if (scale === 'log' && !values && (min <= 0 || max <= 0)) {
// eslint-disable-next-line no-console
@@ -211,17 +232,100 @@ export default function VerticalSlider({
return filtered.length > 0 ? filtered : values;
}, [values, min, max]);
useEffect(() => {
if (
/** True while the user is mid-gesture or a commit is pending/in flight. */
function isBusy() {
return (
dragging.current ||
keyboardEditing.current ||
wheelEditing.current ||
editingText !== null
) {
return;
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);
dragValue.current = value;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]);
useEffect(() => {
@@ -248,22 +352,27 @@ export default function VerticalSlider({
if (!disabled) return;
dragging.current = false;
keyboardEditing.current = false;
keyboardValue.current = null;
wheelEditing.current = false;
wheelValue.current = null;
if (wheelCommitTimeout.current) {
clearTimeout(wheelCommitTimeout.current);
wheelCommitTimeout.current = null;
activePointerId.current = null;
keysHeld.current.clear();
pendingCommit.current = null;
if (wheelTimeout.current) {
clearTimeout(wheelTimeout.current);
wheelTimeout.current = null;
}
setEditingText(null);
setDisplayValue(value);
dragValue.current = 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)));
@@ -289,111 +398,75 @@ export default function VerticalSlider({
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);
dragValue.current = next;
latestValue.current = next;
setDisplayValue(next);
onInput?.(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<HTMLDivElement>) {
if (disabled) return;
if (!NAV_KEYS.includes(e.key)) return;
if (!['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
return;
}
keyboardEditing.current = true;
e.preventDefault();
keysHeld.current.add(e.key);
// Base off displayValue (our own last-known-good local state), not the
// `value` prop: if onChange's round trip through the parent/audio engine
// hasn't landed yet, `value` can still be stale, which made repeated
// key presses appear to snap back to the pre-press position.
const base = keyboardValue.current ?? displayValue;
let next: number;
if (listValues) {
const idx = closestIndex(listValues, base);
let nextIdx = idx;
if (e.key === 'ArrowUp' || e.key === 'ArrowRight')
nextIdx = Math.min(listValues.length - 1, idx + 1);
if (e.key === 'ArrowDown' || e.key === 'ArrowLeft') nextIdx = Math.max(0, idx - 1);
next = listValues[nextIdx];
} else {
const currentStep = step(base);
next = base;
if (e.key === 'ArrowUp' || e.key === 'ArrowRight') next += currentStep;
if (e.key === 'ArrowDown' || e.key === 'ArrowLeft') next -= currentStep;
next = normalizeValue(next);
}
keyboardValue.current = next;
updateValue(next);
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));
}
async function handleKeyUp() {
function handleKeyUp(e: React.KeyboardEvent<HTMLDivElement>) {
if (disabled) return;
if (!NAV_KEYS.includes(e.key)) return;
if (keyboardValue.current == null) return;
keysHeld.current.delete(e.key);
const next = keyboardValue.current;
const success = await onChange?.(next);
keyboardEditing.current = false;
keyboardValue.current = null;
if (success === false) {
setDisplayValue(value);
dragValue.current = value;
onInput?.(value);
// 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();
wheelEditing.current = true;
const base = wheelValue.current ?? displayValue;
// deltaY < 0 means scrolling up/away from the user — treat that as
// increasing the value, matching the vertical slider's "up = more".
const direction = e.deltaY < 0 ? 1 : -1;
const direction: 1 | -1 = e.deltaY < 0 ? 1 : -1;
updateValue(nudge(latestValue.current, direction));
let next: number;
if (listValues) {
const idx = closestIndex(listValues, base);
const nextIdx = Math.min(listValues.length - 1, Math.max(0, idx + direction));
next = listValues[nextIdx];
} else {
const currentStep = step(base);
next = normalizeValue(base + direction * currentStep);
}
wheelValue.current = next;
updateValue(next);
if (wheelCommitTimeout.current) clearTimeout(wheelCommitTimeout.current);
wheelCommitTimeout.current = setTimeout(() => {
void commitWheel();
}, 250);
}
async function commitWheel() {
if (wheelValue.current == null) return;
const next = wheelValue.current;
const success = await onChange?.(next);
wheelEditing.current = false;
wheelValue.current = null;
if (success === false) {
setDisplayValue(value);
dragValue.current = value;
onInput?.(value);
}
if (wheelTimeout.current) clearTimeout(wheelTimeout.current);
wheelTimeout.current = setTimeout(() => {
wheelTimeout.current = null;
commitLatestIfChanged();
}, WHEEL_COMMIT_DELAY_MS);
}
useEffect(() => {
@@ -407,82 +480,65 @@ export default function VerticalSlider({
return () => el.removeEventListener('wheel', handleWheel);
});
useEffect(() => {
return () => {
if (wheelCommitTimeout.current) clearTimeout(wheelCommitTimeout.current);
};
}, []);
// --- pointer / mouse ---------------------------------------------------
function valueFromPointer(clientY: number) {
if (!sliderRef.current) return;
const rect = sliderRef.current.getBoundingClientRect();
const percent = 1 - (clientY - rect.top) / rect.height;
const raw = percentToValue(percent, min, max, scale, listValues);
const raw = percentToValue(Math.min(1, Math.max(0, percent)), min, max, scale, listValues);
updateValue(raw);
}
function startDrag(e: React.PointerEvent<HTMLDivElement>) {
if (disabled) 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 handlePointerMove(e: React.PointerEvent<HTMLDivElement>) {
if (!dragging.current) return;
if (!dragging.current || e.pointerId !== activePointerId.current) return;
valueFromPointer(e.clientY);
}
async function endDrag(e: React.PointerEvent<HTMLDivElement>) {
if (!dragging.current) return;
function endDrag(e: React.PointerEvent<HTMLDivElement>) {
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;
const pointerId = e.pointerId;
const finalValue = dragValue.current;
const success = await onChange?.(finalValue);
dragging.current = false;
if (success === false) {
setDisplayValue(value);
dragValue.current = value;
onInput?.(value);
if (target.hasPointerCapture(e.pointerId)) {
target.releasePointerCapture(e.pointerId);
}
if (target.hasPointerCapture(pointerId)) {
target.releasePointerCapture(pointerId);
}
commitLatestIfChanged();
}
async function commitEditing() {
if (disabled) {
setEditingText(null);
return;
}
if (editingText !== null && editingText !== '' && editingText !== '-') {
const parsed = Number(editingText);
if (!Number.isNaN(parsed)) {
const next = normalizeValue(parsed);
setDisplayValue(next);
onInput?.(next);
const success = await onChange?.(next);
if (success === false) {
setDisplayValue(value);
dragValue.current = value;
onInput?.(value);
}
}
}
// --- 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);
@@ -515,6 +571,7 @@ export default function VerticalSlider({
tabIndex={disabled ? -1 : 0}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
onBlur={handleSliderBlur}
onPointerDown={startDrag}
onPointerMove={handlePointerMove}
onPointerUp={endDrag}
@@ -541,7 +598,7 @@ export default function VerticalSlider({
disabled={disabled}
value={editingText ?? formattedValue}
style={{ width: '100%' }}
onFocus={() => setEditingText(value.toFixed(decimals))} // plain number while editing
onFocus={() => setEditingText(displayValue.toFixed(decimals))} // plain number while editing
onChange={(e) => setEditingText(e.target.value)}
onBlur={commitEditing}
onKeyDown={(e) => {
@@ -556,4 +613,4 @@ export default function VerticalSlider({
</div>
</div>
);
}
}