// 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} sequenceDoc * @param {Record} 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 buildLaneGroupIdsForEditor(doc, laneIndex, numLanes) { const raw = Array.isArray(doc && doc.lanes_group_ids) ? doc.lanes_group_ids : []; if (laneIndex < raw.length) { const row = raw[laneIndex]; if (Array.isArray(row)) { return row.map(String).filter(Boolean); } } if (numLanes > 1 && laneIndex >= raw.length) { return []; } return []; } function renderLaneGroupCheckboxes(groupsMap, selectedIds, zoneGroupIds) { const wrap = document.createElement('div'); wrap.className = 'sequence-lane-groups-wrap'; wrap.style.cssText = 'margin-bottom:0.6rem;'; const row = document.createElement('div'); row.className = 'sequence-lane-groups'; row.style.cssText = 'display:flex;flex-wrap:wrap;gap:0.5rem;align-items:center;'; const sel = new Set((selectedIds || []).map((x) => String(x))); const zg = Array.isArray(zoneGroupIds) ? zoneGroupIds.map(String).filter(Boolean) : []; const gidsToShow = zg.length ? zg : Object.keys(groupsMap).sort((a, b) => a.localeCompare(b)); gidsToShow.forEach((gid) => { const g = groupsMap[gid]; const gn = g && g.name ? String(g.name) : gid; const id = `seq-lg-${gid}-${Math.random().toString(36).slice(2)}`; const lbl = document.createElement('label'); lbl.style.cssText = 'display:inline-flex;align-items:center;gap:0.25rem;font-size:0.9em;'; const cb = document.createElement('input'); cb.type = 'checkbox'; cb.className = 'sequence-lane-group'; cb.value = gid; cb.id = id; if (sel.has(String(gid))) cb.checked = true; const sp = document.createElement('span'); sp.textContent = `${gn} (${gid})`; lbl.appendChild(cb); lbl.appendChild(sp); row.appendChild(lbl); }); const editG = document.createElement('button'); editG.type = 'button'; editG.className = 'btn btn-secondary btn-small'; editG.textContent = 'Edit groups'; editG.title = 'Open Device groups'; editG.addEventListener('click', async () => { if (typeof window.openDeviceGroupsModal === 'function') { await window.openDeviceGroupsModal(); return; } const b = document.getElementById('groups-btn'); if (b) b.click(); else alert('Groups could not be opened.'); }); row.appendChild(editG); wrap.appendChild(row); return wrap; } 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); } } /** Play an animation once over whatever runs in the zone; its tile shows progress while it plays. */ async function fireAnimation(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); } pollAnimationProgress(); } let animProgressTimer = null; async function pollAnimationProgress() { 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(pollAnimationProgress, 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 = sequenceDoc && sequenceDoc.kind === 'animation'; 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', () => { fireAnimation(sequenceId, zoneId).catch((e) => { console.error(e); alert(e.message || 'Animation failed.'); }); }); } 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 = [ ...(Array.isArray(zoneDoc.sequence_ids) ? zoneDoc.sequence_ids.map((x) => String(x)) : []), ...(Array.isArray(zoneDoc.animation_ids) ? zoneDoc.animation_ids.map((x) => String(x)) : []), ]; 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 seqs = await fetchSequencesMap(); const field = seqs[sequenceId] && seqs[sequenceId].kind === 'animation' ? 'animation_ids' : 'sequence_ids'; const list = Array.isArray(tabData[field]) ? tabData[field].map(String) : []; if (list.includes(String(sequenceId))) { alert('Already on this zone.'); return; } list.push(String(sequenceId)); tabData[field] = list; 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 = Array.isArray(tabData.sequence_ids) ? tabData.sequence_ids.map(String) : []; const alist = Array.isArray(tabData.animation_ids) ? tabData.animation_ids.map(String) : []; const next = list.filter((x) => String(x) !== String(sequenceId)); const anext = alist.filter((x) => String(x) !== String(sequenceId)); if (next.length === list.length && anext.length === alist.length) { alert('Not on this zone.'); return; } tabData.sequence_ids = next; tabData.animation_ids = anext; 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 = [ ...(Array.isArray(zone.sequence_ids) ? zone.sequence_ids.map(String) : []), ...(Array.isArray(zone.animation_ids) ? zone.animation_ids.map(String) : []), ]; const seqMap = await fetchSequencesMap(); const onSet = new Set(onZone); currentEl.innerHTML = ''; if (!onZone.length) { currentEl.innerHTML = 'No sequences on this zone yet.'; } else { for (const sid of onZone) { const sdoc = seqMap[sid] || {}; const name = `${sdoc.kind === 'animation' ? '⚡ ' : ''}${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 = 'No sequences to add.'; } 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 = seqMap[id] && seqMap[id].kind === 'animation' ? '⚡ ' : ''; 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 = 'Failed to load sequences.'; addEl.innerHTML = ''; } } let sequenceEditorId = null; /** Insert point when dragging a step row vertically within a lane. */ function getDragAfterSequenceStepRow(container, y) { const draggableElements = [ ...container.querySelectorAll(':scope > .sequence-step-row:not(.dragging)'), ]; return draggableElements.reduce( (closest, child) => { const box = child.getBoundingClientRect(); const offset = y - box.top - box.height / 2; if (offset < 0 && offset > closest.offset) { return { offset, element: child }; } return closest; }, { offset: Number.NEGATIVE_INFINITY, element: null }, ).element; } /** Reorder step rows within one lane (DOM order = save order). */ function wireSequenceLaneStepsDragReorder(stepsHost) { if (!stepsHost || stepsHost.dataset.sequenceLaneDndWired === '1') return; stepsHost.dataset.sequenceLaneDndWired = '1'; let draggedRow = null; stepsHost.addEventListener('dragstart', (e) => { const handle = e.target.closest('.sequence-step-drag-handle'); if (!handle || !stepsHost.contains(handle)) return; const row = handle.closest('.sequence-step-row'); if (!row || !stepsHost.contains(row)) return; draggedRow = row; row.classList.add('dragging'); try { e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', 'sequence-step'); } catch (_) { /* ignore */ } }); stepsHost.addEventListener('dragend', () => { if (draggedRow) draggedRow.classList.remove('dragging'); draggedRow = null; }); stepsHost.addEventListener('dragenter', (e) => { if (!draggedRow || !stepsHost.contains(draggedRow)) return; e.preventDefault(); }); stepsHost.addEventListener('dragover', (e) => { if (!draggedRow || !stepsHost.contains(draggedRow)) return; e.preventDefault(); try { e.dataTransfer.dropEffect = 'move'; } catch (_) { /* ignore */ } const afterElement = getDragAfterSequenceStepRow(stepsHost, e.clientY); if (afterElement == null) { stepsHost.appendChild(draggedRow); } else if (afterElement !== draggedRow) { stepsHost.insertBefore(draggedRow, afterElement); } }); stepsHost.addEventListener('drop', (e) => { if (!draggedRow) return; e.preventDefault(); }); } /* ------------------------------------------------------------------ editor * Sequence editor state: the sequence's targets (an ordered driver list: groups and/or single drivers), * the presets and animations steps can play, and the groups/devices targets can name. Targets keep a * local uid while editing; lanes and steps store the uids and save them as indexes. */ const seqEd = { targets: [], // [{uid, name, group_ids: [], devices: []}] presetsMap: {}, groupsMap: {}, devicesMap: {}, seqMap: {}, zoneGroupIds: [], nextUid: 1, }; const LANES_MAX_UI = 16; function seqEdTargetLabel(t, i) { const n = t && t.name ? String(t.name).trim() : ''; return n || `Target ${i + 1}`; } /** Checkbox chips, one per target; `selected` is a set of uids. */ function renderTargetChips(host, selected, cls) { host.innerHTML = ''; host.dataset.chipClass = cls; if (!seqEd.targets.length) { const m = document.createElement('span'); m.className = 'muted-text'; m.textContent = 'No targets yet (add them above).'; host.appendChild(m); return; } seqEd.targets.forEach((t, i) => { const lbl = document.createElement('label'); lbl.className = 'seq-chip'; const cb = document.createElement('input'); cb.type = 'checkbox'; cb.className = cls; cb.value = String(t.uid); cb.checked = selected.has(String(t.uid)); const sp = document.createElement('span'); sp.textContent = seqEdTargetLabel(t, i); lbl.appendChild(cb); lbl.appendChild(sp); host.appendChild(lbl); }); } function chipSelection(host) { const out = new Set(); if (!host) return out; host.querySelectorAll('input[type=checkbox]:checked').forEach((c) => out.add(String(c.value))); return out; } /** Re-render every chip row after targets were added, renamed, moved or removed (keeping selections). */ function refreshAllTargetChips() { document.querySelectorAll('#sequence-editor-modal .seq-target-chips').forEach((host) => { renderTargetChips(host, chipSelection(host), host.dataset.chipClass || 'seq-chip-cb'); }); document.querySelectorAll('#sequence-editor-lanes .sequence-lane').forEach((laneEl) => { const legacy = laneEl.querySelector('.sequence-lane-groups-wrap'); if (legacy) legacy.style.display = seqEd.targets.length ? 'none' : ''; }); renderSequenceGrid(); } function renderTargetsPanel() { const host = document.getElementById('sequence-editor-targets'); if (!host) return; host.innerHTML = ''; seqEd.targets.forEach((t, i) => { const row = document.createElement('div'); row.className = 'seq-target-row profiles-row'; const num = document.createElement('span'); num.className = 'seq-target-num'; num.textContent = String(i + 1); const name = document.createElement('input'); name.type = 'text'; name.placeholder = `Target ${i + 1}`; name.value = t.name || ''; name.addEventListener('input', () => { t.name = name.value; refreshAllTargetChips(); }); const det = document.createElement('details'); const sum = document.createElement('summary'); const what = () => { const g = t.group_ids.map((id) => (seqEd.groupsMap[id] && seqEd.groupsMap[id].name) || id); const d = t.devices.map((m) => (seqEd.devicesMap[m] && seqEd.devicesMap[m].name) || m); const all = [...g, ...d]; return all.length ? all.join(', ') : 'Nothing picked'; }; sum.textContent = what(); det.appendChild(sum); const pick = document.createElement('div'); pick.className = 'seq-target-pick'; const addBox = (label, list, value) => { const l = document.createElement('label'); l.className = 'seq-chip'; const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = list.includes(value); cb.addEventListener('change', () => { const at = list.indexOf(value); if (cb.checked && at < 0) list.push(value); if (!cb.checked && at >= 0) list.splice(at, 1); sum.textContent = what(); }); const sp = document.createElement('span'); sp.textContent = label; l.appendChild(cb); l.appendChild(sp); pick.appendChild(l); }; const gh = document.createElement('div'); gh.className = 'muted-text'; gh.textContent = 'Groups'; pick.appendChild(gh); Object.keys(seqEd.groupsMap) .sort((a, b) => a.localeCompare(b, undefined, { numeric: true })) .forEach((gid) => addBox(`${(seqEd.groupsMap[gid] && seqEd.groupsMap[gid].name) || gid}`, t.group_ids, gid)); const dh = document.createElement('div'); dh.className = 'muted-text'; dh.textContent = 'Single drivers'; pick.appendChild(dh); Object.keys(seqEd.devicesMap) .sort((a, b) => String((seqEd.devicesMap[a] || {}).name || a).localeCompare(String((seqEd.devicesMap[b] || {}).name || b))) .forEach((mac) => addBox(`${(seqEd.devicesMap[mac] && seqEd.devicesMap[mac].name) || mac}`, t.devices, mac)); det.appendChild(pick); const btns = document.createElement('div'); btns.className = 'seq-target-btns'; const mk = (txt, title, fn, disabled) => { const b = document.createElement('button'); b.type = 'button'; b.className = 'btn btn-secondary btn-small'; b.textContent = txt; b.title = title; b.disabled = !!disabled; b.addEventListener('click', fn); btns.appendChild(b); return b; }; mk('↑', 'Move up', () => { seqEd.targets.splice(i - 1, 0, seqEd.targets.splice(i, 1)[0]); renderTargetsPanel(); }, i === 0); mk('↓', 'Move down', () => { seqEd.targets.splice(i + 1, 0, seqEd.targets.splice(i, 1)[0]); renderTargetsPanel(); }, i === seqEd.targets.length - 1); const rm = mk('Remove', 'Remove target', () => { seqEd.targets.splice(i, 1); renderTargetsPanel(); }); rm.className = 'btn btn-danger btn-small'; row.appendChild(num); row.appendChild(name); row.appendChild(det); row.appendChild(btns); host.appendChild(row); }); refreshAllTargetChips(); } 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] }); }); renderTargetsPanel(); } /** Step "what plays" picker: presets, animations, or a rest. Values: p:, a:, 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) => seqEd.seqMap[id] && seqEd.seqMap[id].kind === 'animation' && id !== sequenceEditorId); if (anims.length) { const ag = document.createElement('optgroup'); ag.label = 'Animations'; 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; } function renderSequenceStepRow(presetsMap, step) { const row = document.createElement('div'); row.className = 'sequence-step-row profiles-row'; row.style.cssText = 'display:flex;flex-direction:column;gap:0.35rem;margin-bottom:0.75rem;padding:0.5rem;border:1px solid rgba(255,255,255,0.12);border-radius:6px;'; const top = document.createElement('div'); top.style.cssText = 'display:flex;align-items:center;gap:0.75rem;flex-wrap:wrap;'; const dragHandle = document.createElement('span'); dragHandle.className = 'sequence-step-drag-handle'; dragHandle.draggable = true; dragHandle.title = 'Drag to reorder'; dragHandle.textContent = '⠿'; dragHandle.style.cssText = 'cursor:grab;user-select:none;flex-shrink:0;line-height:1;opacity:0.75;padding:0.15rem 0.25rem;'; const presetWrap = document.createElement('div'); presetWrap.style.cssText = 'display:flex;align-items:center;gap:0.5rem;flex-wrap:wrap;'; const pl = document.createElement('label'); pl.textContent = 'Plays'; const psel = buildStepPlaySelect(step); presetWrap.appendChild(pl); presetWrap.appendChild(psel); const beatWrap = document.createElement('div'); beatWrap.style.cssText = 'display:flex;align-items:center;gap:0.35rem;'; const bl = document.createElement('label'); bl.textContent = 'Beats'; const beatsInp = document.createElement('input'); beatsInp.type = 'number'; beatsInp.className = 'sequence-step-beats'; beatsInp.autocomplete = 'off'; beatsInp.min = '0.25'; beatsInp.max = '256'; beatsInp.step = '0.25'; beatsInp.value = String(step && step.beats != null ? Math.max(0.25, parseFloat(String(step.beats)) || 1) : 1); beatsInp.style.width = '4.5rem'; beatWrap.appendChild(bl); beatWrap.appendChild(beatsInp); beatWrap.classList.add('sequence-step-beats-wrap'); const secWrap = document.createElement('div'); secWrap.className = 'sequence-step-seconds-wrap'; secWrap.style.cssText = 'display:flex;align-items:center;gap:0.35rem;'; const sl = document.createElement('label'); sl.textContent = 'Seconds'; const secInp = document.createElement('input'); secInp.type = 'number'; secInp.className = 'sequence-step-seconds'; secInp.autocomplete = 'off'; secInp.min = '0.1'; secInp.max = '3600'; secInp.step = '0.1'; secInp.value = String(step && step.seconds != null ? Math.max(0.1, parseFloat(String(step.seconds)) || 3) : 3); secInp.style.width = '5rem'; secWrap.appendChild(sl); secWrap.appendChild(secInp); const editPresetBtn = document.createElement('button'); editPresetBtn.type = 'button'; editPresetBtn.className = 'btn btn-secondary btn-small'; editPresetBtn.textContent = 'Edit'; editPresetBtn.title = 'Edit the preset or animation'; editPresetBtn.addEventListener('click', async (e) => { e.preventDefault(); const v = psel.value || ''; if (v.startsWith('a:')) { openSequenceEditor(v.slice(2), seqEd.seqMap[v.slice(2)]); return; } const presetId = v.startsWith('p:') ? v.slice(2) : ''; if (!presetId) { alert('Select a preset first.'); return; } let preset = presetsMap[presetId]; try { const r = await fetch(`/presets/${presetId}`, { headers: { Accept: 'application/json' } }); if (r.ok) preset = await r.json(); } catch (_) { /* keep cached */ } preset = preset && typeof preset === 'object' ? preset : {}; document.dispatchEvent( new CustomEvent('editPreset', { detail: { presetId, preset, zoneId: null }, }), ); }); top.appendChild(dragHandle); top.appendChild(presetWrap); top.appendChild(beatWrap); top.appendChild(secWrap); top.appendChild(editPresetBtn); row.appendChild(top); // More: which targets this step lights, others off, animation length const more = document.createElement('details'); more.className = 'seq-step-more'; const ms = document.createElement('summary'); ms.textContent = 'Targets and options'; more.appendChild(ms); const chips = document.createElement('div'); chips.className = 'seq-target-chips seq-step-targets'; const stepSel = new Set(); (step && Array.isArray(step.targets) ? step.targets : []).forEach((ix) => { if (seqEd.targets[ix]) stepSel.add(String(seqEd.targets[ix].uid)); }); if (step && step._uids) step._uids.forEach((u) => stepSel.add(String(u))); renderTargetChips(chips, stepSel, 'seq-step-target'); const chipsHint = document.createElement('div'); chipsHint.className = 'muted-text'; chipsHint.textContent = 'Lights only these (none ticked: all of the lane\'s targets, or the chase).'; more.appendChild(chipsHint); more.appendChild(chips); const opts = document.createElement('div'); opts.style.cssText = 'display:flex;gap:1rem;flex-wrap:wrap;margin-top:0.35rem;'; const othersLbl = document.createElement('label'); const othersCb = document.createElement('input'); othersCb.type = 'checkbox'; othersCb.className = 'sequence-step-others-off'; othersCb.checked = !!(step && step.others === 'off'); othersLbl.appendChild(othersCb); othersLbl.appendChild(document.createTextNode(' Lane\'s other targets off')); const lenLbl = document.createElement('label'); lenLbl.className = 'sequence-step-length-wrap'; const lenCb = document.createElement('input'); lenCb.type = 'checkbox'; lenCb.className = 'sequence-step-anim-length'; lenCb.checked = !step || step.length === 'animation' || !step.animation_id; lenLbl.appendChild(lenCb); lenLbl.appendChild(document.createTextNode(' Step lasts as long as the animation')); opts.appendChild(othersLbl); opts.appendChild(lenLbl); more.appendChild(opts); if (stepSel.size || othersCb.checked) more.open = true; row.appendChild(more); const syncKind = () => { const v = psel.value || ''; const anim = v.startsWith('a:'); lenLbl.style.display = anim ? '' : 'none'; editPresetBtn.disabled = !(anim || v.startsWith('p:')); renderSequenceGrid(); }; psel.addEventListener('change', syncKind); beatsInp.addEventListener('input', () => renderSequenceGrid()); secInp.addEventListener('input', () => renderSequenceGrid()); syncKind(); const rm = document.createElement('button'); rm.type = 'button'; rm.className = 'btn btn-danger btn-small'; rm.textContent = 'Remove step'; rm.addEventListener('click', () => { row.remove(); renderSequenceGrid(); }); row.appendChild(rm); return row; } function laneOptsField(label, input) { const l = document.createElement('label'); l.className = 'seq-lane-opt'; const sp = document.createElement('span'); sp.textContent = label; l.appendChild(sp); l.appendChild(input); return l; } function renderLaneOptions(opts) { const o = opts && typeof opts === 'object' ? opts : {}; const box = document.createElement('div'); box.className = 'seq-lane-opts'; const mode = document.createElement('select'); mode.className = 'seq-lane-mode zone-device-add-select'; [['', 'Sequence default'], ['beats', 'Beats'], ['time', 'Seconds']].forEach(([v, t]) => mode.appendChild(new Option(t, v))); mode.value = o.mode === 'beats' || o.mode === 'time' ? o.mode : ''; mode.addEventListener('change', applySequenceEditorMode); const offset = document.createElement('input'); offset.type = 'number'; offset.className = 'seq-lane-offset'; offset.min = '0'; offset.step = '0.25'; offset.value = String(Math.max(0, parseFloat(String(o.offset || 0)) || 0)); offset.style.width = '4.5rem'; offset.title = 'Beats (or seconds) before this lane starts'; const rate = document.createElement('select'); rate.className = 'seq-lane-rate zone-device-add-select'; [['0.25', '¼×'], ['0.5', '½×'], ['1', '1×'], ['2', '2×'], ['4', '4×']].forEach(([v, t]) => rate.appendChild(new Option(t, v))); rate.value = String(o.rate || 1); if (!rate.value) rate.value = '1'; box.appendChild(laneOptsField('Timing', mode)); box.appendChild(laneOptsField('Start after', offset)); box.appendChild(laneOptsField('Speed', rate)); const tLbl = document.createElement('div'); tLbl.className = 'muted-text'; tLbl.textContent = 'Plays to'; const chips = document.createElement('div'); chips.className = 'seq-target-chips seq-lane-targets'; const sel = new Set(); (Array.isArray(o.targets) ? o.targets : []).forEach((ix) => { if (seqEd.targets[ix]) sel.add(String(seqEd.targets[ix].uid)); }); renderTargetChips(chips, sel, 'seq-lane-target'); chips.addEventListener('change', () => renderSequenceGrid()); const chase = o.chase && typeof o.chase === 'object' ? o.chase : null; const chaseRow = document.createElement('div'); chaseRow.className = 'seq-lane-chase'; const chaseCb = document.createElement('input'); chaseCb.type = 'checkbox'; chaseCb.className = 'seq-lane-chase-on'; chaseCb.checked = !!chase; const chaseLbl = document.createElement('label'); chaseLbl.appendChild(chaseCb); chaseLbl.appendChild(document.createTextNode(' Chase: each step moves to the next target')); const order = document.createElement('select'); order.className = 'seq-lane-chase-order zone-device-add-select'; [['forward', 'Forward'], ['reverse', 'Reverse'], ['bounce', 'Bounce'], ['random', 'Random']].forEach(([v, t]) => order.appendChild(new Option(t, v))); order.value = (chase && chase.order) || 'forward'; const width = document.createElement('input'); width.type = 'number'; width.className = 'seq-lane-chase-width'; width.min = '1'; width.max = '32'; width.value = String((chase && chase.width) || 1); width.style.width = '3.5rem'; width.title = 'How many targets are lit at once'; const others = document.createElement('select'); others.className = 'seq-lane-chase-others zone-device-add-select'; [['off', 'Others off'], ['hold', 'Others hold']].forEach(([v, t]) => others.appendChild(new Option(t, v))); others.value = chase && chase.others === 'hold' ? 'hold' : 'off'; const chaseOpts = document.createElement('span'); chaseOpts.className = 'seq-lane-chase-opts'; chaseOpts.appendChild(order); chaseOpts.appendChild(laneOptsField('Width', width)); chaseOpts.appendChild(others); const syncChase = () => { chaseOpts.style.display = chaseCb.checked ? '' : 'none'; }; chaseCb.addEventListener('change', syncChase); syncChase(); chaseRow.appendChild(chaseLbl); chaseRow.appendChild(chaseOpts); box.appendChild(tLbl); box.appendChild(chips); box.appendChild(chaseRow); return box; } function renderSequenceLane(laneIndex, laneSteps, laneGroupIds, presetsMap, groupsMap, zoneGroupIds, laneOpts) { const wrap = document.createElement('div'); wrap.className = 'sequence-lane'; wrap.dataset.laneIndex = String(laneIndex); const head = document.createElement('div'); head.style.cssText = 'display:flex;align-items:center;justify-content:space-between;gap:0.5rem;margin-bottom:0.5rem;flex-wrap:wrap;'; const title = document.createElement('strong'); title.textContent = `Lane ${laneIndex + 1}`; head.appendChild(title); const headBtns = document.createElement('div'); headBtns.style.cssText = 'display:flex;gap:0.35rem;flex-wrap:wrap;'; const addStep = document.createElement('button'); addStep.type = 'button'; addStep.className = 'btn btn-secondary btn-small'; addStep.textContent = 'Add step'; addStep.addEventListener('click', () => { const stepsHost = wrap.querySelector('.sequence-lane-steps'); if (stepsHost) { stepsHost.appendChild(renderSequenceStepRow(presetsMap, { preset_id: '', beats: 1, seconds: 3 })); applySequenceEditorMode(); } }); const dupLane = document.createElement('button'); dupLane.type = 'button'; dupLane.className = 'btn btn-secondary btn-small'; dupLane.textContent = 'Duplicate'; dupLane.title = 'Copy this lane (then give the copy an offset for a canon)'; dupLane.addEventListener('click', () => { const host = document.getElementById('sequence-editor-lanes'); if (!host || host.querySelectorAll('.sequence-lane').length >= LANES_MAX_UI) { alert(`A sequence can have up to ${LANES_MAX_UI} lanes.`); return; } const data = collectLaneFromEl(wrap); const copy = renderSequenceLane(0, data.steps.map((s) => ({ ...s, _uids: s._uids })), data.groups, presetsMap, groupsMap, zoneGroupIds, data.optsUi); wrap.after(copy); refreshSequenceEditorLaneTitles(); applySequenceEditorMode(); }); const rmLane = document.createElement('button'); rmLane.type = 'button'; rmLane.className = 'btn btn-danger btn-small sequence-lane-remove-lane'; rmLane.textContent = 'Remove lane'; rmLane.addEventListener('click', () => { const host = document.getElementById('sequence-editor-lanes'); const n = host ? host.querySelectorAll('.sequence-lane').length : 1; if (n <= 1) return; wrap.remove(); refreshSequenceEditorLaneTitles(); }); headBtns.appendChild(addStep); headBtns.appendChild(dupLane); headBtns.appendChild(rmLane); head.appendChild(headBtns); wrap.appendChild(head); wrap.appendChild(renderLaneOptions(laneOpts)); // Older sequences: groups per lane, shown while the sequence has no targets const legacy = renderLaneGroupCheckboxes(groupsMap, laneGroupIds, zoneGroupIds); if (seqEd.targets.length) legacy.style.display = 'none'; wrap.appendChild(legacy); const stepsHost = document.createElement('div'); stepsHost.className = 'sequence-lane-steps'; const steps = Array.isArray(laneSteps) && laneSteps.length ? laneSteps : [{ preset_id: '', beats: 1, seconds: 3 }]; steps.forEach((s) => { stepsHost.appendChild(renderSequenceStepRow(presetsMap, s)); }); wireSequenceLaneStepsDragReorder(stepsHost); stepsHost.addEventListener('drop', () => setTimeout(renderSequenceGrid, 0)); wrap.appendChild(stepsHost); return wrap; } function refreshSequenceEditorLaneTitles() { const host = document.getElementById('sequence-editor-lanes'); if (!host) return; const lanes = [...host.querySelectorAll('.sequence-lane')]; lanes.forEach((el, i) => { el.dataset.laneIndex = String(i); const t = el.querySelector(':scope > div strong'); if (t) t.textContent = `Lane ${i + 1}`; const rm = el.querySelector('.sequence-lane-remove-lane'); if (rm) rm.disabled = lanes.length <= 1; }); const add = document.getElementById('sequence-editor-add-lane-btn'); if (add) add.disabled = lanes.length >= LANES_MAX_UI; renderSequenceGrid(); } function laneIsTimed(laneEl) { const sel = document.getElementById('sequence-editor-mode'); const def = !!sel && sel.value === 'time'; const m = laneEl.querySelector('.seq-lane-mode'); return m && m.value ? m.value === 'time' : def; } /** Show the Beats or Seconds field on every step, to match its lane's timing. */ function applySequenceEditorMode() { document.querySelectorAll('#sequence-editor-lanes .sequence-lane').forEach((laneEl) => { const timed = laneIsTimed(laneEl); laneEl.querySelectorAll('.sequence-step-beats-wrap').forEach((e) => { e.style.display = timed ? 'none' : 'flex'; }); laneEl.querySelectorAll('.sequence-step-seconds-wrap').forEach((e) => { e.style.display = timed ? 'flex' : 'none'; }); const off = laneEl.querySelector('.seq-lane-offset'); if (off) off.title = timed ? 'Seconds before this lane starts' : 'Beats before this lane starts'; }); renderSequenceGrid(); } function uidsToIndexes(uids) { const out = []; seqEd.targets.forEach((t, i) => { if (uids.has(String(t.uid))) out.push(i); }); return out; } /** One lane from the editor: its steps (saved form), legacy groups and options. */ function collectLaneFromEl(laneEl) { const groups = []; laneEl.querySelectorAll('.sequence-lane-group:checked').forEach((c) => { if (c.value) groups.push(String(c.value)); }); const steps = []; const stepsHost = laneEl.querySelector('.sequence-lane-steps'); const rows = stepsHost ? stepsHost.querySelectorAll(':scope > .sequence-step-row') : []; rows.forEach((row) => { const v = (row.querySelector('.sequence-step-preset') || {}).value || ''; if (!v) return; const beatsInp = row.querySelector('.sequence-step-beats'); const secInp = row.querySelector('.sequence-step-seconds'); const beats = Math.max(0.25, parseFloat(beatsInp && beatsInp.value ? beatsInp.value : '1') || 1); const seconds = Math.max(0.1, parseFloat(secInp && secInp.value ? secInp.value : '3') || 3); const st = { beats, seconds }; if (v === 'rest') { st.preset_id = ''; st.rest = true; } else if (v.startsWith('a:')) { st.animation_id = v.slice(2); const len = row.querySelector('.sequence-step-anim-length'); if (len && len.checked) st.length = 'animation'; } else { st.preset_id = v.slice(2); } const uids = chipSelection(row.querySelector('.seq-step-targets')); if (uids.size) { st.targets = uidsToIndexes(uids); st._uids = [...uids]; } const oo = row.querySelector('.sequence-step-others-off'); if (oo && oo.checked) st.others = 'off'; st._row = row; steps.push(st); }); const q = (c) => laneEl.querySelector(c); const laneUids = chipSelection(q('.seq-lane-targets')); const opts = {}; const mode = q('.seq-lane-mode'); if (mode && mode.value) opts.mode = mode.value; const off = parseFloat((q('.seq-lane-offset') || {}).value || '0') || 0; if (off > 0) opts.offset = off; const rate = parseFloat((q('.seq-lane-rate') || {}).value || '1') || 1; if (rate !== 1) opts.rate = rate; if (laneUids.size) opts.targets = uidsToIndexes(laneUids); const chaseOn = q('.seq-lane-chase-on'); if (chaseOn && chaseOn.checked) { opts.chase = { order: (q('.seq-lane-chase-order') || {}).value || 'forward', width: Math.max(1, parseInt((q('.seq-lane-chase-width') || {}).value || '1', 10) || 1), others: (q('.seq-lane-chase-others') || {}).value === 'hold' ? 'hold' : 'off', }; } return { steps, groups, opts, optsUi: { ...opts }, timed: laneIsTimed(laneEl) }; } function collectLanesFromEditor() { const host = document.getElementById('sequence-editor-lanes'); const laneEls = host ? [...host.querySelectorAll('.sequence-lane')] : []; const lanes = []; const lanes_group_ids = []; const lane_opts = []; laneEls.forEach((laneEl) => { const l = collectLaneFromEl(laneEl); lanes.push(l.steps.map(({ _row, _uids, ...st }) => st)); lanes_group_ids.push(l.groups); lane_opts.push(l.opts); }); return { lanes, lanes_group_ids, lane_opts }; } /* -------------------------------------------------------------- grid view */ let seqGridTimer = null; function seqStepLabel(st) { if (st.rest) return { text: 'rest', color: '' }; if (st.animation_id) { const a = seqEd.seqMap[st.animation_id]; return { text: `⚡ ${(a && a.name) || st.animation_id}`, color: '' }; } const p = seqEd.presetsMap[st.preset_id]; const colors = p && Array.isArray(p.colors) ? p.colors : []; return { text: (p && p.name) || st.preset_id, color: colors[0] || '' }; } /** Lanes side by side on a shared time axis: one row per lane, cells as wide as their steps. */ function renderSequenceGrid() { const host = document.getElementById('sequence-editor-grid'); if (!host || host.hidden) return; const laneHost = document.getElementById('sequence-editor-lanes'); const laneEls = laneHost ? [...laneHost.querySelectorAll('.sequence-lane')] : []; host.innerHTML = ''; const bpm = parseFloat((document.getElementById('audio-simulated-bpm') || {}).value || '120') || 120; const beatS = 60 / bpm; const rows = laneEls.map((el) => collectLaneFromEl(el)); // Lengths in beats (time lanes converted at the clock tempo) const len = (l, st) => (l.timed ? st.seconds / beatS : st.beats) / (l.opts.rate || 1); const offs = (l) => (l.opts.offset || 0) / (l.timed ? beatS : 1); const total = Math.max(4, ...rows.map((l) => offs(l) + l.steps.reduce((a, st) => a + len(l, st), 0))); const scale = 100 / total; rows.forEach((l, li) => { const row = document.createElement('div'); row.className = 'seq-grid-row'; const name = document.createElement('div'); name.className = 'seq-grid-lane'; const tnames = (l.opts.targets || []).map((i) => seqEdTargetLabel(seqEd.targets[i], i)); name.textContent = `${li + 1}${l.opts.chase ? ' ⇢' : ''}`; name.title = tnames.length ? tnames.join(', ') : 'Lane groups / zone'; const track = document.createElement('div'); track.className = 'seq-grid-track'; if (offs(l) > 0) { const gap = document.createElement('div'); gap.className = 'seq-grid-cell seq-grid-gap'; gap.style.width = `${offs(l) * scale}%`; track.appendChild(gap); } l.steps.forEach((st, si) => { const cell = document.createElement('button'); cell.type = 'button'; cell.className = 'seq-grid-cell'; cell.dataset.lane = String(li); cell.dataset.step = String(si); cell.style.width = `${len(l, st) * scale}%`; const lab = seqStepLabel(st); cell.textContent = lab.text; if (st.rest) cell.classList.add('seq-grid-rest'); if (st.animation_id) cell.classList.add('seq-grid-anim'); if (lab.color) cell.style.setProperty('--cell-color', lab.color); cell.title = `${lab.text} — ${l.timed ? `${st.seconds}s` : `${st.beats} beat(s)`}${st.targets ? ` → ${st.targets.map((i) => seqEdTargetLabel(seqEd.targets[i], i)).join(', ')}` : ''}`; cell.addEventListener('click', () => { // Swap the cell for the step's own picker, so changes land on the step const sel = buildStepPlaySelect(st); sel.className = 'seq-grid-pick'; cell.replaceWith(sel); sel.style.width = cell.style.width; sel.focus(); const done = () => { const src = st._row && st._row.querySelector('.sequence-step-preset'); if (src && sel.value && src.value !== sel.value) { src.value = sel.value; src.dispatchEvent(new Event('change')); } else { renderSequenceGrid(); } }; sel.addEventListener('change', done); sel.addEventListener('blur', () => setTimeout(renderSequenceGrid, 0)); }); track.appendChild(cell); }); row.appendChild(name); row.appendChild(track); host.appendChild(row); }); const axis = document.createElement('div'); axis.className = 'muted-text seq-grid-axis'; axis.textContent = `${Math.round(total * 100) / 100} beats per pass (seconds shown at ${bpm} BPM)`; host.appendChild(axis); } /** Highlight the playing steps in the grid while this sequence (or animation) plays. */ async function pollSequenceGridPlayhead() { const host = document.getElementById('sequence-editor-grid'); const modal = document.getElementById('sequence-editor-modal'); if (!host || host.hidden || !modal || !modal.classList.contains('active') || !sequenceEditorId) { seqGridTimer = null; return; } try { const r = await fetch('/sequences/status', { cache: 'no-store', headers: { Accept: 'application/json' } }); const st = r.ok ? await r.json() : null; let lanes = null; if (st && st.active && String(st.sequence_id) === sequenceEditorId) lanes = st.lanes; else if (st && st.overlay && st.overlay.active && String(st.overlay.sequence_id) === sequenceEditorId) lanes = st.overlay.lanes; host.querySelectorAll('.seq-grid-cell.playing').forEach((c) => c.classList.remove('playing')); (Array.isArray(lanes) ? lanes : []).forEach((l, li) => { if (!l || !l.started || l.done) return; const c = host.querySelector(`.seq-grid-cell[data-lane="${li}"][data-step="${l.step}"]`); if (c) c.classList.add('playing'); }); } catch (_) { /* try again */ } seqGridTimer = setTimeout(pollSequenceGridPlayhead, 400); } function setSequenceEditorView(grid) { const g = document.getElementById('sequence-editor-grid'); const btn = document.getElementById('sequence-editor-view-btn'); if (!g) return; g.hidden = !grid; if (btn) btn.textContent = grid ? 'Hide grid' : 'Show grid'; try { localStorage.setItem('seqEditorGrid', grid ? '1' : '0'); } catch (_) { /* private mode */ } if (grid) { renderSequenceGrid(); if (!seqGridTimer) pollSequenceGridPlayhead(); } } function applySequenceKindUi() { const kind = document.getElementById('sequence-editor-kind'); const anim = !!kind && kind.value === 'animation'; const hint = document.getElementById('sequence-editor-kind-hint'); if (hint) { hint.textContent = anim ? 'An animation plays once over whatever is running, then the drivers go back to it. Fire it from a zone tile or from a step of a sequence.' : 'A sequence plays in a zone, looping unless Loop is off.'; } } 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'); const lanesHost = document.getElementById('sequence-editor-lanes'); if (!modal || !nameInput || !lanesHost) 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'); if (modeSelOpen) modeSelOpen.value = doc.advance_mode === 'time' ? 'time' : 'beats'; const kindSel = document.getElementById('sequence-editor-kind'); const isAnim = doc.kind === 'animation' || (!sequenceEditorId && seqEditorNewKind === 'animation'); if (kindSel) kindSel.value = isAnim ? 'animation' : 'sequence'; const loopCb = document.getElementById('sequence-editor-loop'); if (loopCb) loopCb.checked = doc.loop == null ? !isAnim : doc.loop === true || doc.loop === 1; applySequenceKindUi(); const lanes = normalizeSequenceLanes(doc); const laneOpts = Array.isArray(doc.lane_opts) ? doc.lane_opts : []; renderTargetsPanel(); lanesHost.innerHTML = ''; if (!lanes.some((l) => l.length > 0)) { const lg0 = buildLaneGroupIdsForEditor(doc, 0, 1); lanesHost.appendChild(renderSequenceLane(0, [], lg0, presetsMap, groupsMap, zoneGroupIds, laneOpts[0])); } else { lanes.forEach((laneSteps, i) => { const lg = buildLaneGroupIdsForEditor(doc, i, lanes.length); lanesHost.appendChild(renderSequenceLane(i, laneSteps, lg, presetsMap, groupsMap, zoneGroupIds, laneOpts[i])); }); } refreshSequenceEditorLaneTitles(); applySequenceEditorMode(); 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'; let grid = false; try { grid = localStorage.getItem('seqEditorGrid') === '1'; } catch (_) { grid = false; } modal.classList.add('active'); setSequenceEditorView(grid); } let seqEditorNewKind = 'sequence'; /** 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'); const { lanes, lanes_group_ids, lane_opts } = collectLanesFromEditor(); const idxs = []; lanes.forEach((l, i) => { if (l.length) idxs.push(i); }); if (!idxs.length) { alert('Add at least one step with a preset, animation or rest.'); return; } 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 kindSel = document.getElementById('sequence-editor-kind'); const loopCb = document.getElementById('sequence-editor-loop'); const payload = { name: nameInput ? nameInput.value.trim() : '', kind: kindSel && kindSel.value === 'animation' ? 'animation' : 'sequence', targets, lanes: nonEmpty, lane_opts: opts, lanes_group_ids: nonEmptyLg, group_ids: nonEmptyLg[0] ? [...nonEmptyLg[0]] : [], advance_mode: modeSel && modeSel.value === 'time' ? '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); } } catch (e) { console.error(e); alert(e.message || 'Failed to save sequence.'); } } 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 = Array.isArray(tabData.sequence_ids) ? tabData.sequence_ids.map(String) : []; const alist = Array.isArray(tabData.animation_ids) ? tabData.animation_ids.map(String) : []; const sid = String(idToDelete); if (list.includes(sid) || alist.includes(sid)) { tabData.sequence_ids = list.filter((x) => x !== sid); tabData.animation_ids = alist.filter((x) => x !== sid); 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 = '

Loading…

'; 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 = '

No sequences yet.

'; 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 anim = doc.kind === 'animation'; title.textContent = `${anim ? '⚡ ' : ''}${doc.name || id} — ${anim ? 'animation, ' : ''}${nLanes} lane(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.fireAnimation = fireAnimation; 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'); const addAnimBtn = document.getElementById('animation-add-btn'); if (addAnimBtn) { addAnimBtn.addEventListener('click', () => { sequenceEditorId = null; seqEditorNewKind = 'animation'; openSequenceEditor(null, null); }); } 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; seqEditorNewKind = 'sequence'; 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 edAddLane = document.getElementById('sequence-editor-add-lane-btn'); if (edAddLane) { edAddLane.addEventListener('click', async () => { const host = document.getElementById('sequence-editor-lanes'); if (!host) return; const presetsRes = await fetch('/presets', { headers: { Accept: 'application/json' } }); const presetsMap = presetsRes.ok ? await presetsRes.json() : {}; const groupsMap = await fetchGroupsMapSeq(); const idx = host.querySelectorAll('.sequence-lane').length; if (idx >= LANES_MAX_UI) { alert(`A sequence can have up to ${LANES_MAX_UI} lanes.`); return; } seqEd.presetsMap = presetsMap; host.appendChild(renderSequenceLane(idx, [], [], presetsMap, groupsMap, seqEd.zoneGroupIds, {})); refreshSequenceEditorLaneTitles(); applySequenceEditorMode(); }); } const edMode = document.getElementById('sequence-editor-mode'); if (edMode) edMode.addEventListener('change', applySequenceEditorMode); const edKind = document.getElementById('sequence-editor-kind'); if (edKind) { edKind.addEventListener('change', () => { const loopCb = document.getElementById('sequence-editor-loop'); if (loopCb) loopCb.checked = edKind.value !== 'animation'; applySequenceKindUi(); }); } const addTarget = document.getElementById('sequence-editor-add-target-btn'); if (addTarget) { addTarget.addEventListener('click', () => { if (addSeqTarget({})) renderTargetsPanel(); }); } const perDriver = document.getElementById('sequence-editor-per-driver-btn'); if (perDriver) perDriver.addEventListener('click', addTargetsPerDriver); const viewBtn = document.getElementById('sequence-editor-view-btn'); if (viewBtn) { viewBtn.addEventListener('click', () => { const g = document.getElementById('sequence-editor-grid'); setSequenceEditorView(!!g && g.hidden); }); } const tryBtn = document.getElementById('sequence-editor-try-btn'); if (tryBtn) { tryBtn.addEventListener('click', async () => { if (!sequenceEditorId) return; await saveSequenceEditor(); const zid = resolveZoneIdForPresetStripRefresh(); const kind = document.getElementById('sequence-editor-kind'); try { if (kind && kind.value === 'animation') await fireAnimation(sequenceEditorId, zid); else await requestBackendSequencePlay(sequenceEditorId, zid, null); } catch (e) { alert(e.message || 'Could not play it.'); } }); } });