diff --git a/tsbridge/webapp/app.js b/tsbridge/webapp/app.js
index 98df10c..e65c337 100644
--- a/tsbridge/webapp/app.js
+++ b/tsbridge/webapp/app.js
@@ -1,5 +1,9 @@
// tsbutt webapp — DOM wiring. All vibration logic lives in logic.js; this
-// file connects it to buttplug.js and the page.
+// file connects it to buttplug.js and the page, and renders the vibrator
+// list. Every vibrator (one vibrate-capable feature on one device) gets its
+// own slider, hold-to-max and hold-to-stop buttons. Devices may appear or
+// disappear at any time; the registry diff in logic.js keeps output state
+// consistent and the UI re-renders from manager state.
import {
ButtplugBrowserWebsocketClientConnector,
@@ -9,7 +13,7 @@ import {
InputType,
OutputType,
} from "./vendor/buttplug.mjs";
-import { createVibrationController, sanitizeSteps, MAX_PATTERN_STEPS } from "./logic.js";
+import { createVibrationManager, vibratorId } from "./logic.js";
// --- helpers -------------------------------------------------------------
@@ -38,16 +42,26 @@ function showError(msg) {
}
$("banner").addEventListener("click", () => $("banner").classList.add("hidden"));
-// --- controller wiring ---------------------------------------------------
+// --- manager wiring ------------------------------------------------------
-const controller = createVibrationController({
- sendIntensity(pct) {
- if (!device) throw new Error("no device");
- return device.runOutput(DeviceOutput.Vibrate.percent(pct));
+// id -> buttplug feature object for one vibrator. Rebuilt on every registry
+// refresh; logic.js holds the per-vibrator UI state.
+const features = new Map();
+
+const manager = createVibrationManager({
+ sendVibrate(id, percent01) {
+ const f = features.get(id);
+ if (!f) throw new Error("vibrator is gone");
+ return f.runOutput(DeviceOutput.Vibrate.percent(percent01));
+ },
+ sendStop(id) {
+ const f = features.get(id);
+ if (!f) return; // already gone; nothing to stop
+ return f.runOutput(DeviceOutput.Vibrate.percent(0));
},
- sendStop() {
- if (!device) throw new Error("no device");
- return device.stop();
+ stopAll() {
+ if (!client) throw new Error("not connected");
+ return client.stopAllDevices();
},
now: () => performance.now(),
schedule: (fn, ms) => setTimeout(fn, ms),
@@ -56,15 +70,28 @@ const controller = createVibrationController({
showError(`Command failed: ${err?.message ?? err}`);
log(`command error: ${err?.message ?? err}`);
},
+ onEmergencyStop() {
+ // Future modes stop their own drivers here; direct control has nothing
+ // beyond the manager's own reset.
+ },
+ onChange: render,
});
+function runCommand(fn) {
+ try {
+ fn();
+ } catch (err) {
+ manager.handleCommandError(err);
+ }
+}
+
// --- buttplug client -----------------------------------------------------
let client = null;
-let device = null;
let reconnectTimer = null;
let reconnectDelay = 500;
let intentionallyClosed = false;
+const batteryText = new Map(); // deviceIndex -> "Battery 87%"
function setPill(state, text) {
const pill = $("status-pill");
@@ -72,69 +99,189 @@ function setPill(state, text) {
pill.textContent = text;
}
-function setControlsEnabled(enabled) {
- for (const id of ["intensity", "hold", "play", "stop", "estop", "add-step", "rescan"]) {
- $(id).disabled = !enabled;
+// Enumerate every vibrate-capable feature on every connected device and hand
+// the list to the manager, which diffs it against the current set.
+function refreshRegistry() {
+ features.clear();
+ const descriptors = [];
+ for (const d of client?.devices.values() ?? []) {
+ if (!d.hasOutput(OutputType.Vibrate)) continue;
+ let n = 0;
+ for (const [featureIndex, f] of d.features) {
+ if (!f.hasOutput(OutputType.Vibrate)) continue;
+ n += 1;
+ const id = vibratorId(d.index, featureIndex);
+ features.set(id, f);
+ descriptors.push({
+ deviceIndex: d.index,
+ featureIndex,
+ deviceName: d.displayName || d.name || "unknown device",
+ featureLabel: d.features.size > 1 ? `Vibrator ${n}` : "Vibrator",
+ });
+ }
}
+ manager.setVibrators(descriptors);
}
-function pickDevice(added) {
- const candidate = added ?? [...client.devices.values()].find((d) =>
- d.hasOutput(OutputType.Vibrate),
- );
- if (!candidate?.hasOutput(OutputType.Vibrate)) return;
- device = candidate;
- $("device-name").textContent = candidate.name ?? "unknown device";
- pollBattery();
- setControlsEnabled(true);
- log(`device: ${device.name}`);
-}
-
-let batteryTimer = null;
+// --- battery polling -----------------------------------------------------
function stopBatteryPolling() {
- if (batteryTimer !== null) {
- clearInterval(batteryTimer);
- batteryTimer = null;
- }
+ // Managed per device below; this clears every poll timer.
+ for (const t of batteryTimers.values()) clearInterval(t);
+ batteryTimers.clear();
}
+const batteryTimers = new Map(); // deviceIndex -> interval handle
-function pollBattery() {
+function startBatteryPolling() {
stopBatteryPolling();
- const current = device;
- if (!current?.hasInput(InputType.Battery)) return;
- const refresh = () => {
- if (device !== current) {
- stopBatteryPolling();
- return;
+ if (!client) return;
+ for (const d of client.devices.values()) {
+ if (!d.hasInput(InputType.Battery)) continue;
+ const deviceIndex = d.index;
+ const refresh = () => {
+ const current = client?.devices.get(deviceIndex);
+ if (!current) {
+ const t = batteryTimers.get(deviceIndex);
+ if (t !== undefined) {
+ clearInterval(t);
+ batteryTimers.delete(deviceIndex);
+ }
+ batteryText.delete(deviceIndex);
+ return;
+ }
+ current
+ .battery()
+ .then((level) => {
+ batteryText.set(deviceIndex, `Battery ${Math.round(level * 100)}%`);
+ render();
+ })
+ .catch(() => {
+ /* battery read failures are non-fatal */
+ });
+ };
+ refresh();
+ batteryTimers.set(deviceIndex, setInterval(refresh, 30000));
+ }
+}
+
+// --- rendering -----------------------------------------------------------
+
+// Renders the direct-control view from manager state. Called on registry
+// changes, connection changes, and emergency stop; slider drags do not
+// re-render (the manager holds the value).
+function render() {
+ const host = $("device-list");
+ const connected = manager.isConnected();
+ host.textContent = "";
+
+ const vibrators = manager.vibrators();
+ if (vibrators.length === 0) {
+ const p = document.createElement("p");
+ p.className = "muted empty-note";
+ p.textContent = connected ? "No vibrators found — try a rescan." : "Not connected.";
+ host.append(p);
+ return;
+ }
+
+ // Group vibrators by device, preserving registry order.
+ const groups = new Map(); // deviceIndex -> {name, items}
+ for (const v of vibrators) {
+ let g = groups.get(v.deviceIndex);
+ if (!g) {
+ g = { name: v.deviceName, items: [] };
+ groups.set(v.deviceIndex, g);
}
- current
- .battery()
- .then((level) => {
- const bat = $("battery");
- bat.hidden = false;
- bat.textContent = `Battery ${Math.round(level * 100)}%`;
- })
- .catch(() => {
- /* battery read failures are non-fatal */
- });
- };
- refresh();
- batteryTimer = setInterval(refresh, 30000);
+ g.items.push(v);
+ }
+
+ for (const [deviceIndex, g] of groups) {
+ const card = document.createElement("section");
+ card.className = "card device-card";
+
+ const head = document.createElement("div");
+ head.className = "device-head";
+ const name = document.createElement("h2");
+ name.className = "device-name";
+ name.textContent = g.name;
+ head.append(name);
+ const bat = batteryText.get(deviceIndex);
+ if (bat) {
+ const b = document.createElement("span");
+ b.className = "muted battery";
+ b.textContent = bat;
+ head.append(b);
+ }
+ card.append(head);
+
+ for (const v of g.items) card.append(vibratorRow(v, connected));
+ host.append(card);
+ }
}
-function onDeviceRemoved(d) {
- if (device && d && device.index === d.index) {
- device = null;
- stopBatteryPolling();
- $("device-name").textContent = "no device";
- $("battery").hidden = true;
- controller.emergencyStop();
- setControlsEnabled(!!client?.connected);
- log("device removed");
+function vibratorRow(v, connected) {
+ const row = document.createElement("div");
+ row.className = "vrow";
+
+ const label = document.createElement("span");
+ label.className = "vlabel";
+ label.textContent = v.featureLabel;
+ row.append(label);
+
+ const slider = document.createElement("input");
+ slider.type = "range";
+ slider.min = "0";
+ slider.max = "100";
+ slider.step = "1";
+ slider.value = String(v.slider);
+ slider.disabled = !connected;
+ slider.setAttribute("aria-label", `${v.deviceName} ${v.featureLabel} intensity`);
+ slider.addEventListener("input", () => {
+ runCommand(() => manager.setSlider(v.id, Number(slider.value)));
+ });
+ row.append(slider);
+
+ const btns = document.createElement("div");
+ btns.className = "vbtns";
+ const maxBtn = document.createElement("button");
+ maxBtn.type = "button";
+ maxBtn.className = "hold hold-max";
+ maxBtn.textContent = "Hold to max";
+ maxBtn.disabled = !connected;
+ maxBtn.setAttribute("aria-label", `${v.deviceName} ${v.featureLabel}: hold to vibrate at maximum`);
+ wireHold(maxBtn, v.id, "max");
+ const stopBtn = document.createElement("button");
+ stopBtn.type = "button";
+ stopBtn.className = "hold hold-stop";
+ stopBtn.textContent = "Hold to stop";
+ stopBtn.disabled = !connected;
+ stopBtn.setAttribute("aria-label", `${v.deviceName} ${v.featureLabel}: hold to stop`);
+ wireHold(stopBtn, v.id, "stop");
+ btns.append(maxBtn, stopBtn);
+ row.append(btns);
+ return row;
+}
+
+// Hold buttons: output runs at the hold level while pressed and returns to
+// the slider value on release (handled by the manager).
+function wireHold(btn, id, kind) {
+ btn.addEventListener("pointerdown", (e) => {
+ e.preventDefault();
+ btn.setPointerCapture(e.pointerId);
+ btn.classList.add("holding");
+ runCommand(() => manager.setHold(id, kind));
+ });
+ for (const ev of ["pointerup", "pointercancel", "lostpointercapture"]) {
+ btn.addEventListener(ev, () => {
+ if (!btn.classList.contains("holding")) return;
+ btn.classList.remove("holding");
+ runCommand(() => manager.releaseHold(id));
+ });
}
+ btn.addEventListener("contextmenu", (e) => e.preventDefault());
}
+// --- connection ----------------------------------------------------------
+
async function connect() {
if (client?.connected) return;
intentionallyClosed = false;
@@ -142,17 +289,25 @@ async function connect() {
// Register all listeners before connecting (buttplug.js requirement).
client.on("disconnect", () => {
- device = null;
+ features.clear();
+ batteryText.clear();
stopBatteryPolling();
- setControlsEnabled(false);
+ manager.setVibrators([]);
+ manager.handleDisconnect();
setPill("bad", "disconnected");
- controller.handleDisconnect();
scheduleReconnect();
});
- client.on("deviceadded", pickDevice);
- client.on("deviceremoved", onDeviceRemoved);
+ client.on("deviceadded", () => {
+ refreshRegistry();
+ startBatteryPolling();
+ log(`device added: ${[...client.devices.values()].at(-1)?.name ?? "?"}`);
+ });
+ client.on("deviceremoved", (d) => {
+ refreshRegistry();
+ log(`device removed: ${d?.name ?? "?"}`);
+ });
client.on("scanningfinished", () => {
- if (!device) pickDevice();
+ /* registry is already event-driven; nothing to do */
});
const connector = new ButtplugBrowserWebsocketClientConnector(wsURL());
@@ -161,8 +316,9 @@ async function connect() {
await client.connect(connector);
setPill("on", "connected");
reconnectDelay = 500;
- controller.handleConnected();
- setControlsEnabled(!!device);
+ manager.handleConnected();
+ refreshRegistry();
+ startBatteryPolling();
await client.startScanning();
} catch (err) {
setPill("bad", "connection failed");
@@ -184,191 +340,31 @@ function scheduleReconnect() {
log(`reconnecting in ${reconnectDelay} ms`);
}
-// --- intensity + hold ----------------------------------------------------
-
-$("intensity").addEventListener("input", (e) => {
- const pct = Number(e.target.value);
- $("intensity-value").textContent = `${pct}%`;
- runCommand(() => controller.setIntensity(pct));
-});
-$("intensity").addEventListener("change", (e) => {
- if (Number(e.target.value) === 0) runCommand(() => controller.stopVibration());
-});
-
-const DEFAULT_HOLD_PERCENT = 50;
-const holdBtn = $("hold");
-holdBtn.addEventListener("pointerdown", (e) => {
- e.preventDefault();
- holdBtn.setPointerCapture(e.pointerId);
- holdBtn.classList.add("holding");
- runCommand(() => controller.holdPress(DEFAULT_HOLD_PERCENT));
-});
-for (const ev of ["pointerup", "pointercancel", "lostpointercapture"]) {
- holdBtn.addEventListener(ev, () => {
- if (!holdBtn.classList.contains("holding")) return;
- holdBtn.classList.remove("holding");
- runCommand(() => controller.holdRelease());
- });
-}
-
-// --- pattern editor ------------------------------------------------------
-// patternRows is the source of truth while editing; inputs are committed on
-// every structural change (add/remove/reorder/play).
-
-let patternRows = [];
-
-function commitRows() {
- patternRows = patternRows.map((_, i) => ({
- intensity: Number($(`step-intensity-${i}`)?.value) || 0,
- duration: Number($(`step-duration-${i}`)?.value) || 0.1,
- }));
- controller.setPattern(patternRows, $("loop").checked);
- savePattern();
-}
-
-function savePattern() {
- try {
- localStorage.setItem(
- "tsbutt.pattern",
- JSON.stringify({ steps: patternRows, loop: $("loop").checked }),
- );
- } catch {
- /* private mode etc. — pattern just won't persist */
- }
-}
-
-function renderRows() {
- const ol = $("steps");
- ol.textContent = "";
- patternRows.forEach((step, i) => {
- const li = document.createElement("li");
-
- const label = document.createElement("span");
- label.className = "step-label";
- label.textContent = `${i + 1}.`;
-
- const inten = document.createElement("input");
- inten.type = "number";
- inten.min = "0";
- inten.max = "100";
- inten.step = "5";
- inten.value = String(step.intensity);
- inten.id = `step-intensity-${i}`;
- inten.setAttribute("aria-label", `Step ${i + 1} intensity percent`);
-
- const dur = document.createElement("input");
- dur.type = "number";
- dur.min = "0.1";
- dur.max = "600";
- dur.step = "0.1";
- dur.value = String(step.duration);
- dur.id = `step-duration-${i}`;
- dur.setAttribute("aria-label", `Step ${i + 1} duration seconds`);
-
- const up = ghostButton("↑", `Move step ${i + 1} up`, () => moveStep(i, -1));
- const down = ghostButton("↓", `Move step ${i + 1} down`, () => moveStep(i, 1));
- const del = ghostButton("✕", `Remove step ${i + 1}`, () => removeStep(i));
-
- li.append(label, inten, dur, up, down, del);
- ol.append(li);
- });
-}
-
-function ghostButton(text, ariaLabel, onClick) {
- const b = document.createElement("button");
- b.type = "button";
- b.className = "ghost";
- b.textContent = text;
- b.setAttribute("aria-label", ariaLabel);
- b.addEventListener("click", onClick);
- return b;
-}
-
-function loadPattern() {
- let parsed = null;
- try {
- parsed = JSON.parse(localStorage.getItem("tsbutt.pattern") ?? "null");
- } catch {
- /* fall through to default */
- }
- patternRows = sanitizeSteps(parsed?.steps?.length ? parsed.steps : [{ intensity: 60, duration: 1 }]);
- $("loop").checked = !!parsed?.loop;
- controller.setPattern(patternRows, $("loop").checked);
- renderRows();
-}
-
-function moveStep(i, dir) {
- commitRows();
- const j = i + dir;
- if (j < 0 || j >= patternRows.length) return;
- [patternRows[i], patternRows[j]] = [patternRows[j], patternRows[i]];
- controller.setPattern(patternRows, $("loop").checked);
- savePattern();
- renderRows();
-}
-
-function removeStep(i) {
- commitRows();
- patternRows.splice(i, 1);
- controller.setPattern(patternRows, $("loop").checked);
- savePattern();
- renderRows();
-}
-
-$("add-step").addEventListener("click", () => {
- commitRows();
- if (patternRows.length >= MAX_PATTERN_STEPS) return;
- patternRows.push({ intensity: 50, duration: 1 });
- controller.setPattern(patternRows, $("loop").checked);
- savePattern();
- renderRows();
-});
-
-$("loop").addEventListener("change", commitRows);
-
// --- transport buttons ---------------------------------------------------
-$("play").addEventListener("click", () => {
- commitRows();
- runCommand(() => controller.playPattern());
-});
-$("stop").addEventListener("click", () => {
- runCommand(() => controller.stopPattern());
-});
$("estop").addEventListener("click", () => {
- runCommand(() => controller.emergencyStop());
- $("intensity").value = "0";
- $("intensity-value").textContent = "0%";
+ // Unlatched: stop and reset everything now, but keep the app operable.
+ runCommand(() => manager.emergencyStop({ latch: false }));
});
$("rescan").addEventListener("click", () => {
if (client?.connected) client.startScanning().catch((e) => log(`scan: ${e.message}`));
});
-function runCommand(fn) {
- try {
- fn();
- } catch (err) {
- controller.handleCommandError(err);
- }
-}
-
-// --- safety: page lifecycle (AC.7) ---------------------------------------
+// --- safety: page lifecycle ----------------------------------------------
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") {
- controller.handlePageHide();
+ manager.handlePageHide();
} else {
- controller.handleVisible();
+ manager.handleVisible();
}
});
-window.addEventListener("pagehide", () => controller.handlePageHide());
+window.addEventListener("pagehide", () => manager.handlePageHide());
// Last-resort net: any rejection that escapes every handler must still stop
-// the toy. (All command paths are already routed through logic.js dispatch.)
-window.addEventListener("unhandledrejection", () => controller.emergencyStop());
+// the toys. (All command paths are already routed through logic.js dispatch.)
+window.addEventListener("unhandledrejection", () => manager.emergencyStop());
// --- boot ----------------------------------------------------------------
-setControlsEnabled(false);
-loadPattern();
connect();
log(`webapp loaded; ws target ${wsURL()}`);
diff --git a/tsbridge/webapp/index.html b/tsbridge/webapp/index.html
index 448383c..90f7e44 100644
--- a/tsbridge/webapp/index.html
+++ b/tsbridge/webapp/index.html
@@ -10,43 +10,19 @@
tsbutt
+
connecting…
-
- Device
- no device
-
-
-
-
-
-
-
-
-
+
Status log
@@ -54,6 +30,12 @@
+
+
+