Something went wrong. Try again.
honestly just guess what it does. You're probably right.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620<!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>tsbutt logic tests</title> <style> body { font-family: monospace; background: #111; color: #ddd; padding: 1rem; } .pass { color: #2ed573; } .fail { color: #ff4757; font-weight: bold; } #summary { font-size: 1.2rem; margin: 1rem 0; } </style></head><body> <h1>tsbutt logic tests (logic.js)</h1> <div id="summary">running…</div> <ol id="results"></ol>
<script type="module"> import { createVibrationManager, createPatternEngine, clampPercent, clampLoopSeconds, clampGamma, sanitizeVibrators, vibratorId, freehandIntensity, freehandShadeAlpha, PATTERN_SAMPLES, FREEHAND_MAX_SHADE_ALPHA, MIN_COMMAND_INTERVAL_MS, } from "./logic.js";
// --- fake clock -------------------------------------------------------
function makePorts() { const ports = { now: () => clock, schedule(fn, ms) { const id = ++ports.nextId; timers.push({ id, at: clock + ms, fn }); return id; }, cancel(id) { timers = timers.filter((t) => t.id !== id); }, sendVibrate(id, pct) { ports.events.push(["vibrate", id, pct]); }, sendStop(id) { ports.events.push(["stop", id]); }, stopAll() { ports.events.push(["stop-all"]); }, events: [], nextId: 0, }; let timers = []; ports.tick = (ms) => { const target = clock + ms; for (;;) { timers.sort((a, b) => a.at - b.at); const next = timers[0]; if (!next || next.at > target) break; clock = next.at; timers.shift(); next.fn(); } clock = target; }; let clock = 0; return ports; }
const VIBS = [ { deviceIndex: 1, featureIndex: 0, deviceName: "Device A", featureLabel: "Vibrator 1" }, { deviceIndex: 1, featureIndex: 1, deviceName: "Device A", featureLabel: "Vibrator 2" }, { deviceIndex: 2, featureIndex: 0, deviceName: "Device B", featureLabel: "Vibrator" }, ]; const A0 = vibratorId(1, 0); const A1 = vibratorId(1, 1); const B0 = vibratorId(2, 0);
// --- tiny harness -----------------------------------------------------
const results = []; let totalTests = 0; function assert(cond, msg) { if (!cond) throw new Error(msg || "assertion failed"); } function assertEq(actual, expected, msg) { const a = JSON.stringify(actual); const e = JSON.stringify(expected); if (a !== e) throw new Error(`${msg ?? "eq"}: got ${a}, want ${e}`); } function sent(ports, id) { return id ? ports.events.filter((e) => e[1] === id) : ports.events; } function lastSend(ports) { return ports.events[ports.events.length - 1]; }
function test(name, fn) { totalTests++; const ports = makePorts(); const record = (ok, msg) => { results.push([name, ok, msg]); if (results.length === totalTests) report(); }; try { const r = fn(ports); if (r && typeof r.then === "function") { r.then( () => record(true, ""), (err) => record(false, err.message), ); } else { record(true, ""); } } catch (err) { record(false, err.message); } }
// --- helpers ----------------------------------------------------------
function connectedManager(ports, descriptors = VIBS) { const m = createVibrationManager(ports); m.handleConnected(); m.setVibrators(descriptors); return m; }
// --- pure helpers -----------------------------------------------------
test("clampPercent clamps to 0..100", () => { assertEq(clampPercent(-5), 0); assertEq(clampPercent(150), 100); assertEq(clampPercent(42), 42); assertEq(clampPercent(NaN), 0); });
test("sanitizeVibrators normalizes and dedups ids", () => { const out = sanitizeVibrators([ { deviceIndex: 1, featureIndex: 0, deviceName: "A" }, { deviceIndex: 1, featureIndex: 0, deviceName: "A again" }, { deviceIndex: 2, featureIndex: 3 }, null, { deviceIndex: "x", featureIndex: 0 }, ]); assertEq(out.length, 2); assertEq(out[0].id, "1:0"); assertEq(out[1].id, "2:3"); assertEq(out[0].deviceName, "A"); assertEq(out[1].deviceName, "unknown device"); assertEq(sanitizeVibrators("nope"), []); });
// --- sliders ----------------------------------------------------------
test("setSlider sends immediately when idle", (ports) => { const m = connectedManager(ports); m.setSlider(A0, 40); assertEq(lastSend(ports), ["vibrate", A0, 0.4], "immediate send"); });
test("throttle coalesces rapid changes, latest value wins", (ports) => { const m = connectedManager(ports, [VIBS[0]]); m.setSlider(A0, 10); m.setSlider(A0, 50); m.setSlider(A0, 90); assertEq(sent(ports).length, 1, "one send inside window"); ports.tick(MIN_COMMAND_INTERVAL_MS - 1); assertEq(sent(ports).length, 1, "not yet sent before window closes"); ports.tick(1); assertEq(sent(ports).length, 2, "trailing send after window"); assertEq(lastSend(ports), ["vibrate", A0, 0.9], "trailing value is the latest"); });
test("throttle is per vibrator", (ports) => { const m = connectedManager(ports); m.setSlider(A0, 10); m.setSlider(A1, 80); assertEq(sent(ports, A0).length, 1, "A0 sent"); assertEq(sent(ports, A1).length, 1, "A1 not blocked by A0's window"); });
test("setSlider(0) sends stop, not intensity 0", (ports) => { const m = connectedManager(ports, [VIBS[0]]); m.setSlider(A0, 30); ports.tick(MIN_COMMAND_INTERVAL_MS); m.setSlider(A0, 0); assertEq(lastSend(ports), ["stop", A0], "zero maps to stop"); });
test("redundant syncs send nothing", (ports) => { const m = connectedManager(ports, [VIBS[0]]); m.setSlider(A0, 50); ports.tick(MIN_COMMAND_INTERVAL_MS); const before = ports.events.length; m.refreshBase(); m.refreshBase(); assertEq(ports.events.length, before, "no duplicate sends"); });
// --- hold buttons -----------------------------------------------------
test("hold max: press sends 100%, release returns to slider", (ports) => { const m = connectedManager(ports, [VIBS[0]]); m.setSlider(A0, 20); ports.tick(MIN_COMMAND_INTERVAL_MS); m.setHold(A0, "max"); assertEq(lastSend(ports), ["vibrate", A0, 1], "max while held"); m.releaseHold(A0); ports.tick(MIN_COMMAND_INTERVAL_MS); // release-to-slider is throttled assertEq(lastSend(ports), ["vibrate", A0, 0.2], "release returns to slider"); });
test("hold stop: press stops, release returns to slider", (ports) => { const m = connectedManager(ports, [VIBS[0]]); m.setSlider(A0, 20); ports.tick(MIN_COMMAND_INTERVAL_MS); m.setHold(A0, "stop"); assertEq(lastSend(ports), ["stop", A0], "stop while held"); m.releaseHold(A0); ports.tick(MIN_COMMAND_INTERVAL_MS); // release-to-slider is throttled assertEq(lastSend(ports), ["vibrate", A0, 0.2], "release returns to slider"); });
test("slider changed while held applies on release", (ports) => { const m = connectedManager(ports, [VIBS[0]]); m.setSlider(A0, 20); ports.tick(MIN_COMMAND_INTERVAL_MS); m.setHold(A0, "max"); m.setSlider(A0, 70); // no output change while held assertEq(lastSend(ports), ["vibrate", A0, 1]); m.releaseHold(A0); ports.tick(MIN_COMMAND_INTERVAL_MS); // release-to-slider is throttled assertEq(lastSend(ports), ["vibrate", A0, 0.7], "release uses the new slider value"); });
test("holds are per vibrator", (ports) => { const m = connectedManager(ports); m.setSlider(A0, 30); m.setSlider(A1, 40); ports.tick(MIN_COMMAND_INTERVAL_MS); m.setHold(A0, "max"); assertEq(lastSend(ports), ["vibrate", A0, 1], "A0 held at max"); assertEq(m.vibrator(A1).hold, null, "A1 unaffected"); });
// --- base provider (mode abstraction) ---------------------------------
test("base provider drives output; refreshBase syncs", (ports) => { const m = connectedManager(ports, [VIBS[0]]); let base = 0; m.setBaseProvider(() => base); assertEq(sent(ports, A0).length, 0, "0 base sends nothing"); base = 55; m.refreshBase(); assertEq(lastSend(ports), ["vibrate", A0, 0.55]); base = 0; m.refreshBase(); assertEq(lastSend(ports), ["stop", A0]); });
test("new vibrators join the current base immediately", (ports) => { const m = connectedManager(ports, [VIBS[0]]); let base = 60; m.setBaseProvider(() => base); ports.tick(MIN_COMMAND_INTERVAL_MS); m.setVibrators([VIBS[0], VIBS[1]]); // Device A gained a second vibrator assertEq(lastSend(ports), ["vibrate", A1, 0.6], "new vibrator plays the base"); assertEq(m.vibrator(A1).slider, 0, "starts with a 0 slider"); });
test("removed vibrators stop receiving commands", (ports) => { const m = connectedManager(ports); m.setSlider(B0, 50); ports.tick(MIN_COMMAND_INTERVAL_MS); m.setVibrators([VIBS[0], VIBS[1]]); // Device B removed assertEq(m.vibrator(B0), undefined); const before = ports.events.length; ports.tick(10000); assertEq(ports.events.length, before, "no sends to removed vibrators"); m.setSlider(B0, 90); // stale id is a no-op assertEq(ports.events.length, before); });
test("holds survive registry refresh for unchanged vibrators", (ports) => { const m = connectedManager(ports, [VIBS[0]]); m.setSlider(A0, 30); ports.tick(MIN_COMMAND_INTERVAL_MS); m.setHold(A0, "max"); m.setVibrators(VIBS); // unrelated devices appear assertEq(m.vibrator(A0).hold, "max", "hold kept"); m.releaseHold(A0); ports.tick(MIN_COMMAND_INTERVAL_MS); // release-to-slider is throttled assertEq(lastSend(ports), ["vibrate", A0, 0.3], "release still returns to slider"); });
// --- emergency stop + safety events -----------------------------------
test("emergencyStop zeroes sliders, clears holds, stops everything", (ports) => { const m = connectedManager(ports); m.setSlider(A0, 20); m.setSlider(A1, 80); // pending trailing send scheduled m.setHold(B0, "max"); m.emergencyStop({ latch: false }); // button semantics: still operable assertEq(lastSend(ports), ["stop-all"]); assertEq(m.vibrator(A0).slider, 0); assertEq(m.vibrator(B0).hold, null); const before = ports.events.length; ports.tick(1000); assertEq(ports.events.length, before, "trailing send cancelled, nothing else fires"); // Post-estop slider use works again. m.setSlider(A0, 40); assertEq(lastSend(ports), ["vibrate", A0, 0.4]); });
test("latched emergencyStop (safety events) blocks commands", (ports) => { const m = connectedManager(ports, [VIBS[0]]); m.setSlider(A0, 50); ports.tick(MIN_COMMAND_INTERVAL_MS); m.emergencyStop(); // default: latched, used by page hide / command errors assertEq(lastSend(ports), ["stop-all"]); const before = ports.events.length; m.setSlider(A0, 60); ports.tick(1000); assertEq(ports.events.length, before, "latched: commands do nothing"); // handleVisible (returning to the page) unhooks the latch. m.handleVisible(); m.setSlider(A0, 60); ports.tick(MIN_COMMAND_INTERVAL_MS); assertEq(lastSend(ports), ["vibrate", A0, 0.6]); });
test("emergencyStop invokes the mode hook", (ports) => { let stops = 0; const p2 = makePorts(); p2.onEmergencyStop = () => stops++; const m = connectedManager(p2); m.emergencyStop(); m.emergencyStop(); assertEq(stops, 2, "hook called for each estop"); });
test("disconnect halts everything and zeroes state", (ports) => { const m = connectedManager(ports, [VIBS[0]]); m.setSlider(A0, 70); ports.tick(MIN_COMMAND_INTERVAL_MS); m.handleDisconnect(); assertEq(m.vibrator(A0).slider, 0, "slider reset"); const before = ports.events.length; ports.tick(10000); assertEq(ports.events.length, before, "no sends after disconnect"); // Reconnect restores operation (fresh registry, zero state). m.handleConnected(); m.setVibrators([VIBS[0]]); m.setSlider(A0, 50); assertEq(lastSend(ports), ["vibrate", A0, 0.5]); });
test("page hide stops everything and clears pattern state (AC.7)", (ports) => { const m = connectedManager(ports, [VIBS[0]]); m.setSlider(A0, 70); ports.tick(MIN_COMMAND_INTERVAL_MS); m.handlePageHide(); assertEq(lastSend(ports), ["stop-all"]); const before = ports.events.length; ports.tick(10000); assertEq(ports.events.length, before, "no sends after page hide"); // Visible again with no disconnect: operating, but everything at rest. m.handleVisible(); m.setSlider(A0, 30); assertEq(lastSend(ports), ["vibrate", A0, 0.3]); });
test("async command rejection stops everything (AC.7)", (ports) => { let errors = []; const rejPorts = makePorts(); rejPorts.sendVibrate = (id, pct) => { rejPorts.events.push(["vibrate", id, pct]); return Promise.reject(new Error("async boom")); }; const m = createVibrationManager({ ...rejPorts, onError: (e) => errors.push(e) }); m.handleConnected(); m.setVibrators([VIBS[0]]); m.setSlider(A0, 50); // rejection is asynchronous — nothing thrown here assertEq(lastSend(rejPorts), ["vibrate", A0, 0.5]); return Promise.resolve().then(() => new Promise((res) => setTimeout(res, 0))).then(() => { assertEq(errors.length, 1, "onError called for rejection"); assertEq(lastSend(rejPorts), ["stop-all"], "safety stop after rejected command"); assertEq(m.isHalted(), true); const before = rejPorts.events.length; rejPorts.tick(10000); assertEq(rejPorts.events.length, before, "no further sends after rejection"); }); });
test("sync command error stops everything (AC.7)", (ports) => { let errors = []; const errPorts = makePorts(); errPorts.sendVibrate = () => { errPorts.events.push(["vibrate", A0, 0]); throw new Error("boom"); }; const m = createVibrationManager({ ...errPorts, onError: (e) => errors.push(e) }); m.handleConnected(); m.setVibrators([VIBS[0]]); // dispatch swallows the synchronous failure on purpose: the caller must // not need its own try/catch around every control event. m.setSlider(A0, 50); assertEq(errors.length, 1, "onError called"); assertEq(lastSend(errPorts), ["stop-all"], "safety stop after failed command"); const before = errPorts.events.length; errPorts.tick(10000); assertEq(errPorts.events.length, before, "no further sends after error"); });
// --- pattern engine ---------------------------------------------------
function rampWave(e, id) { const w = e.waveData(id); for (let i = 0; i < PATTERN_SAMPLES; i++) w[i] = (i / (PATTERN_SAMPLES - 1)) * 100; return w; }
function lastSendFor(ports, id) { const evs = ports.events.filter((x) => x[1] === id); return evs[evs.length - 1]; }
function approx(actual, expected, msg, tol = 0.02) { if (Math.abs(actual - expected) > tol) { throw new Error(`${msg ?? "approx"}: got ${actual}, want ~${expected}`); } }
test("clampLoopSeconds clamps to bounds", () => { assertEq(clampLoopSeconds(0), 0.5); assertEq(clampLoopSeconds(999), 60); assertEq(clampLoopSeconds("junk"), 4); assertEq(clampLoopSeconds(2.5), 2.5); });
test("pattern plays waveforms in sync across vibrators and loops", (ports) => { const m = connectedManager(ports); const e = createPatternEngine(m, ports); m.setBaseProvider((st) => (e.isPlaying() ? e.sample(st.id) : 0)); rampWave(e, A0); e.waveData(A1).fill(50); e.setLoopSeconds(2); e.play(); assertEq(lastSendFor(ports, A0), undefined, "A0 starts silent at 0"); assertEq(lastSendFor(ports, A1), ["vibrate", A1, 0.5], "A1 flat at 50%"); ports.tick(1000); // half the loop approx(e.phase(), 0.5, "phase at half loop"); approx(lastSendFor(ports, A0)[2], 0.5, "A0 mid-loop value", 0.05); ports.tick(1000); // wraps to phase 0 approx(e.phase(), 0, "loop wrapped to phase 0"); ports.tick(300); // t = 2300, phase 0.15 into the new loop approx(lastSendFor(ports, A0)[2], 0.15, "output ramping again after wrap", 0.05); assertEq(e.isPlaying(), true); e.stop(); assertEq(e.isPlaying(), false); const before = ports.events.length; ports.tick(10000); assertEq(ports.events.length, before, "no sends after stop"); });
test("pause zeros output, retains position, resume continues", (ports) => { const m = connectedManager(ports, [VIBS[0]]); const e = createPatternEngine(m, ports); m.setBaseProvider((st) => (e.isPlaying() ? e.sample(st.id) : 0)); rampWave(e, A0); e.setLoopSeconds(2); e.play(); ports.tick(500); // phase 0.25 approx(lastSendFor(ports, A0)[2], 0.25, "pre-pause value", 0.05); e.pause(); assertEq(lastSendFor(ports, A0), ["stop", A0], "pause zeros output"); const before = ports.events.length; ports.tick(10000); assertEq(ports.events.length, before, "paused: no sends"); e.play(); approx(lastSendFor(ports, A0)[2], 0.25, "resume continues from position"); });
test("restart jumps to the start of the loop", (ports) => { const m = connectedManager(ports, [VIBS[0]]); const e = createPatternEngine(m, ports); m.setBaseProvider((st) => (e.isPlaying() ? e.sample(st.id) : 0)); rampWave(e, A0); e.setLoopSeconds(2); e.play(); ports.tick(1000); e.restart(); assertEq(lastSendFor(ports, A0), ["stop", A0], "phase 0 after restart"); approx(e.phase(), 0, "phase reset"); });
test("loop length change while playing keeps position", (ports) => { const m = connectedManager(ports, [VIBS[0]]); const e = createPatternEngine(m, ports); m.setBaseProvider((st) => (e.isPlaying() ? e.sample(st.id) : 0)); rampWave(e, A0); e.setLoopSeconds(2); e.play(); ports.tick(500); // phase 0.25 e.setLoopSeconds(4); approx(e.phase(), 0.25, "phase preserved across loop change"); ports.tick(1000); // 0.25 + 1000 ms of a 4 s loop approx(e.phase(), 0.5, "advanced at the new loop speed"); approx(lastSendFor(ports, A0)[2], 0.5, "output follows the new speed", 0.05); });
test("editing a waveform while playing takes effect immediately", (ports) => { const m = connectedManager(ports, [VIBS[0]]); const e = createPatternEngine(m, ports); m.setBaseProvider((st) => (e.isPlaying() ? e.sample(st.id) : 0)); e.setLoopSeconds(2); e.play(); // flat 0 wave: A0 at 0 ports.tick(1000); e.waveData(A0).fill(40); e.waveEdited(A0); approx(lastSendFor(ports, A0)[2], 0.4, "edited value is played"); });
test("vibrator added mid-playback joins with a flat 0 wave", (ports) => { const m = connectedManager(ports, [VIBS[0]]); const e = createPatternEngine(m, ports); m.setBaseProvider((st) => (e.isPlaying() ? e.sample(st.id) : 0)); rampWave(e, A0); e.setLoopSeconds(2); e.play(); ports.tick(200); m.setVibrators(VIBS); // A1 and B0 appear e.syncVibrators(m.vibrators()); assertEq(e.waveData(A1).every((v) => v === 0), true, "new wave is flat 0"); e.waveData(A1).fill(70); e.waveEdited(A1); approx(lastSendFor(ports, A1)[2], 0.7, "new vibrator joins after its wave is drawn"); // Removed vibrators lose their wave data. m.setVibrators([VIBS[0]]); e.syncVibrators(m.vibrators()); assertEq(Object.keys(e.waveSnapshot()), [A0], "stale wave dropped"); });
// --- freehand intensity curve ------------------------------------------
test("freehandIntensity: linear falloff by default", () => { assertEq(freehandIntensity(0), 100, "center is max"); assertEq(freehandIntensity(1), 0, "ring edge is silent"); assertEq(freehandIntensity(1.5), 0, "outside the ring is silent"); assertEq(freehandIntensity(-1), 0, "negative distance is silent"); approx(freehandIntensity(0.5), 50, "halfway is half", 0.01); });
test("freehandIntensity: gamma shapes the falloff", () => { // Steeper curve: intensity concentrated near the center. approx(freehandIntensity(0.5, 2), 25, "gamma 2 at halfway", 0.01); approx(freehandIntensity(0.5, 0.5), Math.sqrt(0.5) * 100, "gamma 0.5 at halfway", 0.01); approx(freehandIntensity(0.25, 2), 56.25, "gamma 2 at quarter", 0.01); assert(freehandIntensity(0.9, 2) < freehandIntensity(0.9, 0.5), "steeper is weaker near edge"); approx(freehandIntensity(0.5, NaN), 50, "invalid gamma falls back to linear", 0.01); approx(freehandIntensity(0.5, 99), 6.25, "gamma clamped high", 0.01); });
test("freehandShadeAlpha visualizes the falloff derivative", () => { const CAP = FREEHAND_MAX_SHADE_ALPHA; assert(CAP < 1, "max shade is not opaque"); // Linear falloff (gamma 1): unchanging transparency across the ring. assertEq(freehandShadeAlpha(0, 1), CAP); approx(freehandShadeAlpha(0.5, 1), CAP, "linear: constant alpha", 0.001); assertEq(freehandShadeAlpha(1, 1), CAP); // Steeper curve (gamma 2): brightest at the center, transparent edge. assertEq(freehandShadeAlpha(0, 2), CAP); approx(freehandShadeAlpha(0.5, 2), CAP / 2, "gamma 2 halves at halfway", 0.001); assertEq(freehandShadeAlpha(1, 2), 0, "edge is transparent"); // Flatter curve (gamma 0.5): brightens toward the edge, capped at CAP. assert(freehandShadeAlpha(0, 0.5) < freehandShadeAlpha(0.9, 0.5)); assert(freehandShadeAlpha(0.9, 0.5) <= CAP); assert(freehandShadeAlpha(0, 0.5) > 0); // Outside and invalid distances are transparent. assertEq(freehandShadeAlpha(2, 3), 0, "outside is transparent"); assertEq(freehandShadeAlpha(NaN, 1), 0, "invalid distance is transparent"); });
test("clampGamma bounds", () => { assertEq(clampGamma(0), 0.3); assertEq(clampGamma(99), 4); assertEq(clampGamma("junk"), 1); assertEq(clampGamma(1.7), 1.7); });
// --- report -----------------------------------------------------------
function report() { const ol = document.getElementById("results"); let failures = 0; for (const [name, ok, msg] of results) { const li = document.createElement("li"); li.className = ok ? "pass" : "fail"; li.textContent = ok ? `PASS ${name}` : `FAIL ${name} — ${msg}`; ol.append(li); if (!ok) failures++; } const summary = document.getElementById("summary"); summary.textContent = failures === 0 ? `All ${results.length} tests passed.` : `${failures} of ${results.length} tests FAILED.`; summary.className = failures === 0 ? "pass" : "fail"; document.title = failures === 0 ? "PASS" : "FAIL"; } </script></body></html>