Files
led-controller/web/static/help.js
T
jimmyandClaude Opus 5.5 581b751904 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>
2026-11-16 19:32:46 +13:00

511 lines
19 KiB
JavaScript

document.addEventListener('DOMContentLoaded', () => {
// Help modal
const helpBtn = document.getElementById('help-btn');
const helpModal = document.getElementById('help-modal');
const helpCloseBtn = document.getElementById('help-close-btn');
const mainMenuBtn = document.getElementById('main-menu-btn');
const mainMenuDropdown = document.getElementById('main-menu-dropdown');
if (helpBtn && helpModal) {
const openHelp = () => {
helpModal.classList.add('active');
switchHelpTab('overview');
};
helpBtn.addEventListener('click', openHelp);
}
if (helpCloseBtn && helpModal) {
helpCloseBtn.addEventListener('click', () => {
helpModal.classList.remove('active');
});
}
const helpTabButtons = document.querySelectorAll('[data-help-tab]');
const helpTabPanels = document.querySelectorAll('[data-help-panel]');
function switchHelpTab(tabId) {
if (!tabId) tabId = 'overview';
for (const btn of helpTabButtons) {
const on = btn.getAttribute('data-help-tab') === tabId;
btn.classList.toggle('active', on);
btn.setAttribute('aria-selected', on ? 'true' : 'false');
}
for (const panel of helpTabPanels) {
const on = panel.getAttribute('data-help-panel') === tabId;
panel.classList.toggle('active', on);
panel.hidden = !on;
}
}
for (const btn of helpTabButtons) {
btn.addEventListener('click', () => {
switchHelpTab(btn.getAttribute('data-help-tab'));
});
}
// Main menu: forward clicks to existing header buttons
if (mainMenuBtn && mainMenuDropdown) {
mainMenuBtn.addEventListener('click', () => {
mainMenuDropdown.classList.toggle('open');
const zonesMenuDropdown = document.getElementById('zones-menu-dropdown');
const zonesMenuBtn = document.getElementById('zones-menu-btn');
if (zonesMenuDropdown) zonesMenuDropdown.classList.remove('open');
if (zonesMenuBtn) zonesMenuBtn.setAttribute('aria-expanded', 'false');
});
mainMenuDropdown.addEventListener('click', (event) => {
const target = event.target;
if (target && target.matches('button[data-target]')) {
const id = target.getAttribute('data-target');
const realBtn = document.getElementById(id);
if (realBtn) {
realBtn.click();
}
mainMenuDropdown.classList.remove('open');
}
});
}
// Settings modal wiring (reusing existing settings endpoints).
const settingsButton = document.getElementById('settings-btn');
const settingsModal = document.getElementById('settings-modal');
const settingsCloseButton = document.getElementById('settings-close-btn');
const showSettingsMessage = (text, type = 'success') => {
const messageEl = document.getElementById('settings-message');
if (!messageEl) return;
messageEl.textContent = text;
messageEl.className = `message ${type} show`;
setTimeout(() => {
messageEl.classList.remove('show');
}, 5000);
};
const rebootButton = document.getElementById('reboot-btn');
if (rebootButton) {
rebootButton.addEventListener('click', async () => {
if (!confirm('Reboot the controller now? The page will be unavailable for a few seconds.')) return;
rebootButton.disabled = true;
try {
await fetch('/reboot', { method: 'POST' });
rebootButton.textContent = 'Rebooting…';
setTimeout(() => location.reload(), 8000);
} catch (error) {
rebootButton.disabled = false;
console.error('Reboot failed:', error);
}
});
}
async function loadNetworkStatus() {
const box = document.getElementById('network-status');
if (!box) return;
const row = (label, value) => {
const r = document.createElement('div');
const b = document.createElement('strong');
b.textContent = label + ': ';
r.append(b, value);
return r;
};
try {
const st = await fetch('/status', { cache: 'no-store' }).then((r) => r.json());
box.textContent = '';
const eth = st.eth || { ip: st.ip };
const up = eth.ip && eth.ip !== '0.0.0.0';
box.append(row('Ethernet', up ? eth.ip + (eth.mask ? ' / ' + eth.mask : '') + (eth.gw && eth.gw !== '0.0.0.0' ? ', gateway ' + eth.gw : '') : 'no address'));
if (st.ap) {
box.append(row('Access point', st.ap_ip || '192.168.5.1'));
const clients = Array.isArray(st.ap_clients) ? st.ap_clients : [];
box.append(row('Wi-Fi clients', clients.length ? clients.map((c) => c.ip + ' (' + c.mac + ')').join(', ') : 'none'));
} else {
box.append(row('Access point', 'off'));
}
if (st.mac) box.append(row('MAC', st.mac));
} catch (error) {
box.textContent = 'Could not read network status.';
}
}
async function loadDeviceSettings() {
try {
const response = await fetch('/settings');
const data = await response.json();
const nameInput = document.getElementById('device-name-input');
if (nameInput && data && typeof data === 'object') {
nameInput.value = data.device_name || 'led-controller';
}
const chInput = document.getElementById('wifi-channel-input');
if (chInput && data && typeof data === 'object') {
const ch = data.wifi_channel;
chInput.value =
ch !== undefined && ch !== null && ch !== '' ? String(ch) : '6';
}
const hostInput = document.getElementById('hostname-input');
if (hostInput && staticIpsList && data && typeof data === 'object') {
hostInput.value = data.hostname || '';
setApToggle(data.ap_enabled !== false);
const apPw = document.getElementById('ap-password-input');
if (apPw) apPw.value = data.ap_password || '';
const bridge = document.getElementById('bridge-input');
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);
}
} catch (error) {
console.error('Error loading device settings:', error);
}
}
const apToggle = document.getElementById('ap-enabled-toggle');
function setApToggle(on) {
if (apToggle) {
apToggle.setAttribute('aria-pressed', on ? 'true' : 'false');
apToggle.classList.toggle('is-on', on);
}
}
if (apToggle) {
apToggle.addEventListener('click', () => {
setApToggle(apToggle.getAttribute('aria-pressed') !== 'true');
});
}
const staticIpsList = document.getElementById('static-ips-list');
const STATIC_IP_FIELDS = [
['ip', 'IP address', '192.168.1.50'],
['netmask', 'Netmask', '255.255.255.0'],
['gw', 'Gateway', '192.168.1.1'],
['dns', 'DNS (optional)', 'gateway'],
];
function addStaticIpRow(entry = {}) {
if (!staticIpsList) return;
const row = document.createElement('div');
row.className = 'static-ip-row';
row.style.cssText = 'display:flex;flex-wrap:wrap;gap:0.5rem;margin:0.5rem 0;align-items:center;';
STATIC_IP_FIELDS.forEach(([key, label, placeholder]) => {
const input = document.createElement('input');
input.type = 'text';
input.dataset.key = key;
input.placeholder = `${label} (${placeholder})`;
input.title = label;
input.value = entry[key] || '';
input.style.cssText = 'flex:1 1 9rem;min-width:0;';
row.appendChild(input);
});
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'btn btn-secondary';
remove.textContent = 'Remove';
remove.addEventListener('click', () => row.remove());
row.appendChild(remove);
staticIpsList.appendChild(row);
}
const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
const validIp = (v) => {
const m = IPV4.exec(v);
return !!m && m.slice(1).every((o) => Number(o) <= 255);
};
function readStaticIps() {
const out = [];
for (const row of staticIpsList.querySelectorAll('.static-ip-row')) {
const entry = {};
row.querySelectorAll('input').forEach((i) => {
const v = i.value.trim();
if (v) entry[i.dataset.key] = v;
});
if (!Object.keys(entry).length) continue;
if (!entry.ip) throw new Error('Every static IP needs an IP address');
for (const [k, v] of Object.entries(entry)) {
if (!validIp(v)) throw new Error(`"${v}" is not a valid ${k} address`);
}
out.push(entry);
}
return out;
}
const addIpButton = document.getElementById('static-ip-add-btn');
if (addIpButton) addIpButton.addEventListener('click', () => addStaticIpRow());
const settingsTabButtons = document.querySelectorAll('#settings-modal .settings-tab-btn');
const settingsTabPanels = document.querySelectorAll('#settings-modal .settings-tab-panel');
const ledToolIframe = document.getElementById('led-tool-iframe');
function switchSettingsTab(tabId) {
for (const btn of settingsTabButtons) {
const on = btn.getAttribute('data-settings-tab') === tabId;
btn.classList.toggle('active', on);
btn.setAttribute('aria-selected', on ? 'true' : 'false');
}
for (const panel of settingsTabPanels) {
const on = panel.getAttribute('data-settings-panel') === tabId;
panel.classList.toggle('active', on);
panel.hidden = !on;
}
if (tabId === 'network') loadNetworkStatus();
settingsModal.classList.toggle('settings-modal--led-tool', tabId === 'led-tool');
if (ledToolIframe) {
// Loaded on demand, so the Controller tab costs no requests
ledToolIframe.src = tabId === 'led-tool' ? '/settings/editor' : 'about:blank';
}
}
for (const btn of settingsTabButtons) {
btn.addEventListener('click', () => switchSettingsTab(btn.getAttribute('data-settings-tab')));
}
if (settingsButton && settingsModal) {
settingsButton.addEventListener('click', () => {
settingsModal.classList.add('active');
switchSettingsTab('controller');
loadDeviceSettings();
loadBridgeSettings();
});
}
if (settingsCloseButton && settingsModal) {
settingsCloseButton.addEventListener('click', () => {
settingsModal.classList.remove('active');
switchSettingsTab('controller');
});
}
const deviceForm = document.getElementById('device-form');
if (deviceForm) {
deviceForm.addEventListener('submit', async (e) => {
e.preventDefault();
const nameInput = document.getElementById('device-name-input');
const deviceName = nameInput ? nameInput.value.trim() : '';
if (!deviceName) {
showSettingsMessage('Device name is required', 'error');
return;
}
const chRaw = document.getElementById('wifi-channel-input')
? document.getElementById('wifi-channel-input').value
: '6';
const wifiChannel = parseInt(chRaw, 10);
if (Number.isNaN(wifiChannel) || wifiChannel < 1 || wifiChannel > 11) {
showSettingsMessage('WiFi channel must be between 1 and 11', 'error');
return;
}
try {
const response = await fetch('/settings/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
device_name: deviceName,
wifi_channel: wifiChannel,
}),
});
const result = await response.json();
if (response.ok) {
showSettingsMessage(
'Device settings saved. They will apply on next restart where relevant.',
'success',
);
} else {
showSettingsMessage(`Error: ${result.error || 'Failed to save device name'}`, 'error');
}
} catch (error) {
showSettingsMessage(`Error: ${error.message}`, 'error');
}
});
}
// 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) => {
e.preventDefault();
const hostname = document.getElementById('hostname-input').value.trim();
if (hostname && !/^[A-Za-z0-9-]+$/.test(hostname)) {
showSettingsMessage('Hostname may only contain letters, digits and hyphens', 'error');
return;
}
const apPassword = (document.getElementById('ap-password-input') || { value: '' }).value;
if (apPassword && (apPassword.length < 8 || apPassword.length > 63)) {
showSettingsMessage('Access point password must be 8 to 63 characters, or empty for open', 'error');
return;
}
let staticIps;
try {
staticIps = readStaticIps();
} catch (error) {
showSettingsMessage(error.message, 'error');
return;
}
try {
const response = await fetch('/settings/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
hostname,
static_ips: staticIps,
ap_password: apPassword,
bridges: (document.getElementById('bridge-input') || { value: '' }).value.split(',').map((v) => v.trim()).filter(Boolean),
ap_enabled: !apToggle || apToggle.getAttribute('aria-pressed') === 'true',
}),
});
const result = await response.json();
if (response.ok) {
showSettingsMessage('Network settings saved. Restart the controller to apply them.', 'success');
} else {
showSettingsMessage(`Error: ${result.error || 'Failed to save network settings'}`, 'error');
}
} catch (error) {
showSettingsMessage(`Error: ${error.message}`, 'error');
}
});
}
});