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
+234 -15
View File
@@ -4,11 +4,18 @@ import { createPortal } from 'react-dom';
import { TriangleDownIcon } from '../../assets/icons/Triangle';
import './ChoiceSelect.css';
type CommitResult = Promise<boolean | void> | boolean | void;
type ChoiceSelectProps<T extends string> = {
value: T;
options: readonly T[];
formatLabel?: (value: T) => string;
onChange: (value: T) => void;
/**
* May be sync or async. Returning (or resolving to) `false` means the change
* was rejected and the select rolls back to the current `value` prop.
* Plain `void` handlers keep working exactly as before.
*/
onChange: (value: T) => CommitResult;
id?: string;
disabled?: boolean;
className?: string;
@@ -17,9 +24,34 @@ type ChoiceSelectProps<T extends string> = {
const LISTBOX_MAX_HEIGHT = 240; // keep in sync with .choice-select__listbox max-height
const LISTBOX_GAP = 4; // px, ~= var(--space-1)
const WHEEL_COMMIT_DELAY = 250;
// Safety net: if the parent's `value` prop never comes back exactly equal
// to what we committed (rounding, an intermediate transform, etc.), stop
// waiting after this long so the select doesn't get stuck ignoring
// external updates.
const PENDING_FALLBACK_MS = 1000;
type Coords = { top: number; left: number; width: number; fontSize: number };
function useNonPassiveWheel(
ref: React.RefObject<HTMLElement | null>,
handler: (e: WheelEvent) => void
) {
const handlerRef = useRef(handler);
handlerRef.current = handler;
useEffect(() => {
const el = ref.current;
if (!el) return;
// React attaches onWheel passively, so preventDefault() would not stop
// the page from scrolling underneath — attach natively instead.
const listener = (e: WheelEvent) => handlerRef.current(e);
el.addEventListener('wheel', listener, { passive: false });
return () => el.removeEventListener('wheel', listener);
}, [ref]);
}
function ChoiceSelect<T extends string>({
value,
options,
@@ -34,12 +66,183 @@ function ChoiceSelect<T extends string>({
const [highlight, setHighlight] = useState(0);
const [dropUp, setDropUp] = useState(false);
const [coords, setCoords] = useState<Coords | null>(null);
/** What the user currently sees. May be ahead of the `value` prop while a commit is in flight. */
const [displayValue, setDisplayValue] = useState<T>(value);
const rootRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const listboxRef = useRef<HTMLUListElement>(null);
const suppressNextClick = useRef(false);
// --- commit pipeline state (same model as VerticalSlider / ChoiceStepper) ---
// Latest-value refs, safe to read from async code and timers.
const valueRef = useRef(value);
valueRef.current = value;
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
/** Source of truth for stepping: what the user currently sees. */
const latest = useRef<T>(value);
/** Last value the parent accepted (or the last prop we synced from). */
const lastCommitted = useRef<T>(value);
/** Newest value waiting to be sent (latest-wins). */
const pending = useRef<{ v: T } | null>(null);
const commitInFlight = useRef(false);
const wheelTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
// Waiting for the prop to echo what we committed.
const echoWait = useRef(false);
const echoFallbackTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const userActive = () => wheelTimeout.current !== null;
function releaseEcho() {
echoWait.current = false;
if (echoFallbackTimeout.current) {
clearTimeout(echoFallbackTimeout.current);
echoFallbackTimeout.current = null;
}
}
function startEchoWait() {
echoWait.current = true;
if (echoFallbackTimeout.current) clearTimeout(echoFallbackTimeout.current);
echoFallbackTimeout.current = setTimeout(() => {
echoWait.current = false;
echoFallbackTimeout.current = null;
}, PENDING_FALLBACK_MS);
}
/** Optimistic local update. Does not commit. */
function preview(next: T) {
latest.current = next;
setDisplayValue(next);
}
function rollbackToProp() {
const v = valueRef.current;
latest.current = v;
lastCommitted.current = v;
setDisplayValue(v);
}
/**
* Only one onChange is ever in flight. Newer values overwrite `pending`
* (latest-wins) and are sent as soon as the current call returns. Nothing
* after an `await` touches per-gesture state, so a slow commit can't
* clobber a wheel gesture that started after it was sent.
*/
async function flushCommits() {
if (commitInFlight.current) return;
commitInFlight.current = true;
releaseEcho();
let lastFailed = false;
try {
while (pending.current !== null) {
const sent = pending.current.v;
pending.current = null;
if (Object.is(sent, lastCommitted.current)) {
lastFailed = false;
continue;
}
let result: boolean | void;
try {
result = await onChangeRef.current(sent);
} catch {
result = false;
}
if (result === false) {
lastFailed = true;
} else {
lastFailed = false;
lastCommitted.current = sent;
}
}
} finally {
commitInFlight.current = false;
}
// If the wheel is still turning, its debounce will trigger the next commit.
if (userActive() || pending.current !== null) return;
if (lastFailed) {
rollbackToProp();
} else if (Object.is(valueRef.current, lastCommitted.current)) {
releaseEcho();
} else {
startEchoWait();
}
}
/** Commits whatever the user currently sees, if it differs from what the parent last accepted. */
function commitLatest() {
if (Object.is(latest.current, lastCommitted.current)) return;
pending.current = { v: latest.current };
void flushCommits();
}
function scheduleWheelCommit() {
if (wheelTimeout.current) clearTimeout(wheelTimeout.current);
wheelTimeout.current = setTimeout(() => {
wheelTimeout.current = null;
commitLatest();
}, WHEEL_COMMIT_DELAY);
}
// Sync from the `value` prop only when the user isn't interacting and no
// commit is pending, so stale echoes can't yank the display backwards.
useEffect(() => {
if (commitInFlight.current || pending.current !== null || userActive()) return;
if (echoWait.current) {
// Only release once the prop actually caught up to what we committed.
if (Object.is(value, lastCommitted.current)) {
releaseEcho();
} else {
return;
}
}
latest.current = value;
lastCommitted.current = value;
setDisplayValue(value);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]);
// When disabled, drop any in-progress interaction, close the list and show the real value.
useEffect(() => {
if (!disabled) return;
pending.current = null;
if (wheelTimeout.current) {
clearTimeout(wheelTimeout.current);
wheelTimeout.current = null;
}
releaseEcho();
setOpen(false);
const v = valueRef.current;
latest.current = v;
lastCommitted.current = v;
setDisplayValue(v);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [disabled]);
useEffect(() => {
return () => {
if (wheelTimeout.current) clearTimeout(wheelTimeout.current);
if (echoFallbackTimeout.current) clearTimeout(echoFallbackTimeout.current);
};
}, []);
// --- outside click ------------------------------------------------------
useEffect(() => {
function handleMouseDown(e: MouseEvent) {
const target = e.target as Node;
@@ -85,13 +288,29 @@ function ChoiceSelect<T extends string>({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
// --- wheel on the trigger ----------------------------------------------
/** Steps from the latest local value (not the `value` prop), wrapping around. */
const step = (direction: 1 | -1) => {
const currentIndex = options.indexOf(value);
if (currentIndex === -1 || options.length === 0) return;
const currentIndex = options.indexOf(latest.current);
if (currentIndex === -1 || options.length === 0) return false;
const nextIndex = (currentIndex + direction + options.length) % options.length;
onChange(options[nextIndex]);
preview(options[nextIndex]);
return true;
};
useNonPassiveWheel(triggerRef, (e) => {
e.preventDefault();
if (disabled) return;
const direction = e.deltaY < 0 ? -1 : e.deltaY > 0 ? 1 : 0;
if (direction === 0) return;
if (step(direction)) scheduleWheelCommit();
});
// --- list ---------------------------------------------------------------
function updatePlacement() {
const el = triggerRef.current;
if (!el) return;
@@ -119,12 +338,18 @@ function ChoiceSelect<T extends string>({
if (disabled) return;
updatePlacement();
setOpen(true);
const idx = options.indexOf(value);
const idx = options.indexOf(latest.current);
setHighlight(idx >= 0 ? idx : 0);
}
function pick(opt: T) {
if (opt !== value) onChange(opt);
if (!Object.is(opt, latest.current)) {
preview(opt);
commitLatest();
} else {
// Picking the already-shown value still flushes any wheel change that is waiting on its debounce.
commitLatest();
}
setOpen(false);
triggerRef.current?.focus();
}
@@ -170,17 +395,11 @@ function ChoiceSelect<T extends string>({
className={'choice-select__trigger' + (open ? ' choice-select__trigger--open' : '')}
onClick={() => (open ? setOpen(false) : openList())}
onKeyDown={handleKeyDown}
onWheel={(e) => {
e.preventDefault();
if (disabled) return;
if (e.deltaY < 0) step(-1);
else if (e.deltaY > 0) step(1);
}}
disabled={disabled}
aria-haspopup="listbox"
aria-expanded={open}
>
<span className="choice-select__label">{formatLabel(value)}</span>
<span className="choice-select__label">{formatLabel(displayValue)}</span>
<span className="choice-select__chevron" aria-hidden="true">
<TriangleDownIcon />
</span>
@@ -210,10 +429,10 @@ function ChoiceSelect<T extends string>({
<li
key={option}
role="option"
aria-selected={option === value}
aria-selected={option === displayValue}
className={
'choice-select__option' +
(option === value ? ' choice-select__option--selected' : '') +
(option === displayValue ? ' choice-select__option--selected' : '') +
(i === highlight ? ' choice-select__option--highlight' : '')
}
onMouseEnter={() => setHighlight(i)}
+337 -285
View File
@@ -11,6 +11,7 @@ const WHEEL_COMMIT_DELAY = 250;
const PENDING_FALLBACK_MS = 1000;
type CommitResult = Promise<boolean | void> | boolean | void;
type Direction = 1 | -1;
function useNonPassiveWheel(
ref: React.RefObject<HTMLElement | null>,
@@ -64,6 +65,310 @@ function StepperArrows({
);
}
// ---- Shared core (all interaction + commit logic lives here) ----
type StepperCoreProps<T> = {
value: T;
onChange: (value: T) => CommitResult;
formatLabel: (value: T) => string;
/** Next value one step from `base`, or null if there is nowhere to go. */
getNext: (base: T, direction: Direction) => T | null;
/** Whether the arrow in `direction` should be enabled for `current`. */
canStep: (current: T, direction: Direction) => boolean;
/** Parses typed text into a value, or null if it isn't valid. */
parseText: (text: string) => T | null;
id?: string;
disabled?: boolean;
className?: string;
};
/**
* One serialized commit pipeline shared by arrows, keyboard, wheel and typed text.
*
* - `latest` is the value the user currently sees; every step is computed
* from it (never from a render closure or the `value` prop), so rapid
* events before a re-render can't lose steps.
* - Only one `onChange` is ever in flight. Newer values overwrite `pending`
* (latest-wins) and are sent as soon as the current call returns.
* - No cleanup after an `await` touches per-gesture state, so a slow commit
* can never cancel a gesture that started after it was sent.
* - After a successful drain we keep showing the local value until the
* `value` prop echoes it back (or a fallback timer expires), so the old
* value never blinks back in.
* - Rollback happens only when the last commit failed, the queue is empty and
* the user isn't touching the control, and it rolls back to the *current*
* prop (read from a ref, not a stale closure).
*/
function StepperCore<T>({
value,
onChange,
formatLabel,
getNext,
canStep,
parseText,
id,
disabled,
className,
}: StepperCoreProps<T>) {
const [localValue, setLocalValue] = useState(value);
const [text, setText] = useState(formatLabel(value));
const inputRef = useRef<HTMLInputElement>(null);
// Latest-value refs, safe to read from async code and timers.
const valueRef = useRef(value);
valueRef.current = value;
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
const formatLabelRef = useRef(formatLabel);
formatLabelRef.current = formatLabel;
/** What the user currently sees. Source of truth for stepping. */
const latest = useRef(value);
/** Last value the parent accepted (or the last prop we synced from). */
const lastCommitted = useRef(value);
/** Newest value waiting to be sent (latest-wins). */
const pending = useRef<{ v: T } | null>(null);
const commitInFlight = useRef(false);
// "Is the user still doing something" flags.
const keysHeld = useRef<Set<string>>(new Set());
const wheelTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const typing = useRef(false);
// Waiting for the prop to echo what we committed.
const echoWait = useRef(false);
const echoFallbackTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const userActive = () => keysHeld.current.size > 0 || wheelTimeout.current !== null;
function releaseEcho() {
echoWait.current = false;
if (echoFallbackTimeout.current) {
clearTimeout(echoFallbackTimeout.current);
echoFallbackTimeout.current = null;
}
}
function startEchoWait() {
echoWait.current = true;
if (echoFallbackTimeout.current) clearTimeout(echoFallbackTimeout.current);
echoFallbackTimeout.current = setTimeout(() => {
echoWait.current = false;
echoFallbackTimeout.current = null;
}, PENDING_FALLBACK_MS);
}
/** Optimistic local update. Does not commit. */
function preview(next: T) {
typing.current = false;
latest.current = next;
setLocalValue(next);
setText(formatLabelRef.current(next));
}
function rollbackToProp() {
const v = valueRef.current;
typing.current = false;
latest.current = v;
lastCommitted.current = v;
setLocalValue(v);
setText(formatLabelRef.current(v));
}
async function flushCommits() {
if (commitInFlight.current) return;
commitInFlight.current = true;
releaseEcho();
let lastFailed = false;
try {
while (pending.current !== null) {
const sent = pending.current.v;
pending.current = null;
if (Object.is(sent, lastCommitted.current)) {
lastFailed = false;
continue;
}
let result: boolean | void;
try {
result = await onChangeRef.current(sent);
} catch {
result = false;
}
if (result === false) {
lastFailed = true;
} else {
lastFailed = false;
lastCommitted.current = sent;
}
}
} finally {
commitInFlight.current = false;
}
// If the user is still mid-gesture, their release will trigger the next commit.
if (userActive() || pending.current !== null) return;
if (lastFailed) {
rollbackToProp();
} else if (Object.is(valueRef.current, lastCommitted.current)) {
releaseEcho();
} else {
startEchoWait();
}
}
/** Commits whatever the user currently sees, if it differs from what the parent last accepted. */
function commitLatest() {
if (Object.is(latest.current, lastCommitted.current)) return;
pending.current = { v: latest.current };
void flushCommits();
}
function step(direction: Direction): T | null {
const next = getNext(latest.current, direction);
if (next === null) return null;
preview(next);
return next;
}
function scheduleWheelCommit() {
if (wheelTimeout.current) clearTimeout(wheelTimeout.current);
wheelTimeout.current = setTimeout(() => {
wheelTimeout.current = null;
commitLatest();
}, WHEEL_COMMIT_DELAY);
}
useNonPassiveWheel(inputRef, (e) => {
if (disabled) return;
e.preventDefault();
const direction: Direction | 0 = e.deltaY < 0 ? 1 : e.deltaY > 0 ? -1 : 0;
if (direction === 0) return;
if (step(direction) !== null) scheduleWheelCommit();
});
// Sync from the `value` prop only when the user isn't interacting and no
// commit is pending, so stale echoes can't yank the display backwards.
useEffect(() => {
if (commitInFlight.current || pending.current !== null || userActive()) return;
if (echoWait.current) {
// Only release once the prop actually caught up to what we committed.
if (Object.is(value, lastCommitted.current)) {
releaseEcho();
} else {
return;
}
}
if (typing.current) return;
latest.current = value;
lastCommitted.current = value;
setLocalValue(value);
setText(formatLabel(value));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value, formatLabel]);
// When disabled, drop any in-progress interaction and show the real value.
useEffect(() => {
if (!disabled) return;
keysHeld.current.clear();
pending.current = null;
typing.current = false;
if (wheelTimeout.current) {
clearTimeout(wheelTimeout.current);
wheelTimeout.current = null;
}
releaseEcho();
const v = valueRef.current;
latest.current = v;
lastCommitted.current = v;
setLocalValue(v);
setText(formatLabelRef.current(v));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [disabled]);
useEffect(() => {
return () => {
if (wheelTimeout.current) clearTimeout(wheelTimeout.current);
if (echoFallbackTimeout.current) clearTimeout(echoFallbackTimeout.current);
};
}, []);
const commitText = () => {
// A keyup can be lost if focus leaves while a key is held; treat blur as release.
keysHeld.current.clear();
const wasTyping = typing.current;
typing.current = false;
if (wasTyping) {
const parsed = parseText(text);
if (parsed !== null) {
preview(parsed);
} else {
setText(formatLabelRef.current(latest.current));
}
}
commitLatest();
};
const stepAndCommit = (direction: Direction) => {
if (step(direction) !== null) commitLatest();
};
return (
<div className={`choice-stepper ${className ?? ''}`} data-disabled={disabled || undefined}>
<input
ref={inputRef}
id={id}
className="choice-stepper__input"
value={text}
disabled={disabled}
onChange={(e) => {
typing.current = true;
setText(e.target.value);
}}
onBlur={commitText}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.currentTarget.blur();
} else if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
keysHeld.current.add(e.key);
step(e.key === 'ArrowUp' ? 1 : -1);
}
}}
onKeyUp={(e) => {
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return;
keysHeld.current.delete(e.key);
// Commit once every arrow key has been released.
if (keysHeld.current.size === 0) commitLatest();
}}
/>
<StepperArrows
onUp={() => stepAndCommit(1)}
onDown={() => stepAndCommit(-1)}
canUp={canStep(localValue, 1)}
canDown={canStep(localValue, -1)}
disabled={disabled}
/>
</div>
);
}
// ---- List variant ----
type ChoiceStepperListProps<T> = {
@@ -85,162 +390,31 @@ function ChoiceStepperList<T>({
disabled,
className,
}: ChoiceStepperListProps<T>) {
const [localValue, setLocalValue] = useState(value);
const [text, setText] = useState(formatLabel(value));
// True from the moment a commit starts until the prop `value` we get from
// the parent actually reflects it (not just until onChange resolves —
// those are two different moments and the gap between them is what was
// causing the old-value blink).
const interacting = useRef(false);
// The value we're waiting to see echoed back via the `value` prop.
const pendingValue = useRef<T | null>(null);
const wheelTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const fallbackTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
useNonPassiveWheel(inputRef, (e) => {
e.preventDefault();
if (e.deltaY < 0 && canUp) {
stepWheel(1);
} else if (e.deltaY > 0 && canDown) {
stepWheel(-1);
}
});
useEffect(() => {
if (interacting.current) {
// Only release control once the prop actually catches up to what we
// committed — otherwise keep showing localValue as-is (no flash back
// to the stale old value in between).
if (pendingValue.current !== null && Object.is(value, pendingValue.current)) {
interacting.current = false;
pendingValue.current = null;
if (fallbackTimeout.current) clearTimeout(fallbackTimeout.current);
} else {
return;
}
}
setLocalValue(value);
setText(formatLabel(value));
}, [value, formatLabel]);
useEffect(() => {
return () => {
if (wheelTimeout.current) clearTimeout(wheelTimeout.current);
if (fallbackTimeout.current) clearTimeout(fallbackTimeout.current);
};
}, []);
const index = values.indexOf(localValue);
const canUp = index === -1 || index < values.length - 1;
const canDown = index > 0;
const stepLocal = (direction: 1 | -1): T | null => {
const currentIndex = values.indexOf(localValue);
if (currentIndex === -1) return null;
const nextIndex = currentIndex + direction;
if (nextIndex < 0 || nextIndex >= values.length) return null;
const next = values[nextIndex];
setLocalValue(next);
setText(formatLabel(next));
return next;
};
async function commit(next: T) {
interacting.current = true;
pendingValue.current = next;
const result = await onChange(next);
if (result === false) {
interacting.current = false;
pendingValue.current = null;
if (fallbackTimeout.current) clearTimeout(fallbackTimeout.current);
setLocalValue(value);
setText(formatLabel(value));
return;
}
// Accepted: don't clear `interacting` here. Wait for the prop-sync
// effect above to see `value === next` and release it, so we never
// hand control back to a still-stale prop. Guard with a timeout in
// case it never matches exactly.
if (fallbackTimeout.current) clearTimeout(fallbackTimeout.current);
fallbackTimeout.current = setTimeout(() => {
interacting.current = false;
pendingValue.current = null;
}, PENDING_FALLBACK_MS);
}
const stepAndCommit = (direction: 1 | -1) => {
const next = stepLocal(direction);
if (next !== null) void commit(next);
};
const stepWheel = (direction: 1 | -1) => {
const next = stepLocal(direction);
if (next === null) return;
interacting.current = true;
if (wheelTimeout.current) clearTimeout(wheelTimeout.current);
wheelTimeout.current = setTimeout(() => {
wheelTimeout.current = null;
void commit(next);
}, WHEEL_COMMIT_DELAY);
};
const commitText = () => {
const match = values.find(
(v) => formatLabel(v).trim().toLowerCase() === text.trim().toLowerCase()
);
if (match !== undefined) {
setLocalValue(match);
void commit(match);
} else {
setText(formatLabel(value));
}
};
return (
<div className={`choice-stepper ${className ?? ''}`} data-disabled={disabled || undefined}>
<input
ref={inputRef}
<StepperCore<T>
value={value}
onChange={onChange}
formatLabel={formatLabel}
id={id}
className="choice-stepper__input"
value={text}
disabled={disabled}
onChange={(e) => setText(e.target.value)}
onBlur={commitText}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.currentTarget.blur();
} else if (e.key === 'ArrowUp') {
e.preventDefault();
interacting.current = true;
stepLocal(1);
} else if (e.key === 'ArrowDown') {
e.preventDefault();
interacting.current = true;
stepLocal(-1);
}
className={className}
getNext={(base, direction) => {
const i = values.indexOf(base);
if (i === -1) return null;
const n = i + direction;
return n < 0 || n >= values.length ? null : values[n];
}}
onKeyUp={(e) => {
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return;
void commit(localValue);
canStep={(current, direction) => {
const i = values.indexOf(current);
if (direction === 1) return i === -1 || i < values.length - 1;
return i > 0;
}}
parseText={(t) => {
const wanted = t.trim().toLowerCase();
const match = values.find((v) => formatLabel(v).trim().toLowerCase() === wanted);
return match === undefined ? null : match;
}}
/>
<StepperArrows
onUp={() => stepAndCommit(1)}
onDown={() => stepAndCommit(-1)}
canUp={canUp}
canDown={canDown}
disabled={disabled}
/>
</div>
);
}
@@ -269,149 +443,27 @@ function ChoiceStepperRange({
disabled,
className,
}: ChoiceStepperRangeProps) {
const [localValue, setLocalValue] = useState(value);
const [text, setText] = useState(formatLabel(value));
const interacting = useRef(false);
const pendingValue = useRef<number | null>(null);
const wheelTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const fallbackTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
useNonPassiveWheel(inputRef, (e) => {
e.preventDefault();
if (e.deltaY < 0 && canUp) {
stepWheel(1);
} else if (e.deltaY > 0 && canDown) {
stepWheel(-1);
}
});
useEffect(() => {
if (interacting.current) {
if (pendingValue.current !== null && Object.is(value, pendingValue.current)) {
interacting.current = false;
pendingValue.current = null;
if (fallbackTimeout.current) clearTimeout(fallbackTimeout.current);
} else {
return;
}
}
setLocalValue(value);
setText(formatLabel(value));
}, [value, formatLabel]);
useEffect(() => {
return () => {
if (wheelTimeout.current) clearTimeout(wheelTimeout.current);
if (fallbackTimeout.current) clearTimeout(fallbackTimeout.current);
};
}, []);
const clamp = (n: number) => Math.min(max, Math.max(min, n));
const canUp = localValue < max;
const canDown = localValue > min;
const stepLocal = (direction: 1 | -1): number | null => {
const next = clamp(localValue + direction * stepSize);
if (next === localValue) return null;
setLocalValue(next);
setText(formatLabel(next));
return next;
};
async function commit(next: number) {
interacting.current = true;
pendingValue.current = next;
const result = await onChange(next);
if (result === false) {
interacting.current = false;
pendingValue.current = null;
if (fallbackTimeout.current) clearTimeout(fallbackTimeout.current);
setLocalValue(value);
setText(formatLabel(value));
return;
}
if (fallbackTimeout.current) clearTimeout(fallbackTimeout.current);
fallbackTimeout.current = setTimeout(() => {
interacting.current = false;
pendingValue.current = null;
}, PENDING_FALLBACK_MS);
}
const stepAndCommit = (direction: 1 | -1) => {
const next = stepLocal(direction);
if (next !== null) void commit(next);
};
const stepWheel = (direction: 1 | -1) => {
const next = stepLocal(direction);
if (next === null) return;
interacting.current = true;
if (wheelTimeout.current) clearTimeout(wheelTimeout.current);
wheelTimeout.current = setTimeout(() => {
wheelTimeout.current = null;
void commit(next);
}, WHEEL_COMMIT_DELAY);
};
const commitText = () => {
const parsed = Number(text);
if (Number.isFinite(parsed)) {
const next = clamp(parsed);
setLocalValue(next);
void commit(next);
} else {
setText(formatLabel(value));
}
};
return (
<div className={`choice-stepper ${className ?? ''}`} data-disabled={disabled || undefined}>
<input
ref={inputRef}
<StepperCore<number>
value={value}
onChange={onChange}
formatLabel={formatLabel}
id={id}
className="choice-stepper__input"
value={text}
disabled={disabled}
onChange={(e) => setText(e.target.value)}
onBlur={commitText}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.currentTarget.blur();
} else if (e.key === 'ArrowUp') {
e.preventDefault();
if (canUp) {
interacting.current = true;
stepLocal(1);
}
} else if (e.key === 'ArrowDown') {
e.preventDefault();
if (canDown) {
interacting.current = true;
stepLocal(-1);
}
}
className={className}
getNext={(base, direction) => {
const next = clamp(base + direction * stepSize);
return next === base ? null : next;
}}
onKeyUp={(e) => {
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return;
void commit(localValue);
canStep={(current, direction) => (direction === 1 ? current < max : current > min)}
parseText={(t) => {
if (t.trim() === '') return null;
const parsed = Number(t);
return Number.isFinite(parsed) ? clamp(parsed) : null;
}}
/>
<StepperArrows
onUp={() => stepAndCommit(1)}
onDown={() => stepAndCommit(-1)}
canUp={canUp}
canDown={canDown}
disabled={disabled}
/>
</div>
);
}
+208 -151
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);
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));
}
keyboardValue.current = next;
updateValue(next);
}
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) {
// --- text input --------------------------------------------------------
function commitEditing() {
const text = editingText;
setEditingText(null);
return;
}
if (editingText !== null && editingText !== '' && editingText !== '-') {
const parsed = Number(editingText);
if (disabled) return;
if (text === null || text === '' || text === '-') return;
if (!Number.isNaN(parsed)) {
const next = normalizeValue(parsed);
const parsed = Number(text);
if (Number.isNaN(parsed)) return;
setDisplayValue(next);
onInput?.(next);
const success = await onChange?.(next);
if (success === false) {
setDisplayValue(value);
dragValue.current = value;
onInput?.(value);
}
}
}
setEditingText(null);
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) => {