feat(editor): send a slider drag when it settles, not step by step

A drag shows its own value and is sent after 250 ms without a change, or at
once on release; clicks and number-box commits still go at once.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
NiJingzhe
2026-10-20 23:45:59 +08:00
parent 3f5ee25e1c
commit 57418c27e0
7 changed files with 166 additions and 29 deletions
+12 -12
View File
@@ -19,6 +19,7 @@ import {
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { ParamControl, type ParamMeta, type ParamValue } from "@/components/ParamControl";
import { createSettler, SETTLE_MS } from "@/lib/settle";
import { cadTheme } from "@/lib/cm-theme";
import { sdkCompletion } from "@/lib/sdk-complete";
import { cn } from "@/lib/utils";
@@ -205,17 +206,16 @@ export function CellEditor({
);
};
// Forward slider bursts; the server coalesces (latest-wins rebuild).
const pendingParams = useRef(new Map<string, ParamValue>());
const paramTimer = useRef<number | null>(null);
const forwardParam = (id: string, value: ParamValue) => {
pendingParams.current.set(id, value);
if (paramTimer.current !== null) return;
paramTimer.current = window.setTimeout(() => {
paramTimer.current = null;
socket?.send({ type: "param.set", values: Object.fromEntries(pendingParams.current) });
pendingParams.current.clear();
}, 60);
// A drag is sent when it pauses or ends, not step by step: every value the
// server gets is a rebuild.
const socketRef = useRef(socket);
socketRef.current = socket;
const settler = useRef(
createSettler<ParamValue>(SETTLE_MS, (values) => socketRef.current?.send({ type: "param.set", values })),
);
const forwardParam = (id: string, value: ParamValue, now = false) => {
settler.current.push(id, value);
if (now) settler.current.flush();
};
// Disarm delete when clicking anywhere outside the armed button.
@@ -364,7 +364,7 @@ function CellBlock({
live: boolean;
armed: boolean;
socket: SocketLike;
forwardParam: (id: string, value: ParamValue) => void;
forwardParam: (id: string, value: ParamValue, now?: boolean) => void;
onToggle: () => void;
onRun: () => void;
onInterrupt: () => void;
+17 -10
View File
@@ -8,6 +8,7 @@ import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { ParamControl, type ParamMeta, type ParamValue } from "@/components/ParamControl";
import { cadTheme } from "@/lib/cm-theme";
import { createSettler, SETTLE_MS } from "@/lib/settle";
import { sdkCompletion } from "@/lib/sdk-complete";
/** A local module of the workspace (shared dimensions, helpers): what the
@@ -41,8 +42,17 @@ export function ModuleView({
const [draft, setDraft] = useState(module.code);
const dirty = useRef(false);
const saveTimer = useRef<number | null>(null);
const paramTimer = useRef<number | null>(null);
const pending = useRef(new Map<string, ParamValue>());
const socketRef = useRef(socket);
socketRef.current = socket;
const pathRef = useRef(module.path);
pathRef.current = module.path;
const settler = useRef(
createSettler<ParamValue>(SETTLE_MS, (values) =>
socketRef.current?.send({ type: "module.param", path: pathRef.current, values }),
),
);
// values of the module that was left are not the next one's
useEffect(() => () => settler.current.cancel(), [module.path]);
// A different module, an external edit or a parameter edit replaces the
// text; our own autosave echo must not clobber what is being typed.
@@ -68,14 +78,11 @@ export function ModuleView({
editRef.current = edit;
const handleChange = useCallback((value: string) => editRef.current(value), []);
const forward = (id: string, value: ParamValue) => {
pending.current.set(id, value);
if (paramTimer.current !== null) return;
paramTimer.current = window.setTimeout(() => {
paramTimer.current = null;
socket?.send({ type: "module.param", path: module.path, values: Object.fromEntries(pending.current) });
pending.current.clear();
}, 120);
// A drag is sent when it pauses or ends, not step by step: every value the
// server gets is a rebuild.
const forward = (id: string, value: ParamValue, now = false) => {
settler.current.push(id, value);
if (now) settler.current.flush();
};
const groups = new Map<string, ParamMeta[]>();
+21 -5
View File
@@ -30,8 +30,16 @@ export function ParamControl({
forwardParam,
}: {
param: ParamMeta;
forwardParam: (id: string, value: ParamValue) => void;
/** `now`: send at once (a click, a release) instead of when the changes settle. */
forwardParam: (id: string, value: ParamValue, now?: boolean) => void;
}) {
// A drag shows its own value: the server only hears of it when it settles,
// so the value it echoes back cannot move the thumb meanwhile.
const [drag, setDrag] = useState<number | null>(null);
const dragging = useRef(false);
useEffect(() => {
if (!dragging.current) setDrag(null);
}, [param.value]);
const label = param.label || param.id;
const title = [param.comment, ...(param.issues ?? [])].filter(Boolean).join("\n") || undefined;
const ink = param.modified ? "text-focus" : "text-name";
@@ -42,7 +50,7 @@ export function ParamControl({
type="button"
className="flex items-center justify-between gap-2 text-left text-[11px]"
title={title}
onClick={() => forwardParam(param.id, !on)}
onClick={() => forwardParam(param.id, !on, true)}
>
<span className={ink}>{label}</span>
<span className={cn("border-2 px-1.5 text-[10px] font-bold uppercase", on ? "border-primary bg-primary text-primary-foreground" : "border-input text-muted-foreground")}>
@@ -51,7 +59,7 @@ export function ParamControl({
</button>
);
}
const value = Number(param.value);
const value = drag ?? Number(param.value);
return (
<div title={title}>
<div className="mb-1 flex items-baseline justify-between gap-2 text-[11px]">
@@ -63,7 +71,7 @@ export function ParamControl({
min={param.min}
max={param.max}
step={param.step ?? (param.kind === "int" ? 1 : null)}
onCommit={(next) => forwardParam(param.id, next)}
onCommit={(next) => forwardParam(param.id, next, true)}
/>
) : (
<span>{value}</span>
@@ -78,7 +86,15 @@ export function ParamControl({
max={param.max}
modified={param.modified}
step={param.step ?? (param.kind === "int" ? 1 : (param.max - param.min) / 200)}
onValueChange={([next]) => forwardParam(param.id, next)}
onValueChange={([next]) => {
dragging.current = true;
setDrag(next);
forwardParam(param.id, next);
}}
onValueCommit={([next]) => {
dragging.current = false;
forwardParam(param.id, next, true);
}}
/>
)}
</div>
+70
View File
@@ -0,0 +1,70 @@
// Run with: node --test src/lib/settle.test.ts (Node >= 22.6 strips the types)
import assert from "node:assert/strict";
import { mock, test } from "node:test";
import { createSettler } from "./settle.ts";
function setup(delay = 250) {
mock.timers.enable({ apis: ["setTimeout"] });
const sent: Record<string, number>[] = [];
const settler = createSettler<number>(delay, (values) => sent.push(values));
return { sent, settler };
}
test("a burst of changes is sent once, after it stops", () => {
const { sent, settler } = setup();
for (let step = 1; step <= 20; step++) {
settler.push("j1", step);
mock.timers.tick(100); // faster than the delay: the drag never pauses
}
assert.equal(sent.length, 0);
mock.timers.tick(250);
assert.deepEqual(sent, [{ j1: 20 }]);
mock.reset();
});
test("a pause in the middle of a drag sends what is there", () => {
const { sent, settler } = setup();
settler.push("j1", 5);
mock.timers.tick(300);
settler.push("j1", 9);
mock.timers.tick(300);
assert.deepEqual(sent, [{ j1: 5 }, { j1: 9 }]);
mock.reset();
});
test("flush sends at once and cancels the wait", () => {
const { sent, settler } = setup();
settler.push("j1", 7);
settler.flush();
assert.deepEqual(sent, [{ j1: 7 }]);
mock.timers.tick(1000);
assert.equal(sent.length, 1);
mock.reset();
});
test("the latest value of each parameter wins, and all of them go together", () => {
const { sent, settler } = setup();
settler.push("j1", 1);
settler.push("j2", 2);
settler.push("j1", 3);
settler.flush();
assert.deepEqual(sent, [{ j1: 3, j2: 2 }]);
mock.reset();
});
test("flush with nothing pending sends nothing", () => {
const { sent, settler } = setup();
settler.flush();
assert.equal(sent.length, 0);
mock.reset();
});
test("cancel drops what is pending", () => {
const { sent, settler } = setup();
settler.push("j1", 1);
settler.cancel();
mock.timers.tick(1000);
assert.equal(sent.length, 0);
mock.reset();
});
+42
View File
@@ -0,0 +1,42 @@
/** How long a drag has to pause before its value is sent (ms). */
export const SETTLE_MS = 250;
/** Collect changes and send them once they settle.
*
* A slider reports every step of a drag, and each step the server is given
* is a rebuild of the model. `push` records the latest value of a key and
* restarts the wait; the values go out together when `delay` ms pass without
* another change (the drag paused), or at once on `flush` (the pointer was
* released, a toggle was clicked). Not a throttle: a drag that never pauses
* sends nothing until it ends.
*/
export function createSettler<V>(delay: number, send: (values: Record<string, V>) => void) {
const pending = new Map<string, V>();
let timer: ReturnType<typeof setTimeout> | null = null;
const stop = () => {
if (timer !== null) clearTimeout(timer);
timer = null;
};
const flush = () => {
stop();
if (pending.size === 0) return;
const values = Object.fromEntries(pending);
pending.clear();
send(values);
};
return {
push(key: string, value: V) {
pending.set(key, value);
stop();
timer = setTimeout(flush, delay);
},
flush,
cancel() {
stop();
pending.clear();
},
};
}
+2 -1
View File
@@ -22,5 +22,6 @@
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
"include": ["src"],
"exclude": ["src/**/*.test.ts"]
}
+2 -1
View File
@@ -17,5 +17,6 @@
"@/*": ["./src/*"]
}
},
"include": ["src"]
"include": ["src"],
"exclude": ["src/**/*.test.ts"]
}