Files
led-controller/web/static/sequences.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

1095 lines
41 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Sequences: lanes (parallel preset chains); advance by audio beats or global simulated BPM.
// Debug: in the browser console run setSequenceDebug(true) — session only, not persisted.
/** @type {'beat'|'downbeat'} */
let sequenceSwitchWaitFor = 'beat';
let sequenceDebugEnabled = false;
let sequenceSwitchSaveInFlight = false;
/** When true (simulated BPM / audio off), downbeat is disabled and switch is beat-only. */
let sequenceSwitchSimulatedMode = false;
async function loadSequenceSwitchWaitForFromServer() {
try {
const res = await fetch('/settings', {
cache: 'no-store',
headers: { Accept: 'application/json' },
});
if (!res.ok) return;
const data = await res.json();
const raw = data && data.sequence_switch_wait;
if (raw === 'downbeat' || raw === 'beat') {
sequenceSwitchWaitFor = raw;
} else if (raw === 'phrase') {
sequenceSwitchWaitFor = 'beat';
}
} catch {
/* keep default */
}
}
async function persistSequenceSwitchWaitFor() {
sequenceSwitchSaveInFlight = true;
try {
const res = await fetch('/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ sequence_switch_wait: sequenceSwitchWaitFor }),
});
if (!res.ok) {
console.warn('[sequence] could not save switch wait to server', res.status);
}
} catch (e) {
console.warn('[sequence] could not save switch wait to server', e);
} finally {
sequenceSwitchSaveInFlight = false;
}
}
function getSequenceSwitchWaitFor() {
return sequenceSwitchWaitFor === 'downbeat' ? 'downbeat' : 'beat';
}
async function setSequenceSwitchWaitFor(waitFor) {
if (sequenceSwitchSimulatedMode) {
sequenceSwitchWaitFor = 'beat';
updateSequenceSwitchToggleUI();
return;
}
sequenceSwitchWaitFor = waitFor === 'downbeat' ? 'downbeat' : 'beat';
updateSequenceSwitchToggleUI();
await persistSequenceSwitchWaitFor();
}
function updateSequenceSwitchToggleUI() {
const mode = sequenceSwitchSimulatedMode ? 'beat' : getSequenceSwitchWaitFor();
const ariaLabels = {
beat: 'Switch sequence on beat',
downbeat: 'Switch sequence on downbeat',
};
document.documentElement.classList.toggle(
'simulated-bpm-mode',
sequenceSwitchSimulatedMode,
);
document.querySelectorAll('.seq-switch-toggle-wrap').forEach((wrap) => {
wrap.hidden = sequenceSwitchSimulatedMode;
wrap.setAttribute('aria-hidden', sequenceSwitchSimulatedMode ? 'true' : 'false');
wrap.classList.toggle('nav-slide-toggle-wrap--downbeat', mode === 'downbeat');
});
if (sequenceSwitchSimulatedMode) {
return;
}
document.querySelectorAll('.seq-switch-toggle').forEach((btn) => {
btn.disabled = false;
btn.removeAttribute('aria-disabled');
btn.setAttribute('aria-pressed', mode === 'beat' ? 'false' : 'true');
btn.setAttribute('aria-label', ariaLabels[mode] || ariaLabels.beat);
btn.classList.toggle('seq-switch-toggle--downbeat', mode === 'downbeat');
btn.title =
mode === 'downbeat'
? 'When starting a sequence: wait for downbeat'
: 'When starting a sequence: wait for beat';
});
}
/** @param {boolean} simulated */
function setSequenceSwitchSimulatedMode(simulated) {
const next = !!simulated;
if (next === sequenceSwitchSimulatedMode) {
if (next) updateSequenceSwitchToggleUI();
return;
}
sequenceSwitchSimulatedMode = next;
if (next) {
sequenceSwitchWaitFor = 'beat';
updateSequenceSwitchToggleUI();
void persistSequenceSwitchWaitFor();
return;
}
void loadSequenceSwitchWaitForFromServer().then(() => updateSequenceSwitchToggleUI());
}
async function syncSequenceSwitchSimulatedModeFromStatus() {
try {
const res = await fetch('/api/audio/status', { cache: 'no-store' });
const data = await res.json();
const simulated = !!(data && data.status && data.status.bpm_simulated);
setSequenceSwitchSimulatedMode(simulated);
} catch {
setSequenceSwitchSimulatedMode(true);
}
}
async function initSequenceSwitchToggle() {
await syncSequenceSwitchSimulatedModeFromStatus();
await loadSequenceSwitchWaitForFromServer();
updateSequenceSwitchToggleUI();
document.querySelectorAll('.seq-switch-toggle').forEach((btn) => {
btn.addEventListener('click', () => {
if (sequenceSwitchSimulatedMode) return;
void setSequenceSwitchWaitFor(getSequenceSwitchWaitFor() === 'beat' ? 'downbeat' : 'beat');
});
});
}
/** Sync toggle when settings changed elsewhere (e.g. another tab via audio status poll). */
function applySequenceSwitchWaitFromServer(raw) {
if (sequenceSwitchSaveInFlight || sequenceSwitchSimulatedMode) return;
let mode = 'beat';
if (raw === 'downbeat') mode = 'downbeat';
else if (raw !== 'beat' && raw !== 'phrase') return;
if (mode === getSequenceSwitchWaitFor()) return;
sequenceSwitchWaitFor = mode;
updateSequenceSwitchToggleUI();
}
function seqDebugEnabled() {
return sequenceDebugEnabled;
}
/** @param {boolean} [clearSequenceTileSelection] When false, leaves the active highlight on sequence tiles (used when restarting playback so the click handler’s selection is not cleared). */
async function stopZoneSequencePlayback(clearSequenceTileSelection = true) {
// Clear selection **before** awaiting fetch so overlapping stop() calls cannot finish out of
// order and strip .active from tiles after a later render or click (intermittent dead UI).
if (clearSequenceTileSelection) {
document.querySelectorAll('.sequence-tile-main.active').forEach((btn) => btn.classList.remove('active'));
}
try {
const res = await fetch('/sequences/stop', {
method: 'POST',
headers: { Accept: 'application/json' },
credentials: 'same-origin',
});
if (!res.ok) {
console.warn('Sequence stop failed:', res.status);
}
} catch (e) {
console.warn('Sequence stop:', e);
}
if (typeof window.ledControllerSequencePlaybackChanged === 'function') {
window.ledControllerSequencePlaybackChanged(false);
}
}
function normalizeSequenceLanes(doc) {
let lanesRaw = Array.isArray(doc && doc.lanes) ? doc.lanes : [];
let lanes = lanesRaw.filter((l) => Array.isArray(l));
const hasAnyLaneSteps = lanes.some((l) => l.length > 0);
if ((!lanes.length || !hasAnyLaneSteps) && Array.isArray(doc && doc.steps) && doc.steps.length) {
lanes = [doc.steps.slice()];
}
if (!lanes.length) lanes = [[]];
return lanes.map((lane) =>
lane
.filter((s) => s && typeof s === 'object')
.map((s) => ({
preset_id: s.preset_id != null ? String(s.preset_id) : String(s.presetId || ''),
animation_id: s.animation_id != null ? String(s.animation_id) : '',
rest: s.rest === true,
others: s.others === 'off' ? 'off' : '',
length: s.length === 'animation' ? 'animation' : '',
targets: Array.isArray(s.targets) ? s.targets.map((x) => parseInt(String(x), 10)).filter((x) => x >= 0) : [],
beats: Math.max(0.25, parseFloat(String(s.beats != null ? s.beats : 1)) || 1),
seconds: Math.max(0.1, parseFloat(String(s.seconds != null ? s.seconds : 3)) || 3),
group_ids: Array.isArray(s.group_ids)
? s.group_ids.map((x) => String(x).trim()).filter(Boolean)
: [],
})),
);
}
/**
* Log each preset in the sequence with its step beat count (beats per step before advancing).
* @param {string} sequenceId
* @param {Record<string, unknown>} sequenceDoc
* @param {Record<string, unknown>} presetsMap
*/
function logSequenceSelectionPresets(sequenceId, sequenceDoc, presetsMap) {
if (!sequenceDoc || typeof sequenceDoc !== 'object') return;
const lanes = normalizeSequenceLanes(sequenceDoc);
const nameFor = (pid) => {
const p = presetsMap && presetsMap[pid];
if (p && typeof p === 'object' && p.name != null && String(p.name).trim()) {
return String(p.name).trim();
}
return pid || '(unknown preset)';
};
const nm = String(sequenceDoc.name || '').trim() || sequenceId;
const multi =
lanes.filter((lane) => lane.some((s) => s && s.preset_id)).length > 1;
let headerLine = `Sequence "${nm}" (${sequenceId}) — advance: beats`;
if (multi) {
headerLine +=
' — header/audio beat readout follows lane 1 only (other lanes run in parallel)';
}
console.log(headerLine);
lanes.forEach((lane, li) => {
const steps = lane.filter((s) => s && s.preset_id);
if (!steps.length) return;
if (multi) console.log(`Lane ${li + 1}`);
steps.forEach((step) => {
const b = step.beats;
console.log(` ${nameFor(step.preset_id)}: ${b} beat${b === 1 ? '' : 's'}`);
});
});
}
function zoneGroupIdsFromDoc(zoneDoc) {
return Array.isArray(zoneDoc && zoneDoc.group_ids)
? zoneDoc.group_ids.map((x) => String(x).trim()).filter(Boolean)
: [];
}
function groupIdsForLaneStep(sequenceDoc, step, laneIndex, numLanes) {
const lgs = Array.isArray(sequenceDoc.lanes_group_ids) ? sequenceDoc.lanes_group_ids : [];
if (laneIndex < lgs.length) {
const forLane = lgs[laneIndex];
if (Array.isArray(forLane)) {
return forLane.map((x) => String(x).trim()).filter(Boolean);
}
}
if (numLanes > 1 && laneIndex >= lgs.length) {
return [];
}
const shared = Array.isArray(sequenceDoc.group_ids)
? sequenceDoc.group_ids.map((x) => String(x).trim()).filter((x) => x.length > 0)
: [];
if (shared.length) return shared;
if (numLanes === 1 && step && Array.isArray(step.group_ids) && step.group_ids.length) {
return step.group_ids.map((x) => String(x).trim()).filter(Boolean);
}
return [];
}
function splitDeviceNamesForLane(allNames, laneIndex, numLanes) {
const names = Array.isArray(allNames) ? allNames.filter((n) => n && String(n).trim()) : [];
if (numLanes <= 1) return names;
if (names.length >= numLanes) {
const n = names[laneIndex];
return n ? [n] : [];
}
return names;
}
function presetsSectionElForZone(zoneId) {
if (zoneId != null && String(zoneId).length) {
const el = document.querySelector(`.presets-section[data-zone-id="${String(zoneId)}"]`);
if (el) return el;
}
return document.querySelector('.presets-section[data-zone-id]');
}
/** Match preset tiles: prefer DOM device list, then zone JSON (same as parseTabDeviceNames + computeZoneTargets). */
async function resolveSequenceSendDeviceNames(zoneId, zoneDoc, groupIds) {
const gids = Array.isArray(groupIds) ? groupIds.map((x) => String(x).trim()).filter((x) => x.length > 0) : [];
if (window.zonesManager && typeof window.zonesManager.resolveSequenceStepDeviceNames === 'function' && zoneDoc) {
return await window.zonesManager.resolveSequenceStepDeviceNames(zoneDoc, gids);
}
return [];
}
/** Start sequence playback on the server (ESP-NOW / TCP delivery from backend). */
async function requestBackendSequencePlay(sequenceId, zoneId, sequenceDoc) {
// Do not call stop here: server start() already stops any prior run. A fire-and-forget
// client stop can reorder after play and clear the new session (same tile re-click bug).
const body = { zone_id: String(zoneId) };
const res = await fetch(`/sequences/${encodeURIComponent(sequenceId)}/play`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
credentials: 'same-origin',
body: JSON.stringify(body),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error((err && err.error) || res.statusText);
}
if (typeof window.ledControllerSequencePlaybackChanged === 'function') {
window.ledControllerSequencePlaybackChanged(true);
}
}
/** A one-shot plays once, then the zone goes back to its last looping preset or sequence. Its Loop is off
* (older records: kind "animation" with no loop). */
function seqIsOneShot(doc) {
if (!doc || typeof doc !== 'object') return false;
if (doc.loop === false || doc.loop === 0) return true;
return doc.loop == null && doc.kind === 'animation';
}
/** A zone's sequences, looping and one-shot (older zones keep one-shots apart in animation_ids). */
function zoneSequenceIds(zone) {
const out = [];
[zone && zone.sequence_ids, zone && zone.animation_ids].forEach((list) =>
(Array.isArray(list) ? list : []).forEach((x) => out.includes(String(x)) || out.push(String(x))),
);
return out;
}
/** Play a one-shot sequence once over whatever runs in the zone; its tile shows progress while it plays. */
async function fireOneShot(sequenceId, zoneId) {
const res = await fetch(`/sequences/${encodeURIComponent(sequenceId)}/fire`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ zone_id: zoneId ? String(zoneId) : '', wait: 'now' }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error((err && err.error) || res.statusText);
}
pollOneShotProgress();
}
let animProgressTimer = null;
async function pollOneShotProgress() {
if (animProgressTimer) clearTimeout(animProgressTimer);
animProgressTimer = null;
let ov = null;
try {
const r = await fetch('/sequences/status', { cache: 'no-store', headers: { Accept: 'application/json' } });
const st = r.ok ? await r.json() : null;
ov = st && st.overlay ? st.overlay : null;
} catch (_) {
ov = null;
}
document.querySelectorAll('.animation-tile-row').forEach((row) => {
const on = !!(ov && (ov.active || ov.pending) && String(ov.sequence_id || ov.pending_id) === row.dataset.sequenceId);
row.classList.toggle('firing', on);
row.style.setProperty('--anim-progress', on && ov.active ? String(ov.progress || 0) : '0');
});
if (ov && (ov.active || ov.pending)) animProgressTimer = setTimeout(pollOneShotProgress, 250);
}
async function fetchSequencesMap() {
try {
const res = await fetch('/sequences', { cache: 'no-store', headers: { Accept: 'application/json' } });
if (!res.ok) return {};
const data = await res.json();
return data && typeof data === 'object' ? data : {};
} catch (e) {
console.error('fetchSequencesMap:', e);
return {};
}
}
async function fetchGroupsMapSeq() {
try {
const res = await fetch('/groups', {
headers: { Accept: 'application/json' },
credentials: 'same-origin',
});
if (!res.ok) return {};
const data = await res.json();
return data && typeof data === 'object' ? data : {};
} catch (e) {
return {};
}
}
function createSequenceTileRow(sequenceId, sequenceDoc, zoneId, zoneDoc, allPresets, uiMode) {
const row = document.createElement('div');
const canDrag = false;
const isAnim = seqIsOneShot(sequenceDoc);
row.className = `preset-tile-row preset-tile-row--${uiMode} sequence-tile-row${isAnim ? ' animation-tile-row' : ''}${canDrag ? ' draggable-preset' : ''}`;
row.dataset.sequenceId = sequenceId;
const button = document.createElement('button');
button.type = 'button';
button.className = 'pattern-button preset-tile-main sequence-tile-main';
button.title = sequenceDoc.name || `Sequence ${sequenceId}`;
const label = document.createElement('span');
label.textContent = `${isAnim ? '⚡ ' : ''}${sequenceDoc.name || sequenceId}`;
label.style.fontWeight = 'bold';
label.className = 'pattern-button-label';
button.appendChild(label);
if (isAnim) {
// One shot: never becomes the active tile, so the sequence or preset underneath stays highlighted
button.title = `${sequenceDoc.name || sequenceId} — plays once, then back to what was running`;
const bar = document.createElement('span');
bar.className = 'animation-tile-progress';
button.appendChild(bar);
button.addEventListener('click', () => {
fireOneShot(sequenceId, zoneId).catch((e) => {
console.error(e);
alert(e.message || 'Could not play it.');
});
});
} else button.addEventListener('click', () => {
const strip = document.getElementById('presets-list-zone');
const clearActiveStrip = () => {
if (strip) strip.querySelectorAll('.pattern-button').forEach((btn) => btn.classList.remove('active'));
};
clearActiveStrip();
button.classList.add('active');
void (async () => {
let seq = sequenceDoc;
let zone = zoneDoc;
let presets = allPresets;
try {
const [sr, zr, pr] = await Promise.all([
fetch(`/sequences/${encodeURIComponent(sequenceId)}`, {
headers: { Accept: 'application/json' },
credentials: 'same-origin',
}),
fetch(`/zones/${encodeURIComponent(zoneId)}`, {
headers: { Accept: 'application/json' },
credentials: 'same-origin',
}),
fetch('/presets', { headers: { Accept: 'application/json' }, credentials: 'same-origin' }),
]);
if (sr.ok) {
const j = await sr.json();
if (j && typeof j === 'object' && !j.error) seq = j;
}
if (zr.ok) {
const j = await zr.json();
if (j && typeof j === 'object' && !j.error) zone = j;
}
if (pr.ok) {
const raw = await pr.json();
if (raw && typeof raw === 'object') {
if (typeof window.filterPresetsForCurrentProfile === 'function') {
presets = await window.filterPresetsForCurrentProfile(raw);
} else {
presets = raw;
}
}
}
} catch (e) {
console.warn('Sequence play: refresh fetch failed, using cached data', e);
}
logSequenceSelectionPresets(sequenceId, seq, presets);
try {
await requestBackendSequencePlay(sequenceId, zoneId, seq);
} catch (e) {
console.error(e);
alert(e.message || 'Sequence playback failed.');
}
})();
});
row.appendChild(button);
if (uiMode === 'edit') {
const actions = document.createElement('div');
actions.className = 'preset-tile-actions';
const editBtn = document.createElement('button');
editBtn.type = 'button';
editBtn.className = 'btn btn-secondary btn-small';
editBtn.textContent = 'Edit';
editBtn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
openSequenceEditor(sequenceId, sequenceDoc);
});
actions.appendChild(editBtn);
row.appendChild(actions);
}
return row;
}
async function appendZoneSequenceTiles(zoneId, zoneDoc, allPresets, paletteColors, presetsListEl) {
if (!presetsListEl || !zoneId) return;
const ids = zoneSequenceIds(zoneDoc);
if (!ids.length) return;
const sequences = await fetchSequencesMap();
const uiMode = typeof window.getPresetUiMode === 'function' ? window.getPresetUiMode() : 'run';
for (const sid of ids) {
const seq = sequences[sid];
if (!seq) continue;
const row = createSequenceTileRow(sid, seq, zoneId, zoneDoc, allPresets, uiMode);
presetsListEl.appendChild(row);
}
}
async function addSequenceToTab(sequenceId, zoneId) {
if (!zoneId) {
const leftPanel = document.querySelector('.presets-section[data-zone-id]');
zoneId = leftPanel ? leftPanel.dataset.zoneId : null;
}
if (!zoneId || !sequenceId) {
alert('Could not determine zone or sequence.');
return;
}
try {
const tabResponse = await fetch(`/zones/${zoneId}`, { headers: { Accept: 'application/json' } });
if (!tabResponse.ok) throw new Error('Failed to load zone');
const tabData = await tabResponse.json();
const list = zoneSequenceIds(tabData);
if (list.includes(String(sequenceId))) {
alert('Already on this zone.');
return;
}
list.push(String(sequenceId));
tabData.sequence_ids = list;
delete tabData.animation_ids;
const updateResponse = await fetch(`/zones/${zoneId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(tabData),
});
if (!updateResponse.ok) throw new Error('Failed to update zone');
if (typeof window.renderTabPresets === 'function') {
await window.renderTabPresets(zoneId);
}
} catch (e) {
console.error('addSequenceToTab:', e);
alert('Failed to add sequence to zone.');
}
}
async function removeSequenceFromTab(zoneId, sequenceId) {
if (!zoneId || !sequenceId) return;
try {
const tabResponse = await fetch(`/zones/${zoneId}`, { headers: { Accept: 'application/json' } });
if (!tabResponse.ok) throw new Error('Failed to load zone');
const tabData = await tabResponse.json();
const list = zoneSequenceIds(tabData);
const next = list.filter((x) => String(x) !== String(sequenceId));
if (next.length === list.length) {
alert('Not on this zone.');
return;
}
tabData.sequence_ids = next;
delete tabData.animation_ids;
const updateResponse = await fetch(`/zones/${zoneId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(tabData),
});
if (!updateResponse.ok) throw new Error('Failed to update zone');
if (typeof window.refreshEditTabSequencesUi === 'function') {
await window.refreshEditTabSequencesUi(zoneId);
}
if (typeof window.renderTabPresets === 'function') {
await window.renderTabPresets(zoneId);
}
} catch (e) {
console.error('removeSequenceFromTab:', e);
alert('Failed to remove sequence from zone.');
}
}
async function refreshEditTabSequencesUi(zoneId) {
const currentEl = document.getElementById('edit-zone-sequences-current');
const addEl = document.getElementById('edit-zone-sequences-list');
if (!currentEl || !addEl || !zoneId) return;
try {
const zoneRes = await fetch(`/zones/${zoneId}`, { headers: { Accept: 'application/json' } });
if (!zoneRes.ok) throw new Error('zone');
const zone = await zoneRes.json();
const onZone = zoneSequenceIds(zone);
const seqMap = await fetchSequencesMap();
const onSet = new Set(onZone);
currentEl.innerHTML = '';
if (!onZone.length) {
currentEl.innerHTML = '<span class="muted-text">No sequences on this zone yet.</span>';
} else {
for (const sid of onZone) {
const sdoc = seqMap[sid] || {};
const name = `${seqIsOneShot(sdoc) ? '⚡ ' : ''}${sdoc.name || sid}`;
const row = document.createElement('div');
row.className = 'profiles-row edit-zone-item-row';
const span = document.createElement('span');
span.textContent = `${name} — ${sid}`;
const rm = document.createElement('button');
rm.type = 'button';
rm.className = 'btn btn-danger btn-small';
rm.textContent = 'Remove';
rm.addEventListener('click', async () => {
if (!window.confirm(`Remove this sequence from the zone?\n\n${name}`)) return;
await removeSequenceFromTab(zoneId, sid);
});
row.appendChild(span);
row.appendChild(rm);
currentEl.appendChild(row);
}
}
addEl.innerHTML = '';
const allIds = Object.keys(seqMap);
const available = allIds.filter((id) => !onSet.has(String(id)));
if (!available.length) {
addEl.innerHTML =
'<span class="muted-text">No sequences to add.</span>';
} else {
const wrap = document.createElement('div');
wrap.className = 'zone-devices-add profiles-actions';
const sel = document.createElement('select');
sel.className = 'zone-device-add-select';
sel.setAttribute('aria-label', 'Sequence to add to this zone');
sel.appendChild(new Option('Add sequence…', ''));
available
.slice()
.sort((a, b) => {
const na = (seqMap[a] && seqMap[a].name) || a;
const nb = (seqMap[b] && seqMap[b].name) || b;
return String(na).localeCompare(String(nb), undefined, { sensitivity: 'base' });
})
.forEach((id) => {
const n = (seqMap[id] && seqMap[id].name) || id;
const a = seqIsOneShot(seqMap[id]) ? '⚡ ' : '';
sel.appendChild(new Option(`${a}${n} — ${id}`, id));
});
const addBtn = document.createElement('button');
addBtn.type = 'button';
addBtn.className = 'btn btn-primary btn-small';
addBtn.textContent = 'Add';
addBtn.addEventListener('click', async () => {
const id = sel.value;
if (!id) return;
await addSequenceToTab(id, zoneId);
sel.value = '';
await refreshEditTabSequencesUi(zoneId);
});
wrap.appendChild(sel);
wrap.appendChild(addBtn);
addEl.appendChild(wrap);
}
} catch (e) {
console.error('refreshEditTabSequencesUi:', e);
currentEl.innerHTML = '<span class="muted-text">Failed to load sequences.</span>';
addEl.innerHTML = '';
}
}
let sequenceEditorId = null;
/* ------------------------------------------------------------------ editor
* Sequence editor state: the sequence's targets (an ordered driver list: groups and/or single drivers;
* the timeline's tracks), the presets and one-shot sequences clips can play, and the groups/devices targets can
* name. Targets keep a local uid while editing; the timeline (seq_timeline.js) saves them as indexes.
*/
const seqEd = {
targets: [], // [{uid, name, group_ids: [], devices: []}]
presetsMap: {},
groupsMap: {},
devicesMap: {},
seqMap: {},
zoneGroupIds: [],
nextUid: 1,
};
function seqEdTargetLabel(t, i) {
const n = t && t.name ? String(t.name).trim() : '';
return n || `Target ${i + 1}`;
}
function addSeqTarget(t) {
if (seqEd.targets.length >= 32) {
alert('A sequence can have up to 32 targets.');
return false;
}
seqEd.targets.push({ uid: seqEd.nextUid++, name: '', group_ids: [], devices: [], ...t });
return true;
}
/** One target per driver in the current zone's groups, in device-list order (for chases). */
function addTargetsPerDriver() {
const macs = [];
const gids = seqEd.zoneGroupIds.length ? seqEd.zoneGroupIds : Object.keys(seqEd.groupsMap);
gids.forEach((gid) => {
const g = seqEd.groupsMap[gid];
(g && Array.isArray(g.devices) ? g.devices : []).forEach((m) => {
const mac = String(m).toLowerCase().replace(/[^0-9a-f]/g, '');
if (mac.length === 12 && !macs.includes(mac)) macs.push(mac);
});
});
if (!macs.length) {
alert('No drivers found in this zone\'s groups.');
return;
}
const have = new Set(seqEd.targets.filter((t) => t.devices.length === 1 && !t.group_ids.length).map((t) => t.devices[0]));
macs.forEach((mac) => {
if (have.has(mac)) return;
const d = seqEd.devicesMap[mac];
addSeqTarget({ name: (d && d.name) || mac, devices: [mac] });
});
}
/** Clip "what plays" picker: presets or one-shot sequences (a rest too). Values: p:<id>, a:<id>, rest. */
function buildStepPlaySelect(step) {
const sel = document.createElement('select');
sel.className = 'sequence-step-preset zone-device-add-select';
sel.appendChild(new Option('Select…', ''));
sel.appendChild(new Option('— Rest (off) —', 'rest'));
const byName = (map) => (a, b) =>
String((map[a] && map[a].name) || a).localeCompare(String((map[b] && map[b].name) || b), undefined, { sensitivity: 'base' });
const pg = document.createElement('optgroup');
pg.label = 'Presets';
Object.keys(seqEd.presetsMap)
.sort(byName(seqEd.presetsMap))
.forEach((pid) => pg.appendChild(new Option(`${(seqEd.presetsMap[pid] && seqEd.presetsMap[pid].name) || pid}`, `p:${pid}`)));
sel.appendChild(pg);
const anims = Object.keys(seqEd.seqMap).filter((id) => seqIsOneShot(seqEd.seqMap[id]) && id !== sequenceEditorId);
if (anims.length) {
const ag = document.createElement('optgroup');
ag.label = 'One-shot sequences';
anims.sort(byName(seqEd.seqMap)).forEach((id) => ag.appendChild(new Option(`⚡ ${seqEd.seqMap[id].name || id}`, `a:${id}`)));
sel.appendChild(ag);
}
if (step && step.rest) sel.value = 'rest';
else if (step && step.animation_id) sel.value = `a:${step.animation_id}`;
else if (step && step.preset_id) sel.value = `p:${step.preset_id}`;
return sel;
}
async function openSequenceEditor(sequenceId, existing) {
sequenceEditorId = sequenceId != null && String(sequenceId).length ? String(sequenceId) : null;
const modal = document.getElementById('sequence-editor-modal');
const nameInput = document.getElementById('sequence-editor-name');
if (!modal || !nameInput) return;
const [presetsRes, groupsMap, devicesRes, seqMap] = await Promise.all([
fetch('/presets', { headers: { Accept: 'application/json' } }),
fetchGroupsMapSeq(),
fetch('/devices', { headers: { Accept: 'application/json' } }).catch(() => null),
fetchSequencesMap(),
]);
const presetsMap = presetsRes.ok ? await presetsRes.json() : {};
let devicesMap = {};
if (devicesRes && devicesRes.ok) {
const d = await devicesRes.json().catch(() => ({}));
devicesMap = d && typeof d === 'object' ? d : {};
}
let zoneDoc = {};
const zoneIdForEditor = resolveZoneIdForPresetStripRefresh();
if (zoneIdForEditor) {
try {
const zr = await fetch(`/zones/${encodeURIComponent(zoneIdForEditor)}`, {
headers: { Accept: 'application/json' },
credentials: 'same-origin',
});
if (zr.ok) {
const zj = await zr.json();
if (zj && typeof zj === 'object' && !zj.error) zoneDoc = zj;
}
} catch (_) {
/* no zone context */
}
}
const zoneGroupIds = zoneGroupIdsFromDoc(zoneDoc);
let doc = existing;
if (sequenceEditorId) {
try {
const r = await fetch(`/sequences/${encodeURIComponent(sequenceEditorId)}`, {
cache: 'no-store',
headers: { Accept: 'application/json' },
credentials: 'same-origin',
});
if (r.ok) {
const j = await r.json();
if (j && typeof j === 'object' && !j.error) {
doc = j;
}
}
} catch (_) {
/* keep existing */
}
}
if (!doc || typeof doc !== 'object') {
doc = {};
}
seqEd.presetsMap = presetsMap;
seqEd.groupsMap = groupsMap;
seqEd.devicesMap = devicesMap;
seqEd.seqMap = seqMap;
seqEd.zoneGroupIds = zoneGroupIds;
seqEd.targets = [];
(Array.isArray(doc.targets) ? doc.targets : []).forEach((t) =>
addSeqTarget({
name: t && t.name ? String(t.name) : '',
group_ids: Array.isArray(t && t.group_ids) ? t.group_ids.map(String) : [],
devices: Array.isArray(t && t.devices) ? t.devices.map((m) => String(m).toLowerCase()) : [],
}),
);
nameInput.value = doc.name || '';
const modeSelOpen = document.getElementById('sequence-editor-mode');
const oneShot = seqIsOneShot(doc);
if (modeSelOpen) modeSelOpen.value = oneShot || doc.advance_mode === 'time' ? 'time' : 'beats';
const loopCb = document.getElementById('sequence-editor-loop');
if (loopCb) loopCb.checked = !oneShot;
const edDel = document.getElementById('sequence-editor-delete-btn');
if (edDel) edDel.style.display = sequenceEditorId ? 'inline-block' : 'none';
const edTry = document.getElementById('sequence-editor-try-btn');
if (edTry) edTry.style.display = sequenceEditorId ? 'inline-block' : 'none';
modal.classList.add('active');
seqTlOnOpen(doc);
}
/** Zone id for refreshing the visible preset/sequence strip if `getCurrentZoneId` is not set yet. */
function resolveZoneIdForPresetStripRefresh() {
if (window.zonesManager && typeof window.zonesManager.getCurrentZoneId === 'function') {
const z = window.zonesManager.getCurrentZoneId();
if (z != null && String(z).trim() !== '') {
return String(z).trim();
}
}
const sec = document.querySelector('.presets-section[data-zone-id]');
if (sec && sec.dataset.zoneId != null && String(sec.dataset.zoneId).trim() !== '') {
return String(sec.dataset.zoneId).trim();
}
return null;
}
async function saveSequenceEditor() {
const modeSel = document.getElementById('sequence-editor-mode');
const nameInput = document.getElementById('sequence-editor-name');
// The timeline (seq_timeline.js) saves one lane per track
const problem = tlSaveProblem();
if (problem) {
alert(problem);
return false;
}
const { lanes, lanes_group_ids, lane_opts } = tlToLanes();
const idxs = [];
lanes.forEach((l, i) => {
if (l.length) idxs.push(i);
});
if (!idxs.length) {
alert('Add at least one clip.');
return false;
}
const targets = seqEd.targets.map((t) => ({
name: String(t.name || '').trim(),
group_ids: [...t.group_ids],
devices: [...t.devices],
}));
const nonEmpty = idxs.map((i) => lanes[i]);
const opts = idxs.map((i) => lane_opts[i] || {});
// Lanes that play to targets also get their groups in lanes_group_ids, for readers that predate targets
const nonEmptyLg = idxs.map((i, k) => {
const own = lanes_group_ids[i] ? [...lanes_group_ids[i]] : [];
if (!targets.length || !opts[k].targets) return own;
const g = [];
opts[k].targets.forEach((ti) => (targets[ti] ? targets[ti].group_ids : []).forEach((x) => g.includes(x) || g.push(x)));
return g;
});
const loopCb = document.getElementById('sequence-editor-loop');
// Loop decides it: off makes a one-shot (older records also had kind "animation"; loop wins over it)
const payload = {
name: nameInput ? nameInput.value.trim() : '',
targets,
lanes: nonEmpty,
lane_opts: opts,
lanes_group_ids: nonEmptyLg,
group_ids: nonEmptyLg[0] ? [...nonEmptyLg[0]] : [],
// A one-shot (loop off) is always timed in seconds
advance_mode: (modeSel && modeSel.value === 'time') || (loopCb && !loopCb.checked) ? 'time' : 'beats',
loop: loopCb ? !!loopCb.checked : true,
steps: nonEmpty.length === 1 ? nonEmpty[0] : [],
};
try {
if (sequenceEditorId) {
const res = await fetch(`/sequences/${sequenceEditorId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(payload),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error((err && err.error) || res.statusText);
}
} else {
const res = await fetch('/sequences', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(payload),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error((err && err.error) || res.statusText);
}
const created = await res.json().catch(() => null);
if (created && typeof created === 'object') {
const entries = Object.entries(created);
if (entries.length > 0) {
sequenceEditorId = String(entries[0][0]);
const edDel = document.getElementById('sequence-editor-delete-btn');
if (edDel) edDel.style.display = 'inline-block';
const edTry = document.getElementById('sequence-editor-try-btn');
if (edTry) edTry.style.display = 'inline-block';
}
}
}
seqEd.seqMap = await fetchSequencesMap();
await loadSequencesModalList();
const zid = resolveZoneIdForPresetStripRefresh();
if (zid && typeof window.refreshEditTabSequencesUi === 'function') {
await window.refreshEditTabSequencesUi(zid);
}
if (zid && typeof window.renderTabPresets === 'function') {
await window.renderTabPresets(zid);
}
return true;
} catch (e) {
console.error(e);
alert(e.message || 'Failed to save sequence.');
return false;
}
}
async function deleteCurrentSequence() {
const idToDelete = sequenceEditorId;
if (!idToDelete) return;
if (!window.confirm('Delete this sequence? It will be removed from the server.')) return;
try {
const res = await fetch(`/sequences/${idToDelete}`, { method: 'DELETE' });
if (!res.ok) throw new Error('Delete failed');
const edModal = document.getElementById('sequence-editor-modal');
if (edModal) edModal.classList.remove('active');
sequenceEditorId = null;
await loadSequencesModalList();
const zid = resolveZoneIdForPresetStripRefresh();
if (zid) {
const tabResponse = await fetch(`/zones/${zid}`, { headers: { Accept: 'application/json' } });
if (tabResponse.ok) {
const tabData = await tabResponse.json();
const list = zoneSequenceIds(tabData);
const sid = String(idToDelete);
if (list.includes(sid)) {
tabData.sequence_ids = list.filter((x) => x !== sid);
delete tabData.animation_ids;
await fetch(`/zones/${zid}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(tabData),
});
}
}
if (typeof window.refreshEditTabSequencesUi === 'function') {
await window.refreshEditTabSequencesUi(zid);
}
if (typeof window.renderTabPresets === 'function') {
await window.renderTabPresets(zid);
}
}
} catch (e) {
console.error(e);
alert('Failed to delete sequence.');
}
}
async function loadSequencesModalList() {
const listEl = document.getElementById('sequences-list');
if (!listEl) return;
listEl.innerHTML = '<p class="muted-text">Loading…</p>';
const map = await fetchSequencesMap();
const ids = Object.keys(map).sort((a, b) => {
const na = (map[a] && map[a].name) || a;
const nb = (map[b] && map[b].name) || b;
return String(na).localeCompare(String(nb), undefined, { sensitivity: 'base' });
});
listEl.innerHTML = '';
if (!ids.length) {
listEl.innerHTML = '<p class="muted-text">No sequences yet.</p>';
return;
}
ids.forEach((id) => {
const doc = map[id] || {};
const row = document.createElement('div');
row.className = 'profiles-row';
row.style.cssText = 'display:flex;justify-content:space-between;align-items:center;gap:0.5rem;';
const title = document.createElement('span');
const ln = normalizeSequenceLanes(doc);
const nSteps = ln.reduce((a, l) => a + l.length, 0);
const nLanes = ln.filter((l) => l.length > 0).length || 1;
const once = seqIsOneShot(doc);
title.textContent = `${once ? '⚡ ' : ''}${doc.name || id} — ${once ? 'one-shot, ' : ''}${nLanes} track(s), ${nSteps} step(s)`;
const edit = document.createElement('button');
edit.type = 'button';
edit.className = 'btn btn-secondary btn-small';
edit.textContent = 'Edit';
edit.addEventListener('click', () => openSequenceEditor(id, doc));
row.appendChild(title);
row.appendChild(edit);
listEl.appendChild(row);
});
}
window.applySequenceSwitchWaitFromServer = applySequenceSwitchWaitFromServer;
window.setSequenceSwitchSimulatedMode = setSequenceSwitchSimulatedMode;
window.stopZoneSequencePlayback = stopZoneSequencePlayback;
/** @param {boolean} on */
window.setSequenceDebug = function setSequenceDebug(on) {
sequenceDebugEnabled = !!on;
console.log(seqDebugEnabled() ? 1 : 0);
};
window.appendZoneSequenceTiles = appendZoneSequenceTiles;
window.fireOneShot = fireOneShot;
window.refreshEditTabSequencesUi = refreshEditTabSequencesUi;
window.addSequenceToTab = addSequenceToTab;
window.removeSequenceFromTab = removeSequenceFromTab;
document.addEventListener('DOMContentLoaded', () => {
void initSequenceSwitchToggle();
const btn = document.getElementById('sequences-btn');
const modal = document.getElementById('sequences-modal');
const closeBtn = document.getElementById('sequences-close-btn');
const addBtn = document.getElementById('sequence-add-btn');
if (btn && modal) {
btn.addEventListener('click', () => {
modal.classList.add('active');
loadSequencesModalList();
});
}
if (closeBtn && modal) {
closeBtn.addEventListener('click', () => modal.classList.remove('active'));
}
if (addBtn) {
addBtn.addEventListener('click', () => {
sequenceEditorId = null;
openSequenceEditor(null, null);
});
}
const openPresetsFromSeq = document.getElementById('sequences-open-presets-btn');
if (openPresetsFromSeq) {
openPresetsFromSeq.addEventListener('click', () => {
const b = document.getElementById('presets-btn');
if (b) b.click();
else alert('Presets is not available.');
});
}
const edClose = document.getElementById('sequence-editor-close-btn');
const edSave = document.getElementById('sequence-editor-save-btn');
const edDel = document.getElementById('sequence-editor-delete-btn');
if (edClose) {
edClose.addEventListener('click', () => {
document.getElementById('sequence-editor-modal') && document.getElementById('sequence-editor-modal').classList.remove('active');
});
}
if (edSave) edSave.addEventListener('click', () => saveSequenceEditor());
if (edDel) edDel.addEventListener('click', () => deleteCurrentSequence());
const tryBtn = document.getElementById('sequence-editor-try-btn');
if (tryBtn) {
tryBtn.addEventListener('click', async () => {
if (!sequenceEditorId) return;
if ((await saveSequenceEditor()) === false) return;
const zid = resolveZoneIdForPresetStripRefresh();
const loopCb = document.getElementById('sequence-editor-loop');
try {
if (loopCb && !loopCb.checked) await fireOneShot(sequenceEditorId, zid);
else await requestBackendSequencePlay(sequenceEditorId, zid, null);
} catch (e) {
alert(e.message || 'Could not play it.');
}
});
}
});