feat: browser simulator served by the controller, desktop build, browser bridge
- led-simulator: the rig runs the C++ led-driver as WebAssembly (sim-driver/), one single-threaded worker per bar, no cross-origin isolation needed. Rooms (one JSON per room) with an on-page editor, and a pattern gallery. The Python server, Pyodide boot and ring buffer are removed. - sim-controller sim_rig.c: serves /sim/ from an embedded pack, the page's WebSocket and the rooms/flash API. The desktop build embeds it too. - bridge.c: a "browser" bridge kind that carries ESP-NOW frames to the page; devices announced through it are marked sim. - UI: Simulator in the Menu, split view with resize and pop-out, swipe between controller and rig on phones; SIM/REAL badges in Devices. - Fades: preset pushes and Wi-Fi driver bodies always carry fade and beat_time, so "off" no longer inherits an earlier fade. - Also the sequences-v2 work in progress: desktop port, bridge firmware, serial bridge, Wi-Fi drivers, sequence timeline, audio and API changes. - led-driver: ESP-NOW link, beat sync, control messages, sim hooks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
698c1463c0
commit
581b751904
506 files changed
+42336
-3599
No files matched your search
+18
-7
@@ -220,7 +220,7 @@ async function runEspnowPing({ btn, dot, statusEl } = {}) {
|
||||
function applyEspnowPingToDeviceRows(responses, phase) {
|
||||
const container = document.getElementById('devices-list-modal');
|
||||
if (!container) return;
|
||||
container.querySelectorAll('.profiles-row[data-device-transport="espnow"]').forEach((row) => {
|
||||
container.querySelectorAll('.profiles-row[data-device-transport="espnow"], .profiles-row[data-device-transport="wifi"]').forEach((row) => {
|
||||
const dot = row.querySelector('.device-status-dot');
|
||||
if (!dot) return;
|
||||
if (phase === 'pinging') {
|
||||
@@ -427,14 +427,15 @@ async function createDeviceFromModal() {
|
||||
if (statusEl) statusEl.textContent = 'Name is required';
|
||||
return;
|
||||
}
|
||||
if (mac.length !== 12) {
|
||||
if (transport === 'wifi') {
|
||||
if (!address) {
|
||||
if (statusEl) statusEl.textContent = 'Address is required for Wi-Fi devices (the driver hostname, e.g. led20)';
|
||||
return;
|
||||
}
|
||||
} else if (mac.length !== 12) {
|
||||
if (statusEl) statusEl.textContent = 'MAC must be 12 hex characters';
|
||||
return;
|
||||
}
|
||||
if (transport === 'wifi' && !address) {
|
||||
if (statusEl) statusEl.textContent = 'Address is required for Wi-Fi devices';
|
||||
return;
|
||||
}
|
||||
|
||||
if (btn) {
|
||||
btn.disabled = true;
|
||||
@@ -446,7 +447,7 @@ async function createDeviceFromModal() {
|
||||
name,
|
||||
transport,
|
||||
type: 'led',
|
||||
mac,
|
||||
mac: transport === 'wifi' ? undefined : mac,
|
||||
address: transport === 'wifi' ? address : mac,
|
||||
};
|
||||
const res = await fetch('/devices', {
|
||||
@@ -549,6 +550,15 @@ function renderDevicesList(devices) {
|
||||
label.style.flex = '1';
|
||||
label.style.minWidth = '100px';
|
||||
|
||||
// Simulated (a driver of the rig page at /sim/, heard on the browser bridge) or a real board
|
||||
const isSim = !!(dev && dev.sim);
|
||||
const kind = document.createElement('span');
|
||||
kind.className = `device-kind-badge device-kind-badge--${isSim ? 'sim' : 'real'}`;
|
||||
kind.textContent = isSim ? 'sim' : 'real';
|
||||
kind.title = isSim
|
||||
? 'Simulated: a driver on the rig page (/sim/), reached over the browser bridge'
|
||||
: 'A real board';
|
||||
|
||||
const editBtn = document.createElement('button');
|
||||
editBtn.className = 'btn btn-secondary btn-small';
|
||||
editBtn.textContent = 'Edit';
|
||||
@@ -576,6 +586,7 @@ function renderDevicesList(devices) {
|
||||
|
||||
row.appendChild(dot);
|
||||
row.appendChild(label);
|
||||
row.appendChild(kind);
|
||||
row.appendChild(editBtn);
|
||||
row.appendChild(identifyBtn);
|
||||
row.appendChild(deleteBtn);
|
||||
|
||||
+154
-2
@@ -147,7 +147,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
const apPw = document.getElementById('ap-password-input');
|
||||
if (apPw) apPw.value = data.ap_password || '';
|
||||
const bridge = document.getElementById('bridge-input');
|
||||
if (bridge) bridge.value = data.bridge || '';
|
||||
if (bridge) bridge.value = Array.isArray(data.bridges) ? data.bridges.join(', ') : (data.bridge || '');
|
||||
staticIpsList.innerHTML = '';
|
||||
(Array.isArray(data.static_ips) ? data.static_ips : []).forEach(addStaticIpRow);
|
||||
}
|
||||
@@ -260,6 +260,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
settingsModal.classList.add('active');
|
||||
switchSettingsTab('controller');
|
||||
loadDeviceSettings();
|
||||
loadBridgeSettings();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -311,6 +312,157 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
});
|
||||
}
|
||||
// Bridges: USB boards and network boards (GET/PUT /settings/bridge)
|
||||
const bridgeSection = document.getElementById('bridge-section');
|
||||
const bridgeList = document.getElementById('bridge-list');
|
||||
const bridgeAddInput = document.getElementById('bridge-add-input');
|
||||
const bridgeAddForm = document.getElementById('bridge-add-form');
|
||||
const bridgePorts = document.getElementById('bridge-ports');
|
||||
const bridgeRefresh = document.getElementById('bridge-refresh-btn');
|
||||
let bridgeAddrs = [];
|
||||
|
||||
function describeBridge(b) {
|
||||
const st = b.status || {};
|
||||
if (b.kind !== 'serial') return 'Network bridge · sent ' + (st.tx || 0) + ' · received ' + (st.rx || 0);
|
||||
if (!st.linked) return 'Not connected (waiting for the board on ' + st.port + ')';
|
||||
return ['Connected', 'MAC ' + st.mac, 'channel ' + st.channel, 'microphone ' + (st.mic ? 'yes' : 'no'),
|
||||
'sent ' + st.sent, 'received ' + st.rx].join(' · ');
|
||||
}
|
||||
|
||||
function syncBridgeInput() {
|
||||
const simInput = document.getElementById('bridge-input');
|
||||
if (simInput) simInput.value = bridgeAddrs.join(', ');
|
||||
}
|
||||
|
||||
function renderBridges(data) {
|
||||
bridgeList.textContent = '';
|
||||
for (const b of data.bridges || []) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'bridge-row';
|
||||
const head = document.createElement('div');
|
||||
const name = document.createElement('strong');
|
||||
name.textContent = b.addr;
|
||||
head.append(name);
|
||||
const status = document.createElement('small');
|
||||
status.className = 'muted-text';
|
||||
status.textContent = ' ' + describeBridge(b);
|
||||
head.append(status);
|
||||
row.append(head);
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'btn-group';
|
||||
if (b.kind === 'serial') {
|
||||
const ch = document.createElement('input');
|
||||
ch.type = 'number';
|
||||
ch.min = '1';
|
||||
ch.max = '13';
|
||||
ch.placeholder = 'channel';
|
||||
ch.value = b.status && b.status.channel ? String(b.status.channel) : '';
|
||||
ch.setAttribute('aria-label', 'Radio channel for ' + b.addr);
|
||||
const setCh = document.createElement('button');
|
||||
setCh.type = 'button';
|
||||
setCh.className = 'btn btn-secondary';
|
||||
setCh.textContent = 'Set channel';
|
||||
setCh.addEventListener('click', () => setBridgeChannel(b.addr, ch.value));
|
||||
actions.append(ch, setCh);
|
||||
}
|
||||
const remove = document.createElement('button');
|
||||
remove.type = 'button';
|
||||
remove.className = 'btn btn-secondary';
|
||||
remove.textContent = 'Remove';
|
||||
remove.addEventListener('click', () => putBridges(bridgeAddrs.filter((a) => a !== b.addr), 'Bridge removed.'));
|
||||
actions.append(remove);
|
||||
row.append(actions);
|
||||
bridgeList.append(row);
|
||||
}
|
||||
if (!(data.bridges || []).length) {
|
||||
const none = document.createElement('small');
|
||||
none.className = 'muted-text';
|
||||
none.textContent = 'No bridges: the controller uses the radio.';
|
||||
bridgeList.append(none);
|
||||
}
|
||||
bridgePorts.textContent = '';
|
||||
for (const port of data.ports || []) {
|
||||
if (bridgeAddrs.includes(port)) continue;
|
||||
const opt = document.createElement('option');
|
||||
opt.value = port;
|
||||
bridgePorts.append(opt);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadBridgeSettings() {
|
||||
if (!bridgeSection) return;
|
||||
try {
|
||||
const data = await fetch('/settings/bridge', { cache: 'no-store' }).then((r) => r.json());
|
||||
bridgeSection.hidden = !data.supported;
|
||||
if (!data.supported) return;
|
||||
bridgeAddrs = (data.bridges || []).map((b) => b.addr);
|
||||
renderBridges(data);
|
||||
syncBridgeInput();
|
||||
} catch (error) {
|
||||
bridgeList.textContent = 'Could not read the bridges.';
|
||||
}
|
||||
}
|
||||
|
||||
async function putBridges(addrs, okText) {
|
||||
try {
|
||||
const response = await fetch('/settings/bridge', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ bridges: addrs }),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (response.ok) {
|
||||
showSettingsMessage(okText, 'success');
|
||||
} else {
|
||||
showSettingsMessage(`Error: ${result.error || 'Failed to update the bridges'}`, 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showSettingsMessage(`Error: ${error.message}`, 'error');
|
||||
}
|
||||
loadBridgeSettings();
|
||||
setTimeout(loadBridgeSettings, 1500); // a board answers its link a moment later
|
||||
}
|
||||
|
||||
async function setBridgeChannel(addr, raw) {
|
||||
const channel = parseInt(raw, 10);
|
||||
if (Number.isNaN(channel) || channel < 1 || channel > 13) {
|
||||
showSettingsMessage('Radio channel must be between 1 and 13', 'error');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch('/settings/bridge', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ addr, channel }),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (response.ok) {
|
||||
showSettingsMessage('Channel set on the board.', 'success');
|
||||
} else {
|
||||
showSettingsMessage(`Error: ${result.error || 'Failed to set the channel'}`, 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showSettingsMessage(`Error: ${error.message}`, 'error');
|
||||
}
|
||||
loadBridgeSettings();
|
||||
}
|
||||
|
||||
if (bridgeRefresh) bridgeRefresh.addEventListener('click', loadBridgeSettings);
|
||||
|
||||
if (bridgeAddForm) {
|
||||
bridgeAddForm.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
const addr = bridgeAddInput.value.trim();
|
||||
if (!addr) return;
|
||||
if (bridgeAddrs.includes(addr)) {
|
||||
showSettingsMessage('That bridge is already in the list', 'error');
|
||||
return;
|
||||
}
|
||||
bridgeAddInput.value = '';
|
||||
putBridges([...bridgeAddrs, addr], 'Bridge added.');
|
||||
});
|
||||
}
|
||||
|
||||
const networkForm = document.getElementById('network-form');
|
||||
if (networkForm) {
|
||||
networkForm.addEventListener('submit', async (e) => {
|
||||
@@ -340,7 +492,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
hostname,
|
||||
static_ips: staticIps,
|
||||
ap_password: apPassword,
|
||||
bridge: (document.getElementById('bridge-input') || { value: '' }).value.trim(),
|
||||
bridges: (document.getElementById('bridge-input') || { value: '' }).value.split(',').map((v) => v.trim()).filter(Boolean),
|
||||
ap_enabled: !apToggle || apToggle.getAttribute('aria-pressed') === 'true',
|
||||
}),
|
||||
});
|
||||
|
||||
+15
-3
@@ -283,7 +283,6 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
const presetBrightnessInput = document.getElementById('preset-brightness-input');
|
||||
const presetDelayInput = document.getElementById('preset-delay-input');
|
||||
const presetFadeInput = document.getElementById('preset-fade-input');
|
||||
const presetBeatTimeInput = document.getElementById('preset-beat-time-input');
|
||||
const presetDelayField = presetDelayInput ? presetDelayInput.closest('.preset-editor-field') : null;
|
||||
const presetBackgroundInput = document.getElementById('preset-background-input');
|
||||
const presetBackgroundButton = document.getElementById('preset-background-btn');
|
||||
@@ -750,7 +749,6 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
presetBrightnessInput.value = preset.brightness || 0;
|
||||
presetDelayInput.value = preset.delay || 0;
|
||||
if (presetFadeInput) presetFadeInput.value = preset.fade || preset.f || 0;
|
||||
if (presetBeatTimeInput) presetBeatTimeInput.checked = !!(preset.beat_time || preset.tb);
|
||||
if (presetBackgroundInput) {
|
||||
const rawBgRef = preset.background_palette_ref ?? preset.backgroundPaletteRef;
|
||||
let bgRef = null;
|
||||
@@ -988,7 +986,6 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
brightness: presetBrightnessInput ? parseInt(presetBrightnessInput.value, 10) || 0 : 0,
|
||||
delay: presetDelayInput ? parseInt(presetDelayInput.value, 10) || 0 : 0,
|
||||
fade: presetFadeInput ? Math.max(0, Math.min(10000, parseInt(presetFadeInput.value, 10) || 0)) : 0,
|
||||
beat_time: !!(presetBeatTimeInput && presetBeatTimeInput.checked),
|
||||
background: presetBackgroundInput ? presetBackgroundInput.value : '#000000',
|
||||
background_palette_ref: currentBackgroundPaletteRef != null ? currentBackgroundPaletteRef : null,
|
||||
auto: presetManualModeInput ? !presetManualModeInput.checked : true,
|
||||
@@ -2008,6 +2005,9 @@ const sendPresetViaEspNow = async (
|
||||
n5: coercePresetInt(preset.n5),
|
||||
n6: presetWireN6(preset),
|
||||
manual_beat_n: coerceManualBeatN(preset),
|
||||
// Always sent: a driver applies a preset over the one it runs, so a missing fade would carry over
|
||||
fade: Math.max(0, Math.min(10000, Number(preset.fade ?? preset.f) || 0)),
|
||||
beat_time: preset.beat_time === true || preset.tb === true || preset.tb === 1,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -2142,6 +2142,18 @@ async function sendZonePresetSelection(zoneId, tabData, presetId, preset, allPre
|
||||
? await zm.resolveDeviceNamesForZonePreset(tabData, pid)
|
||||
: [];
|
||||
const groupIds = zoneGroupIdsFromTabData(tabData);
|
||||
// Tell the controller first: a looping preset takes over the zone from a looping sequence, and a
|
||||
// one-shot sequence goes back to this preset when it ends. The drivers get it from the push below.
|
||||
try {
|
||||
await fetch(`/zones/${encodeURIComponent(String(zoneId))}/play`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({ preset_id: pid, drivers: false }),
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('zone play:', e);
|
||||
}
|
||||
document.querySelectorAll('#presets-list-zone .sequence-tile-main.active').forEach((b) => b.classList.remove('active'));
|
||||
await sendPresetViaEspNow(pid, body, names, false, false, '2', {
|
||||
select: true,
|
||||
groupIds,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+69
-1017
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,360 @@
|
||||
// Simulator in the Menu (host builds only, which serve the simulated rig at /sim/).
|
||||
//
|
||||
// Wide screens: the rig opens beside the UI, the controller on the left and the rig on the right, with a divider to
|
||||
// resize them. Narrow screens (phones): the controller and the rig are two full-width pages; swipe left and right,
|
||||
// or tap the pager at the bottom, to switch. Both stay loaded either way, so the rig's bars keep running. Pop out
|
||||
// moves the rig to its own window. Whether it is open, its width and the page shown are remembered in this browser.
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const KEY = 'ledController.simSplit';
|
||||
const MIN_W = 320;
|
||||
const NARROW = 900; // below this: two pages to swipe between, not side by side
|
||||
const LOCK_PX = 10; // movement before a touch counts as a swipe or a scroll
|
||||
const DRAG_CLASS = 'sim-swipe-dragging';
|
||||
|
||||
let pane = null;
|
||||
let pager = null;
|
||||
let width = 0;
|
||||
let page = 0; // swipe mode: 0 the controller, 1 the rig
|
||||
|
||||
function load() {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(KEY)) || {};
|
||||
} catch (_e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function save(state) {
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(Object.assign(load(), state)));
|
||||
} catch (_e) {
|
||||
// storage unavailable: the split lasts for this page only
|
||||
}
|
||||
}
|
||||
|
||||
function isOpen() {
|
||||
return pane !== null;
|
||||
}
|
||||
|
||||
function swipeMode() {
|
||||
return window.innerWidth < NARROW;
|
||||
}
|
||||
|
||||
function clampWidth(w) {
|
||||
const max = Math.max(MIN_W, window.innerWidth - MIN_W);
|
||||
return Math.round(Math.min(max, Math.max(MIN_W, w)));
|
||||
}
|
||||
|
||||
function applyWidth(w) {
|
||||
width = clampWidth(w);
|
||||
document.documentElement.style.setProperty('--sim-pane-w', `${width}px`);
|
||||
}
|
||||
|
||||
function setDrag(px) {
|
||||
document.documentElement.style.setProperty('--sim-drag', `${Math.round(px)}px`);
|
||||
}
|
||||
|
||||
function setPage(p) {
|
||||
page = p ? 1 : 0;
|
||||
document.documentElement.style.setProperty('--sim-page', String(page));
|
||||
setDrag(0);
|
||||
if (pager) {
|
||||
pager.querySelectorAll('button').forEach((b, i) => b.setAttribute('aria-pressed', String(i === page)));
|
||||
}
|
||||
if (pane) {
|
||||
// The page that is off screen is out of the tab order and hidden from screen readers
|
||||
pane.inert = swipeMode() && page === 0;
|
||||
const app = document.querySelector('.app-container');
|
||||
if (app) {
|
||||
app.inert = swipeMode() && page === 1;
|
||||
}
|
||||
}
|
||||
save({ page });
|
||||
}
|
||||
|
||||
// Side by side or two pages, from the window's width (a phone turned sideways can switch)
|
||||
function layout() {
|
||||
if (!pane) {
|
||||
return;
|
||||
}
|
||||
const swipe = swipeMode();
|
||||
document.body.classList.toggle('sim-split', !swipe);
|
||||
document.body.classList.toggle('sim-swipe', swipe);
|
||||
if (!swipe) {
|
||||
applyWidth(width || load().width || window.innerWidth * 0.45);
|
||||
}
|
||||
setPage(page);
|
||||
}
|
||||
|
||||
function popOut() {
|
||||
const win = window.open('/sim/', 'led-simulator', 'popup,width=1200,height=800');
|
||||
if (!win) {
|
||||
// Pop-ups blocked: keep the simulator here
|
||||
alert('The browser blocked the simulator window. Allow pop-ups for this site, or open /sim/ in a new tab.');
|
||||
return;
|
||||
}
|
||||
// Only one page runs the rig: the new window takes it over, so the pane closes
|
||||
close();
|
||||
}
|
||||
|
||||
/* ---- swiping between the two pages ---- */
|
||||
|
||||
// Touches that belong to something else: sliders and fields, sideways scrollers, open dialogs, and the rig's
|
||||
// canvas while its room is being edited (a drag there moves a bar)
|
||||
function ownsTouch(target, doc) {
|
||||
const el = target && target.nodeType === 1 ? target : target && target.parentElement;
|
||||
if (!el) {
|
||||
return false;
|
||||
}
|
||||
if (el.closest('input, textarea, select, [contenteditable="true"], [data-no-swipe], .sim-pane-divider')) {
|
||||
return true;
|
||||
}
|
||||
if (doc.querySelector('.modal.active, dialog[open]')) {
|
||||
return true;
|
||||
}
|
||||
if (doc.body.classList.contains('editing') && el.closest('canvas')) {
|
||||
return true;
|
||||
}
|
||||
const win = doc.defaultView;
|
||||
for (let n = el; n && n !== doc.body; n = n.parentElement) {
|
||||
const ox = win.getComputedStyle(n).overflowX;
|
||||
if ((ox === 'auto' || ox === 'scroll') && n.scrollWidth > n.clientWidth + 2) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function attachSwipe(doc) {
|
||||
let start = null;
|
||||
doc.addEventListener('touchstart', (ev) => {
|
||||
start = null;
|
||||
if (!document.body.classList.contains('sim-swipe') || ev.touches.length !== 1) {
|
||||
return;
|
||||
}
|
||||
if (ownsTouch(ev.target, doc)) {
|
||||
return;
|
||||
}
|
||||
const t = ev.touches[0];
|
||||
start = { x: t.clientX, y: t.clientY, at: performance.now(), lock: null, dx: 0 };
|
||||
}, { passive: true });
|
||||
|
||||
doc.addEventListener('touchmove', (ev) => {
|
||||
if (!start || ev.touches.length !== 1) {
|
||||
return;
|
||||
}
|
||||
const t = ev.touches[0];
|
||||
const dx = t.clientX - start.x;
|
||||
const dy = t.clientY - start.y;
|
||||
if (!start.lock) {
|
||||
if (Math.abs(dx) < LOCK_PX && Math.abs(dy) < LOCK_PX) {
|
||||
return;
|
||||
}
|
||||
start.lock = Math.abs(dx) > Math.abs(dy) * 1.5 ? 'x' : 'y';
|
||||
if (start.lock === 'x') {
|
||||
document.body.classList.add(DRAG_CLASS);
|
||||
}
|
||||
}
|
||||
if (start.lock !== 'x') {
|
||||
return; // a scroll: leave it to the page
|
||||
}
|
||||
ev.preventDefault();
|
||||
// The pages follow the finger; past the first or last page they resist
|
||||
const past = (page === 0 && dx > 0) || (page === 1 && dx < 0);
|
||||
start.dx = dx;
|
||||
setDrag(past ? dx / 4 : dx);
|
||||
}, { passive: false });
|
||||
|
||||
const end = () => {
|
||||
if (!start) {
|
||||
return;
|
||||
}
|
||||
const s = start;
|
||||
start = null;
|
||||
if (s.lock !== 'x') {
|
||||
return;
|
||||
}
|
||||
document.body.classList.remove(DRAG_CLASS);
|
||||
const fast = Math.abs(s.dx) / Math.max(1, performance.now() - s.at) > 0.5; // px per ms: a flick
|
||||
const far = Math.abs(s.dx) > window.innerWidth * 0.25;
|
||||
if ((far || fast) && s.dx < 0 && page === 0) {
|
||||
setPage(1);
|
||||
} else if ((far || fast) && s.dx > 0 && page === 1) {
|
||||
setPage(0);
|
||||
} else {
|
||||
setPage(page); // not far enough: back where it was
|
||||
}
|
||||
};
|
||||
doc.addEventListener('touchend', end);
|
||||
doc.addEventListener('touchcancel', end);
|
||||
}
|
||||
|
||||
/* ---- the pane ---- */
|
||||
|
||||
function build() {
|
||||
pane = document.createElement('div');
|
||||
pane.id = 'sim-pane';
|
||||
pane.className = 'sim-pane';
|
||||
pane.innerHTML =
|
||||
'<div class="sim-pane-divider" role="separator" aria-orientation="vertical" ' +
|
||||
'aria-label="Resize the simulator" title="Drag to resize"></div>' +
|
||||
'<div class="sim-pane-body">' +
|
||||
'<div class="sim-pane-bar">' +
|
||||
'<span class="sim-pane-title">Simulator</span>' +
|
||||
'<button type="button" class="btn btn-secondary btn-small" data-sim="popout" ' +
|
||||
'title="Open the simulator in its own window">Pop out ↗</button>' +
|
||||
'<button type="button" class="btn btn-secondary btn-small" data-sim="close" ' +
|
||||
'title="Close the simulator (its bars power off)" aria-label="Close the simulator">×</button>' +
|
||||
'</div>' +
|
||||
'<iframe class="sim-pane-frame" src="/sim/" title="Simulated rig"></iframe>' +
|
||||
'</div>';
|
||||
pane.querySelector('[data-sim="popout"]').addEventListener('click', popOut);
|
||||
pane.querySelector('[data-sim="close"]').addEventListener('click', close);
|
||||
|
||||
// Swipes that start in the rig (same origin, so its document can be listened to)
|
||||
const frame = pane.querySelector('iframe');
|
||||
frame.addEventListener('load', () => {
|
||||
try {
|
||||
attachSwipe(frame.contentDocument);
|
||||
} catch (_e) {
|
||||
// not reachable: swipe from the pane's bar or the pager instead
|
||||
}
|
||||
});
|
||||
|
||||
const divider = pane.querySelector('.sim-pane-divider');
|
||||
divider.addEventListener('pointerdown', (ev) => {
|
||||
ev.preventDefault();
|
||||
divider.setPointerCapture(ev.pointerId);
|
||||
document.body.classList.add('sim-split-dragging'); // the iframe would swallow the pointer
|
||||
const move = (e) => applyWidth(window.innerWidth - e.clientX);
|
||||
const up = () => {
|
||||
divider.removeEventListener('pointermove', move);
|
||||
divider.removeEventListener('pointerup', up);
|
||||
divider.removeEventListener('pointercancel', up);
|
||||
document.body.classList.remove('sim-split-dragging');
|
||||
save({ width });
|
||||
};
|
||||
divider.addEventListener('pointermove', move);
|
||||
divider.addEventListener('pointerup', up);
|
||||
divider.addEventListener('pointercancel', up);
|
||||
});
|
||||
divider.addEventListener('keydown', (ev) => {
|
||||
const step = ev.shiftKey ? 80 : 20;
|
||||
if (ev.key === 'ArrowLeft' || ev.key === 'ArrowRight') {
|
||||
ev.preventDefault();
|
||||
applyWidth(width + (ev.key === 'ArrowLeft' ? step : -step));
|
||||
save({ width });
|
||||
}
|
||||
});
|
||||
divider.tabIndex = 0;
|
||||
document.body.appendChild(pane);
|
||||
|
||||
pager = document.createElement('div');
|
||||
pager.className = 'sim-pager';
|
||||
pager.setAttribute('role', 'group');
|
||||
pager.setAttribute('aria-label', 'Show the controller or the simulator (or swipe)');
|
||||
pager.innerHTML =
|
||||
'<button type="button" aria-pressed="true">Controller</button>' +
|
||||
'<button type="button" aria-pressed="false">Simulator</button>';
|
||||
pager.querySelectorAll('button').forEach((b, i) => b.addEventListener('click', () => setPage(i)));
|
||||
document.body.appendChild(pager);
|
||||
}
|
||||
|
||||
function open() {
|
||||
if (!pane) {
|
||||
build();
|
||||
width = load().width || 0;
|
||||
page = swipeMode() ? 1 : 0; // on a phone, opening it shows it
|
||||
}
|
||||
save({ open: true });
|
||||
layout();
|
||||
window.dispatchEvent(new Event('resize')); // the UI lays out for its new width
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (pane) {
|
||||
pane.remove(); // the iframe goes with it: its bars power off
|
||||
pane = null;
|
||||
}
|
||||
if (pager) {
|
||||
pager.remove();
|
||||
pager = null;
|
||||
}
|
||||
const app = document.querySelector('.app-container');
|
||||
if (app) {
|
||||
app.inert = false;
|
||||
}
|
||||
document.body.classList.remove('sim-split', 'sim-swipe', DRAG_CLASS);
|
||||
document.documentElement.style.setProperty('--sim-page', '0');
|
||||
setDrag(0);
|
||||
save({ open: false });
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
}
|
||||
|
||||
// The Menu item: open it; once open, side by side it closes it, on a phone it shows its page
|
||||
function toggle() {
|
||||
if (!isOpen()) {
|
||||
open();
|
||||
} else if (swipeMode()) {
|
||||
setPage(page === 1 ? 0 : 1);
|
||||
} else {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
function addMenuEntries() {
|
||||
// A header button for the Menu item to forward to, as the other entries do (help.js)
|
||||
const headerActions = document.querySelector('.header-actions');
|
||||
const settingsBtn = document.getElementById('settings-btn');
|
||||
const btn = document.createElement('button');
|
||||
btn.className = 'btn btn-secondary edit-mode-only';
|
||||
btn.id = 'sim-btn';
|
||||
btn.textContent = 'Simulator';
|
||||
btn.addEventListener('click', toggle);
|
||||
if (headerActions) {
|
||||
headerActions.insertBefore(btn, settingsBtn && settingsBtn.parentNode === headerActions ? settingsBtn : null);
|
||||
}
|
||||
const menu = document.getElementById('main-menu-dropdown');
|
||||
if (menu) {
|
||||
const item = document.createElement('button');
|
||||
item.type = 'button';
|
||||
item.className = 'edit-mode-only';
|
||||
item.dataset.target = 'sim-btn';
|
||||
item.textContent = 'Simulator';
|
||||
const settingsItem = menu.querySelector('[data-target="settings-btn"]');
|
||||
menu.insertBefore(item, settingsItem);
|
||||
}
|
||||
}
|
||||
|
||||
async function init() {
|
||||
let ok = false;
|
||||
try {
|
||||
const r = await fetch('/sim/api/config', { cache: 'no-store' });
|
||||
ok = r.ok;
|
||||
} catch (_e) {
|
||||
ok = false;
|
||||
}
|
||||
if (!ok) {
|
||||
return; // the board: no simulator
|
||||
}
|
||||
addMenuEntries();
|
||||
attachSwipe(document); // swipes that start on the controller's page
|
||||
const saved = load();
|
||||
if (saved.open) {
|
||||
build();
|
||||
width = saved.width || 0;
|
||||
page = saved.page ? 1 : 0;
|
||||
layout();
|
||||
}
|
||||
window.addEventListener('resize', layout);
|
||||
}
|
||||
|
||||
window.simSplit = { open, close, popOut, setPage };
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
+1003
-194
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user