diff --git a/tsbridge/webapp/app.js b/tsbridge/webapp/app.js index e65c337..d925a5a 100644 --- a/tsbridge/webapp/app.js +++ b/tsbridge/webapp/app.js @@ -1,9 +1,8 @@ // tsbutt webapp — DOM wiring. All vibration logic lives in logic.js; this -// 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. +// file connects it to buttplug.js and the page, renders the vibrator list, +// and hosts the mode system. Every mode drives output through the same +// manager codepath (a base provider); devices may appear or disappear at +// any time and every view re-renders from manager state. import { ButtplugBrowserWebsocketClientConnector, @@ -13,7 +12,12 @@ import { InputType, OutputType, } from "./vendor/buttplug.mjs"; -import { createVibrationManager, vibratorId } from "./logic.js"; +import { + createVibrationManager, + createPatternEngine, + vibratorId, + PATTERN_SAMPLES, +} from "./logic.js"; // --- helpers ------------------------------------------------------------- @@ -71,8 +75,8 @@ const manager = createVibrationManager({ log(`command error: ${err?.message ?? err}`); }, onEmergencyStop() { - // Future modes stop their own drivers here; direct control has nothing - // beyond the manager's own reset. + // Every mode stops its own driver here; the manager handles the rest. + patternEngine.stop(); }, onChange: render, }); @@ -85,6 +89,88 @@ function runCommand(fn) { } } +// --- pattern engine ------------------------------------------------------ + +const patternEngine = createPatternEngine(manager, { + now: () => performance.now(), + schedule: (fn, ms) => setTimeout(fn, ms), + cancel: (h) => clearTimeout(h), +}); + +// The pattern mode's base provider: while playing, every vibrator is driven +// by its waveform at the current phase; otherwise it rests at 0. +const patternProvider = (st) => (patternEngine.isPlaying() ? patternEngine.sample(st.id) : 0); + +const PATTERN_STORE_KEY = "tsbutt.pattern2"; + +function savePatternState() { + try { + localStorage.setItem( + PATTERN_STORE_KEY, + JSON.stringify({ + loop: patternEngine.loopSeconds(), + waves: patternEngine.waveSnapshot(), + }), + ); + } catch { + /* private mode etc. — the pattern just won't persist */ + } +} + +function loadPatternState() { + let parsed = null; + try { + parsed = JSON.parse(localStorage.getItem(PATTERN_STORE_KEY) ?? "null"); + } catch { + /* fall through to defaults */ + } + patternEngine.loadWaves(parsed?.waves, parsed?.loop); + $("pat-loop").value = String(patternEngine.loopSeconds()); +} + +// --- mode system --------------------------------------------------------- + +const modes = { + direct: { + view: "view-direct", + tab: "tab-direct", + activate() { + // No provider: the manager falls back to the slider set-points. + manager.setBaseProvider(null); + }, + deactivate() {}, + }, + pattern: { + view: "view-pattern", + tab: "tab-pattern", + activate() { + manager.setBaseProvider(patternProvider); + }, + deactivate() { + patternEngine.stop(); + }, + }, +}; +let activeMode = "direct"; + +function switchMode(name) { + if (name === activeMode || !modes[name]) return; + modes[activeMode].deactivate(); + activeMode = name; + for (const [key, m] of Object.entries(modes)) { + $(m.view).classList.toggle("hidden", key !== name); + const tab = $(m.tab); + tab.classList.toggle("active", key === name); + tab.setAttribute("aria-selected", String(key === name)); + } + modes[name].activate(); + updateTransport(); +} + +for (const [key, m] of Object.entries(modes)) { + $(m.tab).addEventListener("click", () => switchMode(key)); +} + // --- buttplug client ----------------------------------------------------- let client = null; @@ -121,6 +207,7 @@ function refreshRegistry() { } } manager.setVibrators(descriptors); + patternEngine.syncVibrators(manager.vibrators()); } // --- battery polling ----------------------------------------------------- @@ -166,10 +253,16 @@ function startBatteryPolling() { // --- 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). +// Renders both views from manager state. Called on registry changes, +// connection changes, and emergency stop; slider drags and waveform edits do +// not re-render (the manager/engine hold the values). function render() { + renderDeviceList(); + renderPatternRows(); + updateTransport(); +} + +function renderDeviceList() { const host = $("device-list"); const connected = manager.isConnected(); host.textContent = ""; @@ -262,7 +355,7 @@ function vibratorRow(v, connected) { } // Hold buttons: output runs at the hold level while pressed and returns to -// the slider value on release (handled by the manager). +// the base value on release (handled by the manager). Used by both modes. function wireHold(btn, id, kind) { btn.addEventListener("pointerdown", (e) => { e.preventDefault(); @@ -280,6 +373,185 @@ function wireHold(btn, id, kind) { btn.addEventListener("contextmenu", (e) => e.preventDefault()); } +// --- pattern view --------------------------------------------------------- + +function renderPatternRows() { + const host = $("pattern-rows"); + host.textContent = ""; + for (const v of manager.vibrators()) host.append(patternRow(v)); +} + +function patternRow(v) { + const row = document.createElement("div"); + row.className = "prow"; + + // Small unlabeled hold buttons, stacked vertically to leave the waveform + // maximum width. Same colors as the direct-control hold buttons. + const btns = document.createElement("div"); + btns.className = "pbtns"; + const maxBtn = document.createElement("button"); + maxBtn.type = "button"; + maxBtn.className = "hold hold-max glyph"; + maxBtn.textContent = "⏫"; + maxBtn.setAttribute("aria-label", `${v.deviceName} ${v.featureLabel}: hold to vibrate at maximum`); + maxBtn.title = "Hold to max"; + wireHold(maxBtn, v.id, "max"); + const stopBtn = document.createElement("button"); + stopBtn.type = "button"; + stopBtn.className = "hold hold-stop glyph"; + stopBtn.textContent = "⏹"; + stopBtn.setAttribute("aria-label", `${v.deviceName} ${v.featureLabel}: hold to stop`); + stopBtn.title = "Hold to stop"; + wireHold(stopBtn, v.id, "stop"); + btns.append(maxBtn, stopBtn); + row.append(btns); + + const wrap = document.createElement("div"); + wrap.className = "pwave-wrap"; + + // Waveform editor: viewBox 0 0 100 100 stretched to the row width; x maps + // to sample index phase*(N-1), y to intensity (top = 100%). + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + svg.setAttribute("class", "wave"); + svg.setAttribute("viewBox", "0 0 100 100"); + svg.setAttribute("preserveAspectRatio", "none"); + + const zero = document.createElementNS("http://www.w3.org/2000/svg", "line"); + zero.setAttribute("class", "wave-zero"); + zero.setAttribute("x1", "0"); + zero.setAttribute("x2", "100"); + zero.setAttribute("y1", "100"); + zero.setAttribute("y2", "100"); + svg.append(zero); + + const line = document.createElementNS("http://www.w3.org/2000/svg", "polyline"); + line.setAttribute("class", "wave-line"); + line.setAttribute("vector-effect", "non-scaling-stroke"); + svg.append(line); + + const head = document.createElementNS("http://www.w3.org/2000/svg", "line"); + head.setAttribute("class", "wave-head"); + head.setAttribute("vector-effect", "non-scaling-stroke"); + head.setAttribute("visibility", "hidden"); + head.setAttribute("y1", "0"); + head.setAttribute("y2", "100"); + svg.append(head); + + updateWaveLine(line, patternEngine.waveData(v.id)); + + let editing = false; + let editCol = null; + const applyEdit = (e) => { + const rect = svg.getBoundingClientRect(); + const x01 = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width)); + const y01 = Math.min(1, Math.max(0, 1 - (e.clientY - rect.top) / rect.height)); + const col = Math.round(x01 * (PATTERN_SAMPLES - 1)); + const data = patternEngine.waveData(v.id); + if (editCol === null || editCol === col) { + data[col] = y01 * 100; + } else { + // Fill the span between the last and current column (interpolated) + // so fast drags don't leave gaps. + const startVal = data[editCol]; + for (let i = Math.min(editCol, col); i <= Math.max(editCol, col); i++) { + const t = (i - editCol) / (col - editCol); + data[i] = startVal + (y01 * 100 - startVal) * t; + } + } + editCol = col; + updateWaveLine(line, data); + patternEngine.waveEdited(v.id); + }; + svg.addEventListener("pointerdown", (e) => { + e.preventDefault(); + svg.setPointerCapture(e.pointerId); + editing = true; + editCol = null; + applyEdit(e); + }); + svg.addEventListener("pointermove", (e) => { + if (!editing) return; + applyEdit(e); + }); + for (const ev of ["pointerup", "pointercancel"]) { + svg.addEventListener(ev, () => { + if (!editing) return; + editing = false; + savePatternState(); + }); + } + svg.addEventListener("contextmenu", (e) => e.preventDefault()); + + wrap.append(svg); + // Label sits inside the waveform's top-left corner so rows stay compact. + const tag = document.createElement("div"); + tag.className = "wave-tag"; + tag.textContent = `${v.deviceName} · ${v.featureLabel}`; + wrap.append(tag); + row.append(wrap); + return row; +} + +function updateWaveLine(line, data) { + const pts = []; + for (let i = 0; i < PATTERN_SAMPLES; i++) { + pts.push(`${((i / (PATTERN_SAMPLES - 1)) * 100).toFixed(2)},${(100 - data[i]).toFixed(2)}`); + } + line.setAttribute("points", pts.join(" ")); +} + +// Playhead: one rAF loop drives the scanning bar across every waveform while +// the pattern plays. +let headRaf = null; +function playheadFrame() { + headRaf = null; + const heads = document.querySelectorAll(".wave-head"); + if (!patternEngine.isPlaying()) { + for (const h of heads) h.setAttribute("visibility", "hidden"); + return; + } + const x = (patternEngine.phase() * 100).toFixed(2); + for (const h of heads) { + h.setAttribute("visibility", "visible"); + h.setAttribute("x1", x); + h.setAttribute("x2", x); + } + headRaf = requestAnimationFrame(playheadFrame); +} + +function ensurePlayhead() { + if (headRaf === null) headRaf = requestAnimationFrame(playheadFrame); +} + +function updateTransport() { + const playing = patternEngine.isPlaying(); + $("pat-play").classList.toggle("active", playing); + $("pat-pause").disabled = !playing; + ensurePlayhead(); +} + +$("pat-play").addEventListener("click", () => { + runCommand(() => patternEngine.play()); + updateTransport(); +}); +$("pat-restart").addEventListener("click", () => { + runCommand(() => patternEngine.restart()); + updateTransport(); +}); +$("pat-pause").addEventListener("click", () => { + runCommand(() => patternEngine.pause()); + updateTransport(); +}); +$("pat-stop").addEventListener("click", () => { + runCommand(() => patternEngine.stop()); + updateTransport(); +}); +$("pat-loop").addEventListener("change", () => { + patternEngine.setLoopSeconds(Number($("pat-loop").value)); + $("pat-loop").value = String(patternEngine.loopSeconds()); + savePatternState(); +}); + // --- connection ---------------------------------------------------------- async function connect() { @@ -293,6 +565,7 @@ async function connect() { batteryText.clear(); stopBatteryPolling(); manager.setVibrators([]); + patternEngine.syncVibrators([]); manager.handleDisconnect(); setPill("bad", "disconnected"); scheduleReconnect(); @@ -345,6 +618,7 @@ function scheduleReconnect() { $("estop").addEventListener("click", () => { // Unlatched: stop and reset everything now, but keep the app operable. runCommand(() => manager.emergencyStop({ latch: false })); + updateTransport(); }); $("rescan").addEventListener("click", () => { if (client?.connected) client.startScanning().catch((e) => log(`scan: ${e.message}`)); @@ -358,6 +632,7 @@ document.addEventListener("visibilitychange", () => { } else { manager.handleVisible(); } + updateTransport(); }); window.addEventListener("pagehide", () => manager.handlePageHide()); // Last-resort net: any rejection that escapes every handler must still stop @@ -366,5 +641,6 @@ window.addEventListener("unhandledrejection", () => manager.emergencyStop()); // --- boot ---------------------------------------------------------------- +loadPatternState(); connect(); log(`webapp loaded; ws target ${wsURL()}`); diff --git a/tsbridge/webapp/index.html b/tsbridge/webapp/index.html index 90f7e44..d5dca05 100644 --- a/tsbridge/webapp/index.html +++ b/tsbridge/webapp/index.html @@ -16,12 +16,38 @@
+ +