// tsbutt webapp — DOM wiring. All vibration logic lives in logic.js; this // 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, ButtplugClient, ButtplugClientConnectorException, DeviceOutput, InputType, OutputType, } from "./vendor/buttplug.mjs"; import { createVibrationManager, createPatternEngine, freehandIntensity, freehandShadeAlpha, clampGamma, vibratorId, PATTERN_SAMPLES, FREEHAND_MAX_SHADE_ALPHA, } from "./logic.js"; // --- helpers ------------------------------------------------------------- const $ = (id) => document.getElementById(id); function wsURL() { const scheme = location.protocol === "https:" ? "wss:" : "ws:"; return `${scheme}//${location.host}/`; } // --- server endpoint ------------------------------------------------------ // The WebSocket endpoint the webapp talks to. Empty = this page's own // server (the tsbridge proxy). A custom endpoint — e.g. ws://localhost:12345 // for Intiface Central running on the local machine — lets the page be used // without tsbridge at all. const ENDPOINT_STORE_KEY = "tsbutt.endpoint"; let customEndpoint = loadStoredEndpoint(); function loadStoredEndpoint() { try { return localStorage.getItem(ENDPOINT_STORE_KEY) ?? ""; } catch { return ""; } } function storeEndpoint(ep) { try { if (ep) { localStorage.setItem(ENDPOINT_STORE_KEY, ep); } else { localStorage.removeItem(ENDPOINT_STORE_KEY); } } catch { /* private mode etc. — the endpoint just won't persist */ } } // normalizeEndpoint turns user input into a ws:// or wss:// URL. A bare // host[:port][/path] is accepted and gets the page's own scheme (so // "localhost:12345" works); full URLs are used as-is after validation. function normalizeEndpoint(input) { const raw = String(input ?? "").trim().replace(/\/+$/, ""); if (!raw) return ""; const withScheme = /^wss?:\/\//i.test(raw) ? raw : `${location.protocol === "https:" ? "wss:" : "ws:"}//${raw}`; let url; try { url = new URL(withScheme); } catch { throw new Error(`not a valid WebSocket address: ${raw}`); } if ((url.protocol !== "ws:" && url.protocol !== "wss:") || !url.hostname) { throw new Error(`not a valid WebSocket address: ${raw}`); } return withScheme; } // Switch servers: tear the current client down (its shutdown sends // stop-all, so toys are never left running) and connect to the endpoint. async function reconnectNow() { if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; } const old = client; client = null; // stale events from `old` are ignored via isCurrent guards if (old?.connected) { try { await old.disconnect(); } catch { /* best effort; the new connection replaces it either way */ } } intentionallyClosed = false; reconnectDelay = 500; connect(); } $("endpoint-apply").addEventListener("click", () => { let ep; try { ep = normalizeEndpoint($("endpoint").value); } catch (err) { showError(`Server: ${err.message}`); return; } customEndpoint = ep; storeEndpoint(ep); $("endpoint").value = ep; log(`endpoint set: ${ep || "default (this page's server)"}`); closeSettings(); reconnectNow(); }); $("endpoint-reset").addEventListener("click", () => { customEndpoint = ""; storeEndpoint(""); $("endpoint").value = ""; log("endpoint reset to default (this page's server)"); closeSettings(); reconnectNow(); }); // --- settings panel --------------------------------------------------------- function openSettings() { $("settings-overlay").classList.remove("hidden"); $("endpoint").focus(); } function closeSettings() { $("settings-overlay").classList.add("hidden"); } $("settings-btn").addEventListener("click", openSettings); $("settings-close").addEventListener("click", closeSettings); // Clicks on the dimmed backdrop close the panel; clicks inside it do not. $("settings-overlay").addEventListener("click", (e) => { if (e.target === $("settings-overlay")) closeSettings(); }); document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !$("settings-overlay").classList.contains("hidden")) { closeSettings(); } }); function log(line) { const el = $("log"); el.textContent += `${new Date().toISOString().slice(11, 19)} ${line}\n`; while (el.textContent.split("\n").length > 200) { el.textContent = el.textContent.slice(el.textContent.indexOf("\n") + 1); } } let bannerTimer = null; function showError(msg) { const banner = $("banner"); banner.classList.remove("hidden"); banner.textContent = msg; clearTimeout(bannerTimer); bannerTimer = setTimeout(() => banner.classList.add("hidden"), 8000); } $("banner").addEventListener("click", () => $("banner").classList.add("hidden")); // --- manager wiring ------------------------------------------------------ // 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)); }, stopAll() { if (!client) throw new Error("not connected"); return client.stopAllDevices(); }, now: () => performance.now(), schedule: (fn, ms) => setTimeout(fn, ms), cancel: (h) => clearTimeout(h), onError(err) { showError(`Command failed: ${err?.message ?? err}`); log(`command error: ${err?.message ?? err}`); }, onEmergencyStop() { // Every mode stops its own driver here; the manager handles the rest. patternEngine.stop(); freehand.active = false; updateFhSelection(); }, onChange: render, }); function runCommand(fn) { try { fn(); } catch (err) { manager.handleCommandError(err); } } // --- 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()); } // --- freehand driver ------------------------------------------------------- // Per-vibrator geometry in canvas-normalized coordinates: x, y in 0..1 of // the canvas size, r in 0..1 of the canvas width, gamma = falloff exponent. // The freehand mode's provider converts these to pixels at drive time. const freehand = { submode: "edit", // "edit" | "play" active: false, // pointer held in play mode px: 0, py: 0, points: new Map(), // id -> {x, y, r, gamma} }; const FREEHAND_STORE_KEY = "tsbutt.freehand.v1"; function saveFreehandState() { try { localStorage.setItem( FREEHAND_STORE_KEY, JSON.stringify({ points: Object.fromEntries(freehand.points) }), ); } catch { /* private mode etc. — points just won't persist */ } } function loadFreehandState() { let parsed = null; try { parsed = JSON.parse(localStorage.getItem(FREEHAND_STORE_KEY) ?? "null"); } catch { /* fall through to defaults */ } const pts = parsed?.points; if (!pts || typeof pts !== "object") return; for (const [id, p] of Object.entries(pts)) { if (!p || typeof p !== "object") continue; const x = Number(p.x); const y = Number(p.y); const r = Number(p.r); if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(r)) continue; freehand.points.set(id, { x: Math.min(1, Math.max(0, x)), y: Math.min(1, Math.max(0, y)), r: Math.min(0.45, Math.max(0.03, r)), gamma: clampGamma(p.gamma), }); } } // New vibrators get a default point spread across the canvas; removed ones // are dropped. function syncFreehandPoints() { const vibrators = manager.vibrators(); const ids = new Set(vibrators.map((v) => v.id)); for (const id of [...freehand.points.keys()]) { if (!ids.has(id)) freehand.points.delete(id); } vibrators.forEach((v, i) => { if (!freehand.points.has(v.id)) { freehand.points.set(v.id, { x: (i + 1) / (vibrators.length + 1), y: 0.5, r: 0.16, gamma: 1, }); } }); } const freehandProvider = (st) => { if (!freehand.active) return 0; const p = freehand.points.get(st.id); if (!p || fhW === 0 || fhW === undefined) return 0; const vx = p.x * fhW; const vy = p.y * fhH; const vr = Math.max(1, p.r * fhW); const d = Math.hypot(freehand.px - vx, freehand.py - vy) / vr; return freehandIntensity(d, p.gamma); }; // --- 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(); }, }, freehand: { view: "view-freehand", tab: "tab-freehand", activate() { manager.setBaseProvider(freehandProvider); }, deactivate() { // Release any held touch so output rests at zero. freehand.active = false; manager.refreshBase(); }, }, }; 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; let reconnectTimer = null; let reconnectDelay = 500; let intentionallyClosed = false; const batteryText = new Map(); // deviceIndex -> "Battery 87%" function setPill(state, text) { const pill = $("status-pill"); pill.className = `pill pill-${state}`; pill.textContent = text; } // 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); patternEngine.syncVibrators(manager.vibrators()); syncFreehandPoints(); } // --- battery polling ----------------------------------------------------- function stopBatteryPolling() { // 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 startBatteryPolling() { stopBatteryPolling(); 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 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(); renderFreehand(); updateTransport(); } function renderDeviceList() { 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); } 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 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 base value on release (handled by the manager). Used by both modes. 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()); } // --- 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(); }); // --- freehand canvas ------------------------------------------------------- // All geometry is in canvas pixels; the viewBox matches the element size so // rings stay circular and pointer math is 1:1. let fhW = 0; let fhH = 0; const fhEls = new Map(); // id -> {grad, ring, dot, label, rHandle, cHandle} let fhDrag = null; // {kind: "move"|"radius"|"curve", id, startGamma, startY} const FH_SVG_NS = "http://www.w3.org/2000/svg"; // Distinct per-vibrator colors, assigned deterministically from the // vibrator id so a given toy's vibrator keeps its color across reconnects // and re-renders. const FH_PALETTE = [ "#7c5cff", // violet "#2ed573", // green "#ffa502", // orange "#3aa8ff", // blue "#ff7ac6", // pink "#ffd93a", // yellow "#4adbc8", // teal "#a0a8b8", // slate ]; function fhColor(id) { let h = 0; for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) >>> 0; return FH_PALETTE[h % FH_PALETTE.length]; } function fhSlug(id) { return id.replace(/[^A-Za-z0-9_-]/g, "_"); } function fhPoint(e) { const svg = $("freehand-canvas"); const rect = svg.getBoundingClientRect(); return { x: ((e.clientX - rect.left) * fhW) / Math.max(1, rect.width), y: ((e.clientY - rect.top) * fhH) / Math.max(1, rect.height), }; } function fhGeometry(id) { const p = freehand.points.get(id); if (!p || !fhW) return null; return { p, x: p.x * fhW, y: p.y * fhH, r: Math.max(10, p.r * fhW) }; } function fhEl(tag, attrs) { const el = document.createElementNS(FH_SVG_NS, tag); for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, String(v)); return el; } function createFhEls(defs, host, id) { const gradId = `fhg-${fhSlug(id)}`; const grad = fhEl("radialGradient", { id: gradId }); defs.append(grad); const g = fhEl("g", { class: "fh-point" }); const ring = fhEl("circle", { class: "fh-ring", fill: `url(#${gradId})` }); const dot = fhEl("circle", { class: "fh-dot", r: 7 }); const label = fhEl("text", { class: "fh-label", "text-anchor": "middle" }); const rHandle = fhEl("circle", { class: "fh-handle fh-handle-radius", r: 7 }); const cHandle = fhEl("circle", { class: "fh-handle fh-handle-curve", r: 7 }); g.append(ring, dot, label, rHandle, cHandle); host.append(g); const els = { g, grad, ring, dot, label, rHandle, cHandle }; fhEls.set(id, els); return els; } function updateFhGradient(els, gamma, color) { // The gradient's alpha profile visualizes the falloff curve's derivative // (see freehandShadeAlpha); the hue identifies the vibrator. const STOPS = 10; els.grad.textContent = ""; for (let i = 0; i <= STOPS; i++) { const d = i / STOPS; const stop = fhEl("stop", { offset: d }); stop.setAttribute("stop-color", color); stop.setAttribute("stop-opacity", freehandShadeAlpha(d, gamma).toFixed(3)); els.grad.append(stop); } } // Handle screen positions. Handles are clamped inside the canvas so a ring // pushed against an edge never strands its resize/curve handles offscreen. function fhHandlePositions(geo) { const { x, y, r } = geo; const clampX = (v) => Math.min(fhW - 12, Math.max(12, v)); const clampY = (v) => Math.min(fhH - 12, Math.max(12, v)); return { radius: { x: clampX(x + r * Math.SQRT1_2), y: clampY(y + r * Math.SQRT1_2) }, curve: { x: clampX(x), y: clampY(y - r) }, }; } function positionFh(els, id, featureLabel) { const geo = fhGeometry(id); if (!geo) return; const { p, x, y, r } = geo; const color = fhColor(id); const handles = fhHandlePositions(geo); els.ring.setAttribute("cx", x); els.ring.setAttribute("cy", y); els.ring.setAttribute("r", r); els.ring.setAttribute("stroke", color); els.dot.setAttribute("cx", x); els.dot.setAttribute("cy", y); els.dot.setAttribute("fill", color); els.label.textContent = featureLabel; els.label.setAttribute("fill", color); els.label.setAttribute("x", x); els.label.setAttribute("y", Math.min(fhH - 4, y + r + 12)); // Radius handle at 45° below-right on the ring; curve handle at the top. els.rHandle.setAttribute("cx", handles.radius.x); els.rHandle.setAttribute("cy", handles.radius.y); els.cHandle.setAttribute("cx", handles.curve.x); els.cHandle.setAttribute("cy", handles.curve.y); updateFhGradient(els, p.gamma, color); const edit = freehand.submode === "edit"; for (const h of [els.rHandle, els.cHandle]) { h.setAttribute("visibility", edit ? "visible" : "hidden"); } } function updateFhSelection() { const sel = $("fh-selection"); if (!freehand.active) { sel.setAttribute("visibility", "hidden"); return; } sel.setAttribute("visibility", "visible"); sel.setAttribute("cx", freehand.px); sel.setAttribute("cy", freehand.py); } function renderFreehand() { const defs = $("fh-defs"); const host = $("fh-points"); const ids = new Set(manager.vibrators().map((v) => v.id)); for (const [id, els] of fhEls) { if (!ids.has(id)) { els.g?.remove(); document.getElementById(`fhg-${fhSlug(id)}`)?.remove(); fhEls.delete(id); } } for (const v of manager.vibrators()) { const els = fhEls.get(v.id) ?? createFhEls(defs, host, v.id); positionFh(els, v.id, v.featureLabel); } renderFhKey(); updateFhSelection(); } // Lower-right key: color swatch plus toy name and vibrator label for every // point on the canvas. function renderFhKey() { const key = $("fh-key"); key.textContent = ""; const vibrators = manager.vibrators(); key.classList.toggle("hidden", vibrators.length === 0); for (const v of vibrators) { const row = document.createElement("div"); row.className = "fh-key-row"; const swatch = document.createElement("span"); swatch.className = "fh-key-swatch"; swatch.style.background = fhColor(v.id); const text = document.createElement("span"); text.textContent = `${v.deviceName} · ${v.featureLabel}`; row.append(swatch, text); key.append(row); } } // --- freehand interaction -------------------------------------------------- function fhHitTest(pt) { const vibrators = manager.vibrators(); // Later vibrators render on top, so test them first. for (let i = vibrators.length - 1; i >= 0; i--) { const v = vibrators[i]; const geo = fhGeometry(v.id); if (!geo) continue; const { x, y, r } = geo; const handles = fhHandlePositions(geo); const d = Math.hypot(pt.x - x, pt.y - y); const cHandleD = Math.hypot(pt.x - handles.curve.x, pt.y - handles.curve.y); const rHandleD = Math.hypot(pt.x - handles.radius.x, pt.y - handles.radius.y); if (cHandleD <= 16) return { kind: "curve", id: v.id }; if (rHandleD <= 16) return { kind: "radius", id: v.id }; if (Math.abs(d - r) <= 12) return { kind: "radius", id: v.id }; if (d < r) return { kind: "move", id: v.id }; } return null; } function fhApplyMove(pt, id) { const p = freehand.points.get(id); if (!p || !fhW) return; p.x = Math.min(1, Math.max(0, pt.x / fhW)); p.y = Math.min(1, Math.max(0, pt.y / fhH)); } function fhApplyRadius(pt, id) { const geo = fhGeometry(id); const p = freehand.points.get(id); if (!geo || !p || !fhW) return; const dist = Math.hypot(pt.x - geo.x, pt.y - geo.y); p.r = Math.min(0.45, Math.max(0.03, dist / fhW)); } function fhApplyCurve(pt, id) { const p = freehand.points.get(id); if (!p) return; // Vertical drag on the top handle: up = steeper falloff, down = flatter. p.gamma = clampGamma(fhDrag.startGamma + (fhDrag.startY - pt.y) * 0.02); } function fhChanged() { renderFreehand(); // While a touch is held in play mode this drives output; in edit mode the // provider is inactive and the refresh is a no-op. manager.refreshBase(); } function setFreehandSubmode(sub) { freehand.submode = sub; if (sub !== "play") { freehand.active = false; manager.refreshBase(); } $("fh-edit").classList.toggle("active", sub === "edit"); $("fh-play").classList.toggle("active", sub === "play"); $("fh-hint-edit").classList.toggle("hidden", sub !== "edit"); $("fh-hint-play").classList.toggle("hidden", sub !== "play"); renderFreehand(); } $("fh-edit").addEventListener("click", () => setFreehandSubmode("edit")); $("fh-play").addEventListener("click", () => setFreehandSubmode("play")); { const svg = $("freehand-canvas"); svg.addEventListener("pointerdown", (e) => { e.preventDefault(); const pt = fhPoint(e); if (freehand.submode === "play") { freehand.active = true; freehand.px = pt.x; freehand.py = pt.y; svg.setPointerCapture(e.pointerId); manager.refreshBase(); updateFhSelection(); return; } const hit = fhHitTest(pt); if (!hit) return; svg.setPointerCapture(e.pointerId); fhDrag = { ...hit, startGamma: freehand.points.get(hit.id)?.gamma ?? 1, startY: pt.y, }; if (hit.kind === "move") fhApplyMove(pt, hit.id); fhChanged(); }); svg.addEventListener("pointermove", (e) => { const pt = fhPoint(e); if (freehand.submode === "play") { if (!freehand.active) return; freehand.px = pt.x; freehand.py = pt.y; manager.refreshBase(); updateFhSelection(); return; } if (!fhDrag) return; if (fhDrag.kind === "move") fhApplyMove(pt, fhDrag.id); else if (fhDrag.kind === "radius") fhApplyRadius(pt, fhDrag.id); else fhApplyCurve(pt, fhDrag.id); fhChanged(); }); for (const ev of ["pointerup", "pointercancel", "lostpointercapture"]) { svg.addEventListener(ev, () => { if (freehand.submode === "play") { if (!freehand.active) return; freehand.active = false; manager.refreshBase(); updateFhSelection(); return; } if (!fhDrag) return; fhDrag = null; saveFreehandState(); }); } svg.addEventListener("contextmenu", (e) => e.preventDefault()); } new ResizeObserver(() => { const wrap = $("freehand-wrap"); if (!wrap.clientWidth) return; fhW = wrap.clientWidth; fhH = wrap.clientHeight; $("freehand-canvas").setAttribute("viewBox", `0 0 ${fhW} ${fhH}`); renderFreehand(); }).observe($("freehand-wrap")); // --- connection ---------------------------------------------------------- async function connect() { if (client?.connected) return; intentionallyClosed = false; const thisClient = new ButtplugClient("tsbutt"); // Only the current client's events may touch shared state: a replaced // client can still fire its own disconnect while we are connecting to the // new endpoint, and its handlers must not schedule reconnects or clear // the new client's registry. const isCurrent = () => client === thisClient; // Register all listeners before connecting (buttplug.js requirement). thisClient.on("disconnect", () => { if (!isCurrent()) return; features.clear(); batteryText.clear(); stopBatteryPolling(); manager.setVibrators([]); patternEngine.syncVibrators([]); manager.handleDisconnect(); setPill("bad", "disconnected"); scheduleReconnect(); }); thisClient.on("deviceadded", () => { if (!isCurrent()) return; refreshRegistry(); startBatteryPolling(); log(`device added: ${[...client.devices.values()].at(-1)?.name ?? "?"}`); }); thisClient.on("deviceremoved", (d) => { if (!isCurrent()) return; refreshRegistry(); log(`device removed: ${d?.name ?? "?"}`); }); thisClient.on("scanningfinished", () => { /* registry is already event-driven; nothing to do */ }); client = thisClient; const connector = new ButtplugBrowserWebsocketClientConnector(wsURL()); try { setPill("off", "connecting…"); await thisClient.connect(connector); setPill("on", "connected"); reconnectDelay = 500; manager.handleConnected(); refreshRegistry(); startBatteryPolling(); await thisClient.startScanning(); } catch (err) { setPill("bad", "connection failed"); log(`connect failed: ${err?.message ?? err}`); if (!(err instanceof ButtplugClientConnectorException)) { showError(`Connection failed: ${err?.message ?? err}`); } scheduleReconnect(); } } function scheduleReconnect() { if (intentionallyClosed || reconnectTimer) return; reconnectTimer = setTimeout(() => { reconnectTimer = null; reconnectDelay = Math.min(reconnectDelay * 2, 15000); connect(); }, reconnectDelay); log(`reconnecting in ${reconnectDelay} ms`); } // --- transport buttons --------------------------------------------------- $("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}`)); }); // --- safety: page lifecycle ---------------------------------------------- document.addEventListener("visibilitychange", () => { if (document.visibilityState === "hidden") { manager.handlePageHide(); } else { manager.handleVisible(); } updateTransport(); }); window.addEventListener("pagehide", () => manager.handlePageHide()); // Last-resort net: any rejection that escapes every handler must still stop // the toys. (All command paths are already routed through logic.js dispatch.) window.addEventListener("unhandledrejection", () => manager.emergencyStop()); // --- boot ---------------------------------------------------------------- loadPatternState(); loadFreehandState(); $("endpoint").value = customEndpoint; connect(); log(`webapp loaded; ws target ${wsURL()}`);