// Sequences: timed preset chains per zone, run by the Pi-side engine. const SEQUENCES_POLL_MS = 1000; let sequencesPollTimer = null; async function fetchJson(url) { const res = await fetch(url, { headers: { Accept: 'application/json' }, credentials: 'same-origin' }); if (!res.ok) throw new Error(`${url}: ${res.status}`); return res.json(); } async function loadSequenceContext() { const [sequences, status, zonesData, presets] = await Promise.all([ fetchJson('/sequences'), fetchJson('/sequences/status'), fetchJson('/zones'), fetchJson('/presets'), ]); const order = Array.isArray(zonesData.zone_order) ? zonesData.zone_order : []; const zones = {}; order.forEach((zid) => { if (zonesData.zones && zonesData.zones[zid]) zones[zid] = zonesData.zones[zid]; }); return { sequences, status, zones, presets }; } function stepSummary(seq, presets, state) { const steps = seq.steps || []; const total = steps.reduce((s, st) => s + Number(st.duration_s || 0), 0); let text = `${steps.length} step${steps.length === 1 ? '' : 's'} · ${total.toFixed(1)} s`; text += seq.loop ? (seq.repeat_count ? ` · ×${seq.repeat_count}` : ' · loop') : ' · once'; if (state && state.running) { const p = presets[state.preset_id]; text += ` · ▶ step ${state.step_index + 1}${p ? ` (${p.name})` : ''}`; } return text; } function renderSequencesList(ctx) { const container = document.getElementById('sequences-list-modal'); if (!container) return; const editMode = typeof isEditModeActive === 'function' && isEditModeActive(); container.innerHTML = ''; const ids = Object.keys(ctx.sequences || {}).filter((id) => { const z = ctx.sequences[id].zone_id; return z == null || ctx.zones[z]; // only this profile's zones (plus unassigned) }); if (ids.length === 0) { const p = document.createElement('p'); p.className = 'muted-text'; p.textContent = 'No sequences yet.'; container.appendChild(p); return; } ids.forEach((id) => { const seq = ctx.sequences[id]; const state = ctx.status[id]; const running = !!(state && state.running); const zone = ctx.zones[seq.zone_id]; const row = document.createElement('div'); row.className = 'profiles-row'; row.style.display = 'flex'; row.style.alignItems = 'center'; row.style.gap = '0.5rem'; row.style.flexWrap = 'wrap'; const label = document.createElement('span'); label.style.flex = '1'; const name = document.createElement('strong'); name.textContent = seq.name || `Sequence ${id}`; const meta = document.createElement('span'); meta.className = 'muted-text'; meta.textContent = ` ${zone ? zone.name : 'no zone'} · ${stepSummary(seq, ctx.presets, state)}`; label.append(name, meta); const playBtn = document.createElement('button'); playBtn.type = 'button'; playBtn.className = running ? 'btn btn-danger btn-small' : 'btn btn-primary btn-small'; playBtn.textContent = running ? 'Stop' : 'Play'; playBtn.disabled = !zone || !(seq.steps || []).length; playBtn.addEventListener('click', async () => { playBtn.disabled = true; const res = await fetch(`/sequences/${encodeURIComponent(id)}/${running ? 'stop' : 'play'}`, { method: 'POST', credentials: 'same-origin', }); if (!res.ok) { const data = await res.json().catch(() => ({})); alert(data.error || 'Failed'); } refreshSequencesList(); }); row.append(label, playBtn); if (editMode) { const editBtn = document.createElement('button'); editBtn.type = 'button'; editBtn.className = 'btn btn-secondary btn-small'; editBtn.textContent = 'Edit'; editBtn.addEventListener('click', () => openSequenceEditor(id, seq, ctx)); const delBtn = document.createElement('button'); delBtn.type = 'button'; delBtn.className = 'btn btn-danger btn-small'; delBtn.textContent = 'Delete'; delBtn.addEventListener('click', async () => { if (!confirm(`Delete sequence "${seq.name}"?`)) return; await fetch(`/sequences/${encodeURIComponent(id)}`, { method: 'DELETE' }); refreshSequencesList(); }); row.append(editBtn, delBtn); } container.appendChild(row); }); } let lastSequenceCtx = null; async function refreshSequencesList() { try { lastSequenceCtx = await loadSequenceContext(); renderSequencesList(lastSequenceCtx); } catch (e) { const container = document.getElementById('sequences-list-modal'); if (container && !lastSequenceCtx) container.textContent = 'Failed to load sequences.'; } } function stopSequencesPoll() { if (sequencesPollTimer != null) { clearInterval(sequencesPollTimer); sequencesPollTimer = null; } } function addStepRow(presets, step) { const container = document.getElementById('edit-sequence-steps'); const row = document.createElement('div'); row.className = 'engine-step-row'; const select = document.createElement('select'); select.className = 'engine-step-preset'; Object.entries(presets || {}).forEach(([pid, p]) => { const opt = document.createElement('option'); opt.value = pid; opt.textContent = p.name || pid; select.appendChild(opt); }); if (step && step.preset_id != null) select.value = String(step.preset_id); const dur = document.createElement('input'); dur.type = 'number'; dur.min = '0.5'; dur.max = '600'; dur.step = '0.5'; dur.className = 'engine-step-duration'; dur.value = step && step.duration_s != null ? step.duration_s : 5; dur.title = 'Seconds'; const unit = document.createElement('span'); unit.className = 'muted-text'; unit.textContent = 's'; const mk = (text, title, fn) => { const b = document.createElement('button'); b.type = 'button'; b.className = 'btn btn-secondary btn-small'; b.textContent = text; b.title = title; b.addEventListener('click', fn); return b; }; const up = mk('↑', 'Move up', () => { if (row.previousElementSibling) container.insertBefore(row, row.previousElementSibling); }); const down = mk('↓', 'Move down', () => { if (row.nextElementSibling) container.insertBefore(row.nextElementSibling, row); }); const del = mk('✕', 'Remove step', () => row.remove()); row.append(select, dur, unit, up, down, del); container.appendChild(row); } function openSequenceEditor(id, seq, ctx) { const s = seq || { name: '', zone_id: null, loop: true, repeat_count: 0, steps: [] }; document.getElementById('edit-sequence-title').textContent = id ? 'Edit sequence' : 'New sequence'; document.getElementById('edit-sequence-id').value = id || ''; document.getElementById('edit-sequence-name').value = s.name || ''; const zoneSel = document.getElementById('edit-sequence-zone'); zoneSel.innerHTML = ''; Object.entries(ctx.zones).forEach(([zid, z]) => { const opt = document.createElement('option'); opt.value = zid; opt.textContent = z.name || zid; zoneSel.appendChild(opt); }); const currentZone = s.zone_id || (window.zonesManager && window.zonesManager.getCurrentZoneId && window.zonesManager.getCurrentZoneId()); if (currentZone && ctx.zones[currentZone]) zoneSel.value = String(currentZone); document.getElementById('edit-sequence-loop').checked = s.loop !== false; document.getElementById('edit-sequence-repeat').value = s.repeat_count || 0; const steps = document.getElementById('edit-sequence-steps'); steps.innerHTML = ''; (s.steps || []).forEach((st) => addStepRow(ctx.presets, st)); if (!(s.steps || []).length) addStepRow(ctx.presets, null); document.getElementById('edit-sequence-error').hidden = true; document.getElementById('edit-sequence-modal').classList.add('active'); } function readSequenceForm() { const steps = []; document.querySelectorAll('#edit-sequence-steps .engine-step-row').forEach((row) => { const pid = row.querySelector('.engine-step-preset').value; const dur = Number(row.querySelector('.engine-step-duration').value); if (pid) steps.push({ preset_id: pid, duration_s: Number.isFinite(dur) ? dur : 5 }); }); return { name: document.getElementById('edit-sequence-name').value.trim(), zone_id: document.getElementById('edit-sequence-zone').value || null, loop: document.getElementById('edit-sequence-loop').checked, repeat_count: Number(document.getElementById('edit-sequence-repeat').value) || 0, steps, }; } // Tell the engine a preset was picked on a zone: renders it on the zone's pixel // outputs and stops any sequence there. ESP32s were already sent the preset // by presets.js, so the engine leaves them alone (drivers: false). async function notifyEngineZonePlay(zoneId, presetId) { if (!zoneId || !presetId) return; try { await fetch(`/zones/${encodeURIComponent(zoneId)}/play`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ preset_id: String(presetId), drivers: false }), }); } catch (e) { console.warn('Engine zone play failed:', e); } } window.notifyEngineZonePlay = notifyEngineZonePlay; document.addEventListener('DOMContentLoaded', () => { const btn = document.getElementById('sequences-btn'); const modal = document.getElementById('sequences-modal'); const editModal = document.getElementById('edit-sequence-modal'); const form = document.getElementById('edit-sequence-form'); if (!btn || !modal || !form) return; btn.addEventListener('click', () => { modal.classList.add('active'); refreshSequencesList(); stopSequencesPoll(); sequencesPollTimer = setInterval(refreshSequencesList, SEQUENCES_POLL_MS); }); document.getElementById('sequences-close-btn').addEventListener('click', () => { modal.classList.remove('active'); }); new MutationObserver(() => { if (!modal.classList.contains('active')) stopSequencesPoll(); }).observe(modal, { attributes: true, attributeFilter: ['class'] }); document.getElementById('sequence-add-btn').addEventListener('click', async () => { const ctx = lastSequenceCtx || await loadSequenceContext(); openSequenceEditor(null, null, ctx); }); document.getElementById('edit-sequence-add-step-btn').addEventListener('click', () => { addStepRow((lastSequenceCtx && lastSequenceCtx.presets) || {}, null); }); document.getElementById('edit-sequence-close-btn').addEventListener('click', () => { editModal.classList.remove('active'); }); form.addEventListener('submit', async (e) => { e.preventDefault(); const id = document.getElementById('edit-sequence-id').value; const err = document.getElementById('edit-sequence-error'); err.hidden = true; const body = readSequenceForm(); if (!body.steps.length) { err.textContent = 'Add at least one step.'; err.hidden = false; return; } const res = await fetch(id ? `/sequences/${encodeURIComponent(id)}` : '/sequences', { method: id ? 'PUT' : 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify(body), }); const data = await res.json().catch(() => ({})); if (!res.ok) { err.textContent = data.error || 'Save failed'; err.hidden = false; return; } editModal.classList.remove('active'); refreshSequencesList(); }); });