Files
led-controller/web/static/help.js
T
jimmyandClaude Haiku 5.5 edf35e9c71 Channel 11 defaults, ESP-NOW driver config and rig/desktop updates
Moves the controller, bridge and led-driver default ESP-NOW channel to 11 and
updates the led-driver and led-tool submodule pointers. Includes the rest of the
working tree: web UI, desktop and sim-controller changes, API and bridge code,
graphify output, and the .gitea and fixture-driver folders.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-21 01:19:02 +13:00

688 lines
28 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 (!await uiConfirm('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 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 || '';
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');
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();
document.dispatchEvent(new CustomEvent('settings-tab', { detail: tabId }));
}
for (const btn of settingsTabButtons) {
btn.addEventListener('click', () => switchSettingsTab(btn.getAttribute('data-settings-tab')));
}
// Other scripts open Settings on one of its tabs (the Outputs, Audio and Users tabs)
window.openSettingsTab = (tabId) => {
settingsModal.classList.add('active');
switchSettingsTab(tabId);
loadDeviceSettings();
loadBridgeSettings();
};
if (settingsButton && settingsModal) {
settingsButton.addEventListener('click', () => {
settingsModal.classList.add('active');
switchSettingsTab('network');
loadDeviceSettings();
loadBridgeSettings();
});
}
if (settingsCloseButton && settingsModal) {
settingsCloseButton.addEventListener('click', () => {
settingsModal.classList.remove('active');
switchSettingsTab('network');
});
}
// Bridges: USB boards and network boards (GET/PUT /settings/bridge)
const bridgeSection = document.getElementById('bridge-section');
const bridgeList = document.getElementById('bridge-list');
const bridgeAddBtn = document.getElementById('bridge-add-btn');
const bridgePorts = document.getElementById('bridge-ports');
const bridgeRefresh = document.getElementById('bridge-refresh-btn');
let bridgeAddrs = [];
// A board is named by its MAC (it stays the same when the port or address changes); the address shows while the
// board has not answered yet
function bridgeMac(b) {
const mac = b.status && b.status.mac;
return mac && mac !== '00:00:00:00:00:00' ? mac : '';
}
function bridgeName(b) {
if (b.kind === 'dmx') return (b.status && b.status.name) || b.addr;
return bridgeMac(b) || b.addr;
}
const dmxId = (b) => b.addr.slice(4); // "dmx:<id>"
// 'up' (linked), 'down' (not linked yet) or 'local' (the rig page of this controller)
function bridgeState(b) {
if (b.kind === 'browser') return 'local';
if (b.kind === 'stopped') return 'down';
return b.status && b.status.linked ? 'up' : 'down';
}
function describeBridge(b) {
const st = b.status || {};
if (b.kind === 'browser') return 'Rig page of this controller · sent ' + (st.tx || 0) + ' · received ' + (st.rx || 0);
if (b.kind === 'stopped') return 'DMX bridge, not running';
if (b.kind === 'dmx') {
const parts = ['DMX', (st.universes || 0) + (st.universes === 1 ? ' universe' : ' universes'),
(st.running || 0) + '/' + (st.fixtures || 0) + ' fixtures', (st.hz || 40) + ' Hz', 'sent ' + (st.packets || 0)];
if (st.last_error) parts.push('last error: ' + st.last_error);
return parts.join(' · ');
}
if (b.kind === 'udp' || (b.kind !== 'serial' && !b.addr.startsWith('usb:'))) {
if (!st.linked) return 'Not connected (no answer from ' + b.addr + ')';
return ['Connected', 'channel ' + st.channel, 'microphone ' + (st.mic ? 'yes' : 'no'),
'sent ' + (st.tx || 0), 'received ' + (st.rx || 0)].join(' · ');
}
if (!st.linked) return b.addr.startsWith('usb:') ? 'Not plugged in (looking for it on every USB port)' : 'Not connected (waiting for the board on ' + st.port + ')';
return ['Connected', 'channel ' + st.channel, 'microphone ' + (st.mic ? 'yes' : 'no'),
'sent ' + st.sent, 'received ' + st.rx].join(' · ');
}
function renderBridges(data) {
bridgeList.textContent = '';
for (const b of data.bridges || []) {
// The same row as the groups list: title and status on the left, small buttons on the right
const row = document.createElement('div');
row.className = 'group-list-row';
const info = document.createElement('div');
info.className = 'group-list-row-info';
const title = document.createElement('div');
title.className = 'group-list-row-title';
const dot = document.createElement('span');
const state = bridgeState(b);
dot.className = 'bridge-status-dot bridge-status-' + state;
dot.setAttribute('role', 'img');
dot.setAttribute('aria-label', state === 'up' ? 'Connected' : state === 'local' ? 'Local' : 'Not connected');
title.append(dot, document.createTextNode(b.name || bridgeName(b)));
const meta = document.createElement('div');
meta.className = 'group-list-row-meta muted-text';
meta.textContent = (b.name ? bridgeName(b) + ' · ' : '') + (b.kind === 'serial' && b.status && b.status.port && b.status.linked ? 'USB ' + b.status.port + ' · ' : '') + describeBridge(b);
info.append(title, meta);
const actions = document.createElement('div');
actions.className = 'group-list-row-actions';
const editBtn = document.createElement('button');
editBtn.type = 'button';
editBtn.className = 'btn btn-secondary btn-small';
editBtn.textContent = 'Edit';
const dmx = b.kind === 'dmx' || b.kind === 'stopped';
editBtn.addEventListener('click', () => openBridgeEditor(b));
if (b.kind === 'stopped') {
const startBtn = document.createElement('button');
startBtn.type = 'button';
startBtn.className = 'btn btn-primary btn-small';
startBtn.textContent = 'Start';
startBtn.addEventListener('click', async () => {
try {
await window.DmxBridges.start(dmxId(b));
showSettingsMessage('DMX bridge started.', 'success');
} catch (error) {
showSettingsMessage(`Error: ${error.message}`, 'error');
}
loadBridgeSettings();
});
actions.append(startBtn);
}
actions.append(editBtn);
if (dmx) {
const delBtn = document.createElement('button');
delBtn.type = 'button';
delBtn.className = 'btn btn-danger btn-small';
delBtn.textContent = 'Delete';
delBtn.addEventListener('click', async () => {
if (!await uiConfirm(`Delete DMX bridge "${bridgeName(b)}" and its fixtures?`)) return;
try {
await window.DmxBridges.remove(dmxId(b));
showSettingsMessage('DMX bridge deleted.', 'success');
} catch (error) {
showSettingsMessage(`Error: ${error.message}`, 'error');
}
loadBridgeSettings();
});
actions.append(delBtn);
} else if (b.kind !== 'browser') { // the rig page's own bridge is not removable
const delBtn = document.createElement('button');
delBtn.type = 'button';
delBtn.className = 'btn btn-danger btn-small';
delBtn.textContent = 'Delete';
delBtn.addEventListener('click', async () => {
if (!await uiConfirm(`Delete bridge "${bridgeName(b)}"?`)) return;
putBridges(bridgeAddrs.filter((a) => a !== b.addr), 'Bridge removed.');
});
actions.append(delBtn);
}
row.append(info, 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;
const bridgeTab = document.getElementById('settings-tab-bridges');
if (bridgeTab) bridgeTab.hidden = !data.supported; // nothing to show where bridges are not supported
if (!data.supported) return;
bridgeAddrs = (data.bridges || []).map((b) => b.addr);
// DMX bridge records that are not running are listed too, with a Start button
try {
const recs = await fetch('/dmx-bridges', { cache: 'no-store' }).then((r) => (r.ok ? r.json() : {}));
for (const [id, rec] of Object.entries(recs)) {
if (!bridgeAddrs.includes('dmx:' + id)) {
data.bridges = (data.bridges || []).concat([{ addr: 'dmx:' + id, kind: 'stopped', name: '', status: { name: rec.name } }]);
}
}
} catch (error) {
// no DMX bridges to add
}
renderBridges(data);
filterBridges();
} catch (error) {
bridgeList.textContent = 'Could not read the bridges.';
}
}
// Returns the error text, or '' when the list was set
async function putBridges(addrs, okText) {
let err = '';
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 {
err = result.error || 'Failed to update the bridges';
showSettingsMessage(`Error: ${err}`, 'error');
}
} catch (error) {
err = error.message;
showSettingsMessage(`Error: ${err}`, 'error');
}
loadBridgeSettings();
setTimeout(loadBridgeSettings, 1500); // a board answers its link a moment later
return err;
}
// Returns the error text, or '' when the name was saved ('' clears it)
async function setBridgeName(addr, name) {
let err = '';
try {
const response = await fetch('/settings/bridge', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ addr, name }),
});
const result = await response.json();
if (!response.ok) err = result.error || 'Failed to save the name';
} catch (error) {
err = error.message;
}
loadBridgeSettings();
return err;
}
async function setBridgeChannel(addr, raw) {
const channel = parseInt(raw, 10);
let err = '';
if (Number.isNaN(channel) || channel < 1 || channel > 13) {
return 'Radio channel must be between 1 and 13';
}
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 {
err = result.error || 'Failed to set the channel';
showSettingsMessage(`Error: ${err}`, 'error');
}
} catch (error) {
err = error.message;
showSettingsMessage(`Error: ${err}`, 'error');
}
loadBridgeSettings();
return err;
}
if (bridgeRefresh) bridgeRefresh.addEventListener('click', loadBridgeSettings);
if (bridgeAddBtn) bridgeAddBtn.addEventListener('click', () => openBridgeEditor(null));
const bridgeSearch = document.getElementById('bridge-search');
function filterBridges() {
const q = bridgeSearch ? bridgeSearch.value.trim().toLowerCase() : '';
bridgeList.querySelectorAll('.group-list-row').forEach((row) => {
row.hidden = !!q && !row.textContent.toLowerCase().includes(q);
});
}
if (bridgeSearch) bridgeSearch.addEventListener('input', filterBridges);
// The bridge dialog, for every kind of bridge: a type picker (USB board, network board, DMX) shows the fields of
// that type. Adding starts with the type; an existing bridge keeps its type.
const bridgeEditModal = document.getElementById('edit-bridge-modal');
const bridgeEditForm = document.getElementById('edit-bridge-form');
const bridgeTypeSel = document.getElementById('edit-bridge-type');
let bridgeEditing = null; // the bridge being edited, or null when adding
let dmxLoaded = false; // the DMX section holds the bridge being edited (or a new one)
const isBoardAddr = (addr) => /^(serial:)?\/dev\//.test(addr) || addr.startsWith('usb:');
const TYPE_HELP = {
usb: 'A bridge board on USB: its serial port (/dev/ttyACM1). Once it answers it is known by its MAC, on whichever port it is plugged into.',
network: 'A bridge board or led-simulator on the network: host:port (UDP, default port 8766).',
dmx: 'Universes sent to Art-Net, sACN, USB-DMX or the rig simulator 40 times a second. Each fixture is a led-driver of its own.',
browser: 'The rig page of this controller. It has nothing to set and cannot be removed.',
};
function bridgeType(b) {
if (!b) return 'usb';
if (b.kind === 'dmx' || b.kind === 'stopped') return 'dmx';
if (b.kind === 'browser') return 'browser';
if (b.kind === 'serial' || isBoardAddr(b.addr)) return 'usb';
return 'network';
}
function bridgeEditError(text) {
const el = document.getElementById('edit-bridge-error');
el.textContent = text || '';
el.hidden = !text;
}
async function syncBridgeEditor() {
const type = bridgeTypeSel.value;
const usbKnown = !!bridgeEditing && bridgeEditing.addr.startsWith('usb:');
document.getElementById('edit-bridge-type-help').textContent = TYPE_HELP[type] || '';
document.getElementById('edit-bridge-addr-field').hidden = type === 'dmx' || type === 'browser';
document.getElementById('edit-bridge-channel-field').hidden = type !== 'usb';
document.getElementById('edit-bridge-dmx-field').hidden = type !== 'dmx';
document.getElementById('edit-bridge-name').maxLength = type === 'dmx' ? 63 : 40;
document.getElementById('edit-bridge-name').placeholder = type === 'dmx' ? 'e.g. Stage' : 'e.g. Stage left';
const addr = document.getElementById('edit-bridge-addr');
addr.placeholder = type === 'network' ? '192.168.1.50:8766' : '/dev/ttyACM1';
addr.disabled = type === 'browser' || usbKnown; // a USB board is found by its MAC wherever it is plugged in
bridgeEditModal.querySelector('.modal-content').classList.toggle('bridge-modal-wide', type === 'dmx');
if (type === 'dmx' && !dmxLoaded && window.DmxBridges) {
dmxLoaded = true;
try {
const name = await window.DmxBridges.load(bridgeEditing ? bridgeEditing.addr.slice(4) : null);
if (bridgeEditing) document.getElementById('edit-bridge-name').value = name;
} catch (error) {
dmxLoaded = false;
bridgeEditError(`Could not load the DMX bridge: ${error.message}`);
}
}
}
function openBridgeEditor(b) {
bridgeEditing = b || null;
dmxLoaded = false;
const type = bridgeType(b);
const browser = type === 'browser';
const usbKnown = !!b && b.addr.startsWith('usb:');
document.getElementById('edit-bridge-title').textContent = b ? 'Edit bridge' : 'Add bridge';
bridgeTypeSel.value = type;
bridgeTypeSel.disabled = !!b; // a bridge keeps its type; delete it and add another to change it
bridgeTypeSel.querySelector('option[value="browser"]').hidden = !browser;
document.getElementById('edit-bridge-name').value = b ? (type === 'dmx' ? (b.status && b.status.name) || '' : b.name || '') : '';
document.getElementById('edit-bridge-addr').value = b && type !== 'dmx' ? (bridgeMac(b) || b.addr) : '';
const ch = document.getElementById('edit-bridge-channel');
ch.value = b && b.status && b.status.channel ? String(b.status.channel) : '';
document.getElementById('edit-bridge-status').textContent = b
? (usbKnown && b.status && b.status.port ? 'Now on ' + b.status.port + '. ' : '') + describeBridge(b)
: '';
document.getElementById('edit-bridge-save-btn').hidden = browser;
document.getElementById('edit-bridge-dmx-universes').textContent = '';
bridgeEditError('');
syncBridgeEditor();
bridgeEditModal.classList.add('active');
}
// Save a USB or network board: its place in the list, its name and its radio channel
async function saveBoard() {
const usbKnown = !!bridgeEditing && bridgeEditing.addr.startsWith('usb:');
const addr = usbKnown ? bridgeEditing.addr : document.getElementById('edit-bridge-addr').value.trim();
const type = bridgeTypeSel.value;
if (!addr) return type === 'network' ? 'Enter the board\'s host:port' : 'Enter the board\'s port (/dev/...)';
if (type === 'network' && (isBoardAddr(addr) || !/^[^\s:]+:\d+$/.test(addr))) return 'A network bridge is host:port, e.g. 192.168.1.50:8766';
if (type === 'usb' && !isBoardAddr(addr)) return 'A USB bridge is its port, e.g. /dev/ttyACM1';
if (addr !== (bridgeEditing && bridgeEditing.addr) && bridgeAddrs.includes(addr)) return 'That bridge is already in the list';
const raw = document.getElementById('edit-bridge-channel').value.trim();
const list = bridgeEditing ? bridgeAddrs.map((a) => (a === bridgeEditing.addr ? addr : a)) : [...bridgeAddrs, addr];
const channelChanged = type === 'usb' && raw !== '' &&
raw !== String(bridgeEditing && bridgeEditing.status && bridgeEditing.status.channel || '');
const name = document.getElementById('edit-bridge-name').value.trim();
let err = '';
if (!bridgeEditing || addr !== bridgeEditing.addr) {
err = await putBridges(list, bridgeEditing ? 'Bridge updated.' : 'Bridge added.');
}
if (!err && name !== ((bridgeEditing && bridgeEditing.name) || '')) err = await setBridgeName(addr, name);
if (!err && channelChanged) err = await setBridgeChannel(addr, raw);
return err;
}
async function saveDmx() {
try {
const r = await window.DmxBridges.save(document.getElementById('edit-bridge-name').value);
showSettingsMessage(r.created ? 'DMX bridge added.' : 'DMX bridge saved.', 'success');
} catch (error) {
return error.message;
}
loadBridgeSettings();
setTimeout(loadBridgeSettings, 1500); // the fixtures come up a moment later
return '';
}
if (bridgeEditModal && bridgeEditForm) {
const close = () => bridgeEditModal.classList.remove('active');
document.getElementById('edit-bridge-close-btn').addEventListener('click', close);
bridgeTypeSel.addEventListener('change', () => {
bridgeEditError('');
syncBridgeEditor();
});
bridgeEditForm.addEventListener('submit', async (e) => {
e.preventDefault();
bridgeEditError('');
const err = bridgeTypeSel.value === 'dmx' ? await saveDmx() : await saveBoard();
if (err) bridgeEditError(err);
else close();
});
}
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,
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');
}
});
}
});