Files
led-controller/web/static/seq_timeline.js
T
jimmyandClaude Haiku 5.5 02440be55d feat: sequence editor undo/redo, collapsible browser, playhead easing
Sequence editor: undo and redo, a collapsible browser with chips, search
over sequences too, name in the header row, Beats/Seconds dropdown, Delete
beside Save. Playhead eases between poll results. Lanes keep their phase
when a step ends late, so they no longer drift. The rig's default room is
two columns of bars facing each other, and the simulator has a read-only
debug hook for the playback checks.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-17 00:28:59 +13:00

1489 lines
53 KiB
JavaScript

/* Timeline editor for sequences (looping, or one-shot with Loop off), laid out like a DAW arrangement: each target (a
* group, or some drivers) is a track, time runs left to right in beats (or seconds), and clips are
* the presets or one-shot sequences a track plays. It saves as one lane per track (tlToLanes): the gaps
* become rest steps, and with Loop on every lane is padded to the loop end so the tracks stay in
* step on every pass (lanes wrap on their own in the player). Older sequences made with lane options
* (chase, speed, per-step targets) open as one pass of what they played (tlFlatten).
* Uses seqEd, sequenceEditorId and the helpers in sequences.js.
*/
const TL_BAR = 4;
const TL_TRACKS_MAX = 16; // one lane per track
const TL_STEPS_MAX = 64; // per lane, rests included (STEPS_MAX in main/seqplay.c)
const TL_COLORS = ['#e8645a', '#f0a13c', '#d9c443', '#6cc66c', '#4fb7c9', '#5a8de8', '#9b6be8', '#e468b8'];
const TL_EPS = 1e-6;
const seqTl = {
on: false, // the editor is open
clips: [], // {id, uid, start, len, play}; play is p:<preset> or a:<one-shot sequence> (saved as animation_id)
nextId: 1,
sel: null, // {clip: id} or {track: uid}
ppb: 40, // pixels per beat (or second)
snap: 1,
snapAuto: true, // the Snap menu's Auto: follows the zoom
loopEnd: 0,
loopEndSet: false, // the user moved the end marker
brush: '', // the browser item double-click adds
lastLen: TL_BAR,
head: null, // playhead {pos, at, rate, max, wrap}
headErr: 0, // the playhead's easing offset after a status poll: glides to the server's position instead of jumping
headErrT: 0,
pollTimer: null,
raf: 0,
drag: null,
hoverX: null, // the pointer's last x over the timeline: where the zoom buttons zoom around
};
/* ------------------------------------------------------------------ basics */
const tlEl = (id) => document.getElementById(id);
const tlR = (x) => Math.round(x * 1000) / 1000;
function tlTimed() {
const m = tlEl('sequence-editor-mode');
return !!m && m.value === 'time';
}
function tlLoop() {
const l = tlEl('sequence-editor-loop');
return !!l && l.checked;
}
function tlBpm() {
const live = parseFloat((tlEl('audio-top-bpm-value') || {}).textContent || '');
if (Number.isFinite(live) && live > 0) return live;
return parseFloat((tlEl('audio-simulated-bpm') || {}).value || '120') || 120;
}
function tlMin() {
return tlTimed() ? 0.05 : 0.25;
}
function tlSnapOptions() {
return tlTimed()
? [['1', '1 s'], ['0.5', '½ s'], ['0.25', '¼ s'], ['0.1', '0.1 s'], ['0.05', '0.05 s']]
: [['4', 'Bar'], ['1', 'Beat'], ['0.5', '½ beat'], ['0.25', '¼ beat']];
}
/** Snap to the grid; `floor` for drops so a clip lands in the cell under the pointer. */
function tlQ(x, floor) {
const s = seqTl.snap || 1;
const n = floor ? Math.floor(x / s + TL_EPS) : Math.round(x / s);
return tlR(Math.max(0, n * s));
}
function tlClip(id) {
return seqTl.clips.find((c) => c.id === id) || null;
}
function tlClipsOn(uid) {
return seqTl.clips.filter((c) => c.uid === uid).sort((a, b) => a.start - b.start);
}
function tlTrack(uid) {
return seqEd.targets.find((t) => t.uid === uid) || null;
}
function tlEnd() {
return seqTl.clips.reduce((m, c) => Math.max(m, c.start + c.len), 0);
}
/** The sequence's window: its length, set by the end marker. Clips never change it; the ones past it are cut on save. */
function tlLoopLen() {
return Math.max(tlMin(), seqTl.loopEnd);
}
/** The window the record has, in the editor's units; 0 for records saved before windows. */
function tlWindowOf(doc) {
if (!doc) return 0;
const v = tlTimed() ? doc.window_seconds : doc.window_beats;
return typeof v === 'number' && v > 0 ? tlR(v) : 0;
}
/** The window in both units, as saved: the player and older clients read whichever they use. */
function tlWindowFields() {
const w = tlLoopLen();
const beatS = 60 / tlBpm();
return tlTimed()
? { window_beats: tlR(w / beatS), window_seconds: tlR(w) }
: { window_beats: tlR(w), window_seconds: tlR(w * beatS) };
}
/** True when [start, start+len) is free on the track (ignoring one clip, the one being moved). */
function tlFits(uid, start, len, ignoreId) {
if (start < -TL_EPS || len < tlMin() - TL_EPS || start + len > tlLoopLen() + TL_EPS) return false;
return !seqTl.clips.some(
(c) => c.uid === uid && c.id !== ignoreId && start < c.start + c.len - TL_EPS && c.start < start + len - TL_EPS,
);
}
/** The free space on a track around `at`: {from, to}, or null when `at` is inside a clip. */
function tlGap(uid, at, ignoreId) {
let from = 0;
let to = Infinity;
for (const c of tlClipsOn(uid)) {
if (c.id === ignoreId) continue;
if (at >= c.start - TL_EPS && at < c.start + c.len - TL_EPS) return null;
if (c.start + c.len <= at + TL_EPS) from = Math.max(from, c.start + c.len);
else to = Math.min(to, c.start);
}
return { from, to };
}
function tlPlayInfo(play) {
const id = String(play || '').slice(2);
if (String(play).startsWith('a:')) {
const a = seqEd.seqMap[id];
return { name: `⚡ ${(a && a.name) || id}`, colors: [], anim: true, id };
}
const p = seqEd.presetsMap[id];
const colors = p && Array.isArray(p.colors) ? p.colors.filter((c) => typeof c === 'string' && c) : [];
return { name: (p && p.name) || id || '?', colors, anim: false, id };
}
/** CSS fill for a clip or browser swatch: the preset's colours left to right. */
function tlFill(info) {
if (info.anim) return '';
const c = info.colors.length ? info.colors : ['#777'];
return c.length === 1 ? c[0] : `linear-gradient(90deg, ${c.join(', ')})`;
}
/** How long a sequence runs once, in the editor's current units. */
function tlSeqLen(doc) {
if (!doc) return TL_BAR;
const win = tlWindowOf(doc);
if (win) return win;
const timed = tlTimed();
const beatS = 60 / tlBpm();
const lanes = normalizeSequenceLanes(doc);
const lo = Array.isArray(doc.lane_opts) ? doc.lane_opts : [];
let best = 0;
lanes.forEach((l, i) => {
const o = lo[i] || {};
const lt = seqIsOneShot(doc) || (o.mode ? o.mode === 'time' : doc.advance_mode === 'time');
const rate = parseFloat(o.rate) || 1;
let t = parseFloat(o.offset) || 0;
l.forEach((s) => {
t += (lt ? s.seconds : s.beats) / rate;
});
best = Math.max(best, lt === timed ? t : lt ? t / beatS : t * beatS);
});
return best > 0 ? tlR(best) : TL_BAR;
}
function tlTrackColor(i) {
return TL_COLORS[i % TL_COLORS.length];
}
function tlTrackSummary(t) {
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';
}
/* --------------------------------------------------------- lanes ↔ clips */
/**
* Lanes (normalizeSequenceLanes form) onto tracks, walking each lane the way the player does
* (step targets, else the chase, else the lane's targets). Works on a copy of the targets; older
* records with no targets get them from their lane groups or the zone. Returns the clips, the
* targets, the loop length, and what the timeline could not keep.
*/
function tlFlatten(doc, lanes, laneOpts) {
const timed = tlTimed();
const beatS = 60 / tlBpm();
const targets = seqEd.targets.slice();
const lossy = new Set();
const clips = [];
const lens = [];
const legacyTarget = (li, steps) => {
let gids = groupIdsForLaneStep(doc, steps[0], li, lanes.length);
if (!gids.length) gids = seqEd.zoneGroupIds.slice();
const key = gids.slice().sort().join(',');
let ix = targets.findIndex((t) => !t.devices.length && t.group_ids.slice().sort().join(',') === key);
if (ix < 0) {
const name = gids.length ? gids.map((g) => (seqEd.groupsMap[g] && seqEd.groupsMap[g].name) || g).join(' + ') : 'Zone';
targets.push({ uid: seqEd.nextUid++, name, group_ids: gids, devices: [] });
ix = targets.length - 1;
}
return [ix];
};
lanes.forEach((steps, li) => {
if (!steps.length) return;
const o = laneOpts[li] || {};
let order = Array.isArray(o.targets) ? o.targets.map((x) => parseInt(x, 10)).filter((i) => targets[i]) : [];
if (!order.length) order = legacyTarget(li, steps);
const lt = o.mode ? o.mode === 'time' : timed;
if (o.mode && lt !== timed) lossy.add('lane timing');
const conv = (v) => (lt === timed ? v : lt ? v / beatS : v * beatS);
const rate = parseFloat(o.rate) || 1;
if (rate !== 1) lossy.add('lane speed');
const offset = conv(parseFloat(o.offset) || 0);
if (offset > 0 && tlLoop()) lossy.add('lane start offset');
const n = order.length;
const chase = o.chase && typeof o.chase === 'object' && n > 1 ? o.chase : null;
if (chase) lossy.add('chase');
const width = chase ? Math.min(n, Math.max(1, parseInt(chase.width, 10) || 1)) : 0;
let pos = chase && chase.order === 'reverse' ? n - 1 : 0;
let dir = 1;
let t = offset;
steps.forEach((st) => {
let len = conv(lt ? st.seconds : st.beats) / rate;
if (st.animation_id && st.length === 'animation') len = tlSeqLen(seqEd.seqMap[st.animation_id]);
if (st.others) lossy.add('others off');
let lit;
if (st.targets && st.targets.length) {
lit = st.targets.filter((i) => targets[i]);
lossy.add('step targets');
} else if (chase) {
lit = [];
for (let k = 0; k < width; k++) lit.push(order[(pos + k) % n]);
} else {
lit = order;
}
const play = st.animation_id ? `a:${st.animation_id}` : st.preset_id ? `p:${st.preset_id}` : '';
if (!st.rest && play) {
lit.forEach((ti) => clips.push({ uid: targets[ti].uid, start: tlR(t), len: tlR(len), play, lane: li }));
}
t += len;
if (chase) {
if (chase.order === 'reverse') pos = (pos + n - 1) % n;
else if (chase.order === 'bounce') {
if (pos + dir < 0 || pos + dir >= n) dir = -dir;
pos += dir;
} else pos = (pos + 1) % n;
}
});
lens.push(tlR(t));
});
if (tlLoop() && new Set(lens).size > 1) lossy.add('lanes of different lengths');
// Two lanes on one track: the later lane wins; the earlier clip is cut short or dropped
const out = [];
clips.forEach((c) => {
for (let i = out.length - 1; i >= 0; i--) {
const e = out[i];
if (e.uid !== c.uid || e.lane === c.lane) continue;
if (e.start < c.start + c.len - TL_EPS && c.start < e.start + e.len - TL_EPS) {
lossy.add('overlapping lanes');
if (e.start < c.start - TL_EPS) e.len = tlR(c.start - e.start);
else out.splice(i, 1);
}
}
out.push(c);
});
return {
clips: out.map(({ lane, ...c }) => c),
targets,
total: lens.length ? Math.max(...lens) : 0,
lossy: [...lossy],
};
}
function tlCommit(r) {
seqEd.targets = r.targets;
seqTl.clips = r.clips.map((c) => ({ ...c, id: seqTl.nextId++ }));
seqTl.sel = null;
const auto = Math.max(TL_BAR, Math.ceil(tlEnd() / TL_BAR - TL_EPS) * TL_BAR);
seqTl.loopEnd = r.total > tlEnd() + TL_EPS ? r.total : auto;
seqTl.loopEndSet = Math.abs(seqTl.loopEnd - auto) > TL_EPS;
}
/** The timeline as saved lanes: one per track with clips, gaps as rests, padded to the loop end. */
function tlToLanes() {
const timed = tlTimed();
const beatS = 60 / tlBpm();
const total = tlLoopLen(); // every lane runs the whole window, padded with rests
const lanes = [];
const lane_opts = [];
const lanes_group_ids = [];
const map = [];
const len = (v) =>
timed ? { seconds: tlR(Math.max(0.05, v)), beats: tlR(Math.max(0.25, v / beatS)) } : { beats: tlR(Math.max(0.25, v)), seconds: tlR(Math.max(0.05, v * beatS)) };
seqEd.targets.forEach((t, ti) => {
const cs = tlClipsOn(t.uid);
if (!cs.length) return;
const steps = [];
const starts = [];
let at = 0;
cs.forEach((c) => {
const cl = tlR(Math.min(c.len, total - c.start)); // cut at the window's end
if (cl <= TL_EPS) return;
if (c.start > at + TL_EPS) {
steps.push({ preset_id: '', rest: true, ...len(c.start - at) });
starts.push(at);
}
const st = c.play.startsWith('a:') ? { animation_id: c.play.slice(2) } : { preset_id: c.play.slice(2) };
steps.push({ ...st, ...len(cl) });
starts.push(c.start);
at = c.start + cl;
});
if (total > at + TL_EPS) {
steps.push({ preset_id: '', rest: true, ...len(total - at) });
starts.push(at);
}
lanes.push(steps);
lane_opts.push({ targets: [ti] });
lanes_group_ids.push([...t.group_ids]);
map.push({ uid: t.uid, starts, ends: starts.map((s, i) => (i + 1 < starts.length ? starts[i + 1] : Math.max(at, total))) });
});
return { lanes, lane_opts, lanes_group_ids, map };
}
/** Why the timeline can't be saved as it is, or '' when it can. */
function tlSaveProblem() {
const { lanes } = tlToLanes();
if (!lanes.length) return 'Drag a preset onto a track first.';
if (lanes.length > TL_TRACKS_MAX) return `At most ${TL_TRACKS_MAX} tracks can have clips.`;
if (lanes.some((l) => l.length > TL_STEPS_MAX)) return `A track can hold up to ${TL_STEPS_MAX} clips and gaps.`;
return '';
}
/* -------------------------------------------------------------------- open */
/** Called by openSequenceEditor with the sequence (or {} for a new one). */
function seqTlOnOpen(doc) {
seqTl.drag = null;
seqTl.head = null;
seqTl.clips = [];
seqTl.sel = null;
seqTl.loopEndSet = false;
try {
seqTl.ppb = Math.min(TL_PPB_MAX, Math.max(TL_PPB_MIN, parseFloat(localStorage.getItem('seqTlZoom') || '40') || 40));
} catch (_) {
seqTl.ppb = 40;
}
tlBuildSnap();
const lanes = normalizeSequenceLanes(doc || {});
const r = tlFlatten(doc || {}, lanes, Array.isArray(doc && doc.lane_opts) ? doc.lane_opts : []);
tlCommit(r);
const win = tlWindowOf(doc);
if (win) seqTl.loopEnd = win; // the saved window, not the clips' end
// Older sequences can use lane options the timeline doesn't have; it shows their first pass
tlNotice(
r.lossy.length
? `This was made with lane options the timeline doesn't have (${r.lossy.join(', ')}). It shows one pass of it; saving keeps what you see here.`
: '',
);
seqTl.on = true;
tlHist.undo = [];
tlHist.redo = [];
tlHist.cur = null; // the first render records the opened state
tlRender();
tlStartPoll();
}
function tlNotice(text) {
const n = tlEl('tl-notice');
if (!n) return;
n.textContent = text;
n.hidden = !text;
}
/* ------------------------------------------------------------------ render */
function tlHeadWidth() {
const h = document.querySelector('#tl-canvas .tl-head');
return h ? h.offsetWidth : 0;
}
/** Auto snap: the finest step the ruler shows at this zoom (never coarser than 1 beat or second). */
function tlAutoSnap() {
const steps = tlTimed() ? [0.05, 0.1, 0.25, 0.5, 1] : [0.25, 0.5, 1];
return steps.find((s) => s * seqTl.ppb >= 36) || 1;
}
function tlBuildSnap() {
const sel = tlEl('tl-snap');
if (!sel) return;
const opts = [['auto', 'Auto (zoom)'], ...tlSnapOptions()];
const was = String(seqTl.snap);
sel.innerHTML = '';
opts.forEach(([v, t]) => sel.appendChild(new Option(t, v)));
if (seqTl.snapAuto) {
sel.value = 'auto';
seqTl.snap = tlAutoSnap();
} else {
sel.value = opts.some(([v]) => v === was) ? was : tlTimed() ? '0.5' : '1';
seqTl.snap = parseFloat(sel.value);
}
}
/** Select a clip or track without rebuilding the tracks (so double-clicks still land). */
function tlSelect(sel) {
seqTl.sel = sel;
document.querySelectorAll('#tl-canvas .tl-clip').forEach((el) => el.classList.toggle('sel', !!sel && sel.clip === parseInt(el.dataset.id, 10)));
document.querySelectorAll('#tl-canvas .tl-track .tl-head').forEach((el) => el.classList.toggle('sel', !!sel && sel.track === parseInt(el.dataset.uid, 10)));
tlRenderInspector();
}
function tlRender() {
const canvas = tlEl('tl-canvas');
if (!canvas || !seqTl.on) return;
tlRecord(); // every edit ends in a render: an edit since the last one becomes an undo step
if (seqTl.snapAuto) seqTl.snap = tlAutoSnap(); // Auto follows the zoom, so drags land on the ticks shown
const ppb = seqTl.ppb;
const timed = tlTimed();
const loop = tlLoop();
const loopLen = tlLoopLen();
// The timeline is exactly the window long: nothing past its end is shown or can be placed
const units = loopLen;
const W = units * ppb;
canvas.style.setProperty('--ppb', String(ppb));
canvas.innerHTML = '';
// A one-shot is always in seconds: Beats is greyed out while Loop is off
const beatsOpt = document.querySelector('#sequence-editor-mode option[value="beats"]');
if (beatsOpt) beatsOpt.disabled = !loop;
// Ruler
const rrow = document.createElement('div');
rrow.className = 'tl-row tl-ruler-row';
const corner = document.createElement('div');
corner.className = 'tl-head tl-corner';
corner.textContent = timed ? 'Seconds' : 'Bars';
const ruler = document.createElement('div');
ruler.className = 'tl-ruler';
ruler.style.width = `${W}px`;
// Zoomed out: whole seconds, then every 5/10/30. Zoomed in: the finest step that keeps ~36px between ticks,
// down to a tenth of a second or a quarter of a beat.
let every = timed ? (ppb >= 30 ? 1 : ppb >= 12 ? 5 : ppb >= 5 ? 10 : 30) : 1;
if (ppb >= 30) {
const fine = timed ? [0.05, 0.1, 0.25, 0.5, 1] : [0.25, 0.5, 1];
every = fine.find((s) => s * ppb >= 36) || 1;
}
const barsPerLabel = ppb * TL_BAR >= 28 ? 1 : ppb * TL_BAR >= 14 ? 2 : 4; // zoomed far out
const FRAC = { 0.25: '¼', 0.5: '½', 0.75: '¾' };
const n = Math.floor(units / every + TL_EPS);
for (let i = 0; i <= n; i++) {
const u = tlR(i * every);
const bar = !timed && Number.isInteger(u) && u % (TL_BAR * barsPerLabel) === 0;
const major = timed || bar;
if (!major && ppb < 18) continue;
const tick = document.createElement('span');
tick.className = `tl-tick${major ? ' major' : ''}`;
tick.style.left = `${u * ppb}px`;
if (timed) tick.textContent = `${u}s`;
else if (bar) tick.textContent = String(u / TL_BAR + 1);
else if (ppb >= 44) {
const beat = Math.floor(u % TL_BAR + TL_EPS);
const frac = tlR(u - Math.floor(u / TL_BAR + TL_EPS) * TL_BAR - beat);
tick.textContent = `${Math.floor(u / TL_BAR + TL_EPS) + 1}.${beat + 1}${FRAC[frac] || ''}`;
}
ruler.appendChild(tick);
}
if (loop) {
const brace = document.createElement('div');
brace.className = 'tl-loop';
brace.style.width = `${loopLen * ppb}px`;
brace.title = 'Loop: every track restarts here. Drag the end to change it.';
const end = document.createElement('div');
end.className = 'tl-loop-end';
end.title = 'Drag to set where the loop restarts';
end.addEventListener('pointerdown', (e) => tlStartDrag(e, { kind: 'loop' }));
brace.appendChild(end);
ruler.appendChild(brace);
}
ruler.addEventListener('pointerdown', () => tlSelect(null));
rrow.appendChild(corner);
rrow.appendChild(ruler);
canvas.appendChild(rrow);
// Tracks
seqEd.targets.forEach((t, i) => {
const row = document.createElement('div');
row.className = 'tl-row tl-track';
const head = document.createElement('div');
head.className = 'tl-head';
head.style.setProperty('--track-color', tlTrackColor(i));
if (seqTl.sel && seqTl.sel.track === t.uid) head.classList.add('sel');
const nm = document.createElement('div');
nm.className = 'tl-head-name';
nm.textContent = seqEdTargetLabel(t, i);
const sum = document.createElement('div');
sum.className = 'tl-head-sum';
sum.textContent = tlTrackSummary(t);
head.title = `${seqEdTargetLabel(t, i)}: ${tlTrackSummary(t)}`;
head.appendChild(nm);
head.appendChild(sum);
if (t.group_ids.length && typeof identifyGroupById === 'function') {
const id = document.createElement('button');
id.type = 'button';
id.className = 'tl-head-btn';
id.textContent = '◉';
id.title = 'Identify: flash this track\'s groups';
id.addEventListener('click', (e) => {
e.stopPropagation();
t.group_ids.forEach((g) => identifyGroupById(g));
});
head.appendChild(id);
}
head.dataset.uid = String(t.uid);
head.addEventListener('click', () => tlSelect({ track: t.uid }));
const lane = document.createElement('div');
lane.className = 'tl-lane';
lane.dataset.uid = String(t.uid);
lane.style.width = `${W}px`;
lane.addEventListener('pointerdown', (e) => {
if (e.target === lane && seqTl.sel) tlSelect(null);
});
lane.addEventListener('dblclick', (e) => {
if (e.target !== lane) return;
tlAddAt(t.uid, tlQ(tlLaneX(lane, e.clientX) / seqTl.ppb, true), seqTl.brush);
});
tlClipsOn(t.uid).forEach((c) => {
if (c.start < loopLen - TL_EPS) lane.appendChild(tlClipEl(c));
});
row.appendChild(head);
row.appendChild(lane);
canvas.appendChild(row);
});
if (!seqEd.targets.length) {
const empty = document.createElement('div');
empty.className = 'tl-empty muted-text';
empty.textContent = 'No tracks yet. Add one per group below, then drag presets onto them.';
canvas.appendChild(empty);
}
if (loop && seqEd.targets.length) {
const endLine = document.createElement('div');
endLine.className = 'tl-endline';
endLine.style.left = `calc(var(--tl-head-w) + ${loopLen * ppb}px)`;
canvas.appendChild(endLine);
}
const ph = document.createElement('div');
ph.className = 'tl-playhead';
ph.id = 'tl-playhead';
ph.hidden = !seqTl.head;
canvas.appendChild(ph);
tlRenderAddTrack();
tlRenderBrowser();
tlRenderInspector();
tlDrawHead();
}
function tlClipEl(c) {
const info = tlPlayInfo(c.play);
const el = document.createElement('div');
el.className = `tl-clip${info.anim ? ' anim' : ''}${seqTl.sel && seqTl.sel.clip === c.id ? ' sel' : ''}`;
el.dataset.id = String(c.id);
el.style.left = `${c.start * seqTl.ppb}px`;
// A clip reaching past the window is drawn up to its end
el.style.width = `${Math.min(c.len, tlLoopLen() - c.start) * seqTl.ppb}px`;
const fill = tlFill(info);
if (fill) el.style.setProperty('--clip-fill', fill);
el.title = `${info.name} — ${c.len}${tlTimed() ? ' s' : ' beat(s)'}`;
const lab = document.createElement('span');
lab.className = 'tl-clip-name';
lab.textContent = info.name;
el.appendChild(lab);
const l = document.createElement('span');
l.className = 'tl-clip-edge l';
const r = document.createElement('span');
r.className = 'tl-clip-edge r';
el.appendChild(l);
el.appendChild(r);
el.addEventListener('pointerdown', (e) => {
const kind = e.target === l ? 'left' : e.target === r ? 'right' : 'move';
tlStartDrag(e, { kind, id: c.id, start0: c.start, len0: c.len, uid0: c.uid, el });
});
el.addEventListener('dblclick', (e) => {
e.stopPropagation();
tlEditPlay(c.play);
});
return el;
}
function tlRenderAddTrack() {
const sel = tlEl('tl-add-track');
if (!sel) return;
sel.innerHTML = '';
sel.appendChild(new Option('+ Add track…', ''));
const byName = (map) => (a, b) => String((map[a] || {}).name || a).localeCompare(String((map[b] || {}).name || b), undefined, { numeric: true });
const gg = document.createElement('optgroup');
gg.label = 'Groups';
Object.keys(seqEd.groupsMap)
.sort(byName(seqEd.groupsMap))
.forEach((g) => gg.appendChild(new Option((seqEd.groupsMap[g] && seqEd.groupsMap[g].name) || g, `g:${g}`)));
if (gg.children.length) sel.appendChild(gg);
const dg = document.createElement('optgroup');
dg.label = 'Single drivers';
Object.keys(seqEd.devicesMap)
.sort(byName(seqEd.devicesMap))
.forEach((m) => dg.appendChild(new Option((seqEd.devicesMap[m] && seqEd.devicesMap[m].name) || m, `d:${m}`)));
if (dg.children.length) sel.appendChild(dg);
sel.appendChild(new Option('Empty track (pick later)', 'empty'));
sel.value = '';
}
function tlAddTrack(v) {
if (!v) return;
if (seqEd.targets.length >= TL_TRACKS_MAX) {
alert(`A timeline can have up to ${TL_TRACKS_MAX} tracks.`);
return;
}
let t = {};
if (v.startsWith('g:')) {
const g = v.slice(2);
t = { name: (seqEd.groupsMap[g] && seqEd.groupsMap[g].name) || g, group_ids: [g] };
} else if (v.startsWith('d:')) {
const m = v.slice(2);
t = { name: (seqEd.devicesMap[m] && seqEd.devicesMap[m].name) || m, devices: [m] };
}
if (addSeqTarget(t)) {
seqTl.sel = v === 'empty' ? { track: seqEd.targets[seqEd.targets.length - 1].uid } : seqTl.sel;
tlRender();
}
}
function tlRenderBrowser() {
const list = tlEl('tl-browser-list');
if (!list) return;
const q = String((tlEl('tl-browser-search') || {}).value || '').trim().toLowerCase();
list.innerHTML = '';
const byName = (map) => (a, b) => String((map[a] || {}).name || a).localeCompare(String((map[b] || {}).name || b), undefined, { sensitivity: 'base' });
const section = (title, items) => {
if (!items.length) return;
const h = document.createElement('div');
h.className = 'tl-browser-sec';
h.textContent = title;
list.appendChild(h);
items.forEach((play) => {
const info = tlPlayInfo(play);
const chip = document.createElement('div');
chip.className = `tl-chip${info.anim ? ' anim' : ''}${seqTl.brush === play ? ' on' : ''}`;
chip.dataset.play = play;
chip.title = 'Drag onto a track. Click to pick it for double-click on a track.';
const sw = document.createElement('span');
sw.className = 'tl-chip-sw';
const fill = tlFill(info);
if (fill) sw.style.background = fill;
const nm = document.createElement('span');
nm.className = 'tl-chip-name';
nm.textContent = info.name;
chip.appendChild(sw);
chip.appendChild(nm);
chip.addEventListener('pointerdown', (e) => tlStartDrag(e, { kind: 'new', play, chip }));
list.appendChild(chip);
});
};
const match = (name) => !q || String(name || '').toLowerCase().includes(q);
section(
'Presets',
Object.keys(seqEd.presetsMap)
.filter((id) => match((seqEd.presetsMap[id] || {}).name || id))
.sort(byName(seqEd.presetsMap))
.map((id) => `p:${id}`),
);
section(
'One-shot sequences',
Object.keys(seqEd.seqMap)
.filter((id) => seqIsOneShot(seqEd.seqMap[id]) && id !== sequenceEditorId && match(seqEd.seqMap[id].name || id))
.sort(byName(seqEd.seqMap))
.map((id) => `a:${id}`),
);
if (!list.children.length) {
const m = document.createElement('div');
m.className = 'muted-text';
m.textContent = q ? 'Nothing matches.' : 'No presets yet.';
list.appendChild(m);
}
}
function tlField(label, input) {
const l = document.createElement('label');
l.className = 'tl-insp-field';
const s = document.createElement('span');
s.textContent = label;
l.appendChild(s);
l.appendChild(input);
return l;
}
function tlBtn(text, title, fn, cls) {
const b = document.createElement('button');
b.type = 'button';
b.className = cls || 'btn btn-secondary btn-small';
b.textContent = text;
b.title = title;
b.addEventListener('click', fn);
return b;
}
function tlRenderInspector() {
const host = tlEl('tl-inspector');
if (!host) return;
host.innerHTML = '';
const sel = seqTl.sel;
const clip = sel && sel.clip ? tlClip(sel.clip) : null;
const track = sel && sel.track ? tlTrack(sel.track) : null;
if (clip) return tlInspectClip(host, clip);
if (track) return tlInspectTrack(host, track);
// Nothing selected: the inspector stays empty (and hidden by the stylesheet)
}
function tlInspectClip(host, c) {
const timed = tlTimed();
const unit = timed ? 's' : 'beats';
const title = document.createElement('div');
title.className = 'tl-insp-title';
title.textContent = 'Clip';
host.appendChild(title);
const row = document.createElement('div');
row.className = 'tl-insp-row';
const play = buildStepPlaySelect(c.play.startsWith('a:') ? { animation_id: c.play.slice(2) } : { preset_id: c.play.slice(2) });
[...play.options].forEach((o) => {
if (o.value === 'rest' || o.value === '') o.remove();
});
play.addEventListener('change', () => {
if (!play.value) return;
c.play = play.value;
seqTl.brush = c.play;
tlRender();
});
row.appendChild(tlField('Plays', play));
const num = (v, min) => {
const i = document.createElement('input');
i.type = 'number';
i.min = String(min);
i.step = String(seqTl.snap < 1 ? seqTl.snap : tlMin());
i.value = String(v);
i.style.width = '5.5rem';
return i;
};
const start = num(c.start, 0);
const len = num(c.len, tlMin());
const apply = () => {
const s = tlR(Math.max(0, parseFloat(start.value) || 0));
const l = tlR(Math.max(tlMin(), parseFloat(len.value) || tlMin()));
if (!tlFits(c.uid, s, l, c.id)) {
start.value = String(c.start);
len.value = String(c.len);
host.classList.add('tl-shake');
setTimeout(() => host.classList.remove('tl-shake'), 300);
return;
}
c.start = s;
c.len = l;
seqTl.lastLen = l;
tlRender();
};
start.addEventListener('change', apply);
len.addEventListener('change', apply);
row.appendChild(tlField(`Start (${unit})`, start));
row.appendChild(tlField(`Length (${unit})`, len));
const trackSel = document.createElement('select');
trackSel.className = 'zone-device-add-select';
seqEd.targets.forEach((t, i) => trackSel.appendChild(new Option(seqEdTargetLabel(t, i), String(t.uid))));
trackSel.value = String(c.uid);
trackSel.addEventListener('change', () => {
const uid = parseInt(trackSel.value, 10);
if (!tlFits(uid, c.start, c.len, c.id)) {
alert('That track already has a clip there.');
trackSel.value = String(c.uid);
return;
}
c.uid = uid;
tlRender();
});
row.appendChild(tlField('Track', trackSel));
host.appendChild(row);
const btns = document.createElement('div');
btns.className = 'tl-insp-btns';
btns.appendChild(tlBtn('Edit', 'Edit the preset or sequence', () => tlEditPlay(c.play)));
btns.appendChild(tlBtn('Delete', 'Remove the clip (Delete)', () => tlDelete(c), 'btn btn-danger btn-small'));
host.appendChild(btns);
}
function tlInspectTrack(host, t) {
const i = seqEd.targets.indexOf(t);
const title = document.createElement('div');
title.className = 'tl-insp-title';
title.textContent = 'Track';
host.appendChild(title);
const row = document.createElement('div');
row.className = 'tl-insp-row';
const name = document.createElement('input');
name.type = 'text';
name.placeholder = `Target ${i + 1}`;
name.value = t.name || '';
name.style.width = '12rem';
name.addEventListener('change', () => {
t.name = name.value;
tlRender();
});
row.appendChild(tlField('Name', name));
host.appendChild(row);
const pick = document.createElement('div');
pick.className = 'tl-insp-pick';
const box = (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);
tlRender();
});
const s = document.createElement('span');
s.textContent = label;
l.appendChild(cb);
l.appendChild(s);
pick.appendChild(l);
};
const lab = (txt) => {
const d = document.createElement('div');
d.className = 'muted-text tl-insp-sub';
d.textContent = txt;
pick.appendChild(d);
};
lab('Plays to groups');
Object.keys(seqEd.groupsMap)
.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))
.forEach((g) => box((seqEd.groupsMap[g] && seqEd.groupsMap[g].name) || g, t.group_ids, g));
lab('and single drivers');
Object.keys(seqEd.devicesMap)
.sort((a, b) => String((seqEd.devicesMap[a] || {}).name || a).localeCompare(String((seqEd.devicesMap[b] || {}).name || b)))
.forEach((m) => box((seqEd.devicesMap[m] && seqEd.devicesMap[m].name) || m, t.devices, m));
host.appendChild(pick);
const btns = document.createElement('div');
btns.className = 'tl-insp-btns';
const up = tlBtn('Move up', 'Move the track up', () => {
seqEd.targets.splice(i - 1, 0, seqEd.targets.splice(i, 1)[0]);
tlRender();
});
up.disabled = i <= 0;
const down = tlBtn('Move down', 'Move the track down', () => {
seqEd.targets.splice(i + 1, 0, seqEd.targets.splice(i, 1)[0]);
tlRender();
});
down.disabled = i >= seqEd.targets.length - 1;
btns.appendChild(up);
btns.appendChild(down);
btns.appendChild(
tlBtn(
'Remove track',
'Remove the track and its clips',
() => {
const n = tlClipsOn(t.uid).length;
if (n && !confirm(`Remove this track and its ${n} clip(s)?`)) return;
seqTl.clips = seqTl.clips.filter((c) => c.uid !== t.uid);
seqEd.targets.splice(seqEd.targets.indexOf(t), 1);
seqTl.sel = null;
tlRender();
},
'btn btn-danger btn-small',
),
);
host.appendChild(btns);
}
/* --------------------------------------------------------------- undo/redo */
const TL_HISTORY_MAX = 100;
const tlHist = { undo: [], redo: [], cur: null }; // states as JSON; cur is the one on screen
/** What undo brings back: clips, tracks, the window and units. Not the selection, zoom or scroll. */
function tlSnapshot() {
return JSON.stringify({
clips: seqTl.clips,
targets: seqEd.targets,
loopEnd: seqTl.loopEnd,
loopEndSet: seqTl.loopEndSet,
mode: (tlEl('sequence-editor-mode') || {}).value || '',
loop: tlLoop(),
});
}
/** Called on each render: if the timeline changed since the last one, the old state is an undo step. */
function tlRecord() {
const s = tlSnapshot();
if (tlHist.cur !== null && s !== tlHist.cur) {
tlHist.undo.push(tlHist.cur);
if (tlHist.undo.length > TL_HISTORY_MAX) tlHist.undo.shift();
tlHist.redo = [];
}
tlHist.cur = s;
tlUndoButtons();
}
function tlUndoButtons() {
const u = tlEl('tl-undo');
const r = tlEl('tl-redo');
if (u) u.disabled = !tlHist.undo.length;
if (r) r.disabled = !tlHist.redo.length;
}
function tlRestore(s) {
const st = JSON.parse(s);
seqTl.clips = st.clips;
seqEd.targets = st.targets;
seqTl.loopEnd = st.loopEnd;
seqTl.loopEndSet = st.loopEndSet;
const mode = tlEl('sequence-editor-mode');
if (mode && st.mode) mode.value = st.mode;
const loop = tlEl('sequence-editor-loop');
if (loop) loop.checked = st.loop;
const sel = seqTl.sel;
if (sel && ((sel.clip && !tlClip(sel.clip)) || (sel.track && !tlTrack(sel.track)))) seqTl.sel = null;
tlHist.cur = s; // so the render below doesn't record the restore as a new edit
tlBuildSnap();
tlRender();
}
function tlUndo() {
if (!tlHist.undo.length || seqTl.drag) return;
tlHist.redo.push(tlHist.cur);
tlRestore(tlHist.undo.pop());
}
function tlRedo() {
if (!tlHist.redo.length || seqTl.drag) return;
tlHist.undo.push(tlHist.cur);
tlRestore(tlHist.redo.pop());
}
/* ------------------------------------------------------------------- edits */
function tlAddAt(uid, start, play) {
if (!play) {
alert('Pick a preset in the browser first (click it), or drag one onto the track.');
return;
}
const want = play.startsWith('a:') ? tlSeqLen(seqEd.seqMap[play.slice(2)]) : seqTl.lastLen;
const gap = tlGap(uid, start);
if (!gap) return;
const len = tlR(Math.min(want, gap.to - start));
if (len < tlMin() - TL_EPS) return;
const c = { id: seqTl.nextId++, uid, start, len, play };
seqTl.clips.push(c);
seqTl.sel = { clip: c.id };
seqTl.brush = play;
tlRender();
}
function tlDelete(c) {
seqTl.clips = seqTl.clips.filter((x) => x !== c);
seqTl.sel = null;
tlRender();
}
function tlDuplicate(c) {
let start = tlR(c.start + c.len);
for (let guard = 0; guard < 256 && !tlFits(c.uid, start, c.len); guard++) {
const blocker = tlClipsOn(c.uid).find((x) => x.start + x.len > start + TL_EPS && x.start < start + c.len - TL_EPS);
start = tlR(blocker ? blocker.start + blocker.len : start + c.len);
}
const d = { ...c, id: seqTl.nextId++, start };
seqTl.clips.push(d);
seqTl.sel = { clip: d.id };
tlRender();
}
async function tlEditPlay(play) {
const id = String(play || '').slice(2);
if (!id) return;
if (play.startsWith('a:')) {
openSequenceEditor(id, seqEd.seqMap[id]);
return;
}
let preset = seqEd.presetsMap[id];
try {
const r = await fetch(`/presets/${id}`, { headers: { Accept: 'application/json' } });
if (r.ok) preset = await r.json();
} catch (_) {
/* keep cached */
}
document.dispatchEvent(new CustomEvent('editPreset', { detail: { presetId: id, preset: preset || {}, zoneId: null } }));
}
/** Beats ↔ seconds: clips keep their place in time at the current tempo. */
function tlSetUnits(timed) {
const mode = tlEl('sequence-editor-mode');
if (!mode || tlTimed() === timed) return;
// A one-shot is always in seconds
if (!timed && !tlLoop()) return;
const beatS = 60 / tlBpm();
const k = timed ? beatS : 1 / beatS;
const min = timed ? 0.05 : 0.25;
const q = (x) => tlR(Math.round((x * k) / min) * min);
seqTl.clips.forEach((c) => {
c.start = q(c.start);
c.len = Math.max(min, q(c.len));
});
// Rounding can make neighbours touch over each other; push later clips along
seqEd.targets.forEach((t) => {
let at = 0;
tlClipsOn(t.uid).forEach((c) => {
if (c.start < at) c.start = tlR(at);
at = c.start + c.len;
});
});
seqTl.loopEnd = q(seqTl.loopEnd);
seqTl.lastLen = timed ? 4 : TL_BAR;
mode.value = timed ? 'time' : 'beats';
tlBuildSnap();
tlRender();
}
const TL_PPB_MIN = 6;
const TL_PPB_MAX = 800; // 0.05 s comes out at 40px, the finest tick
/**
* Zoom by `f`, keeping the time under `clientX` where it is (the middle of the view without one).
* The ruler, tracks and clips are laid out from --ppb, so this rebuilds them.
*/
function tlZoom(f, clientX) {
const sc = tlEl('tl-scroll');
const head = tlHeadWidth();
const view = sc ? Math.max(0, sc.clientWidth - head) : 0;
const px =
sc && clientX != null ? Math.min(view, Math.max(0, clientX - sc.getBoundingClientRect().left - head)) : view / 2;
const at = sc ? (sc.scrollLeft + px) / seqTl.ppb : 0;
const ppb = Math.min(TL_PPB_MAX, Math.max(TL_PPB_MIN, seqTl.ppb * f));
if (Math.abs(ppb - seqTl.ppb) < 0.01) return;
seqTl.ppb = Math.round(ppb * 100) / 100;
try {
localStorage.setItem('seqTlZoom', String(seqTl.ppb));
} catch (_) {
/* private mode */
}
tlRender();
if (sc) sc.scrollLeft = Math.max(0, at * seqTl.ppb - px);
}
/**
* Ctrl+wheel (trackpad pinch arrives as ctrl+wheel) zooms around the pointer. A plain wheel scrolls as
* usual: the timeline, then the page. Shift+wheel and sideways swipes scroll sideways.
* Wheel events come in bursts, so they add up and apply once per frame.
*/
function tlWheel(e) {
if (seqTl.drag) return;
const sc = tlEl('tl-scroll');
if (!sc) return;
if (!e.ctrlKey && !e.metaKey) return;
if (e.target.closest && e.target.closest('.tl-head')) return;
e.preventDefault();
const dy = e.deltaY * (e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? 400 : 1);
const w = seqTl.wheel || (seqTl.wheel = { f: 1, x: 0, raf: 0 });
// About 15% per mouse wheel notch; big deltas (fast wheels, some mice) are capped per event
w.f *= Math.min(1.25, Math.max(0.8, Math.exp(-dy * 0.01)));
w.x = e.clientX;
if (!w.raf) {
w.raf = requestAnimationFrame(() => {
w.raf = 0;
const f = w.f;
w.f = 1;
tlZoom(f, w.x);
});
}
}
/* ------------------------------------------------------------------- drags */
function tlLaneX(lane, clientX) {
return clientX - lane.getBoundingClientRect().left;
}
function tlLaneAt(x, y) {
const els = document.elementsFromPoint(x, y);
for (const el of els) {
if (el.classList && el.classList.contains('tl-lane')) return el;
}
return null;
}
/** Pointer drags for new clips (from the browser), moves, edge resizes and the loop end. */
function tlStartDrag(e, d) {
if (e.button !== undefined && e.button !== 0) return;
e.stopPropagation();
if (d.kind !== 'new') e.preventDefault();
seqTl.drag = { ...d, x0: e.clientX, y0: e.clientY, moved: false, pid: e.pointerId };
if (d.kind === 'loop') seqTl.drag.base = tlLoopLen();
try {
e.currentTarget.setPointerCapture(e.pointerId);
} catch (_) {
/* not capturable */
}
const src = e.currentTarget;
const move = (ev) => tlDragMove(ev);
const up = (ev) => {
src.removeEventListener('pointermove', move);
src.removeEventListener('pointerup', up);
src.removeEventListener('pointercancel', up);
tlDragEnd(ev, ev.type === 'pointercancel');
};
src.addEventListener('pointermove', move);
src.addEventListener('pointerup', up);
src.addEventListener('pointercancel', up);
if (d.kind === 'move' || d.kind === 'left' || d.kind === 'right') {
if (!seqTl.sel || seqTl.sel.clip !== d.id) tlSelect({ clip: d.id });
}
}
function tlGhost(lane) {
let g = document.querySelector('#tl-canvas .tl-ghost');
if (!lane) {
if (g) g.remove();
return null;
}
if (!g) {
g = document.createElement('div');
g.className = 'tl-ghost';
}
if (g.parentNode !== lane) lane.appendChild(g);
return g;
}
function tlFloat(d, x, y) {
let f = tlEl('tl-float');
if (!f) {
f = document.createElement('div');
f.id = 'tl-float';
f.className = 'tl-chip tl-float';
f.textContent = tlPlayInfo(d.play).name;
document.body.appendChild(f);
}
f.style.left = `${x + 8}px`;
f.style.top = `${y + 8}px`;
}
function tlDragMove(e) {
const d = seqTl.drag;
if (!d || e.pointerId !== d.pid) return;
const dxp = e.clientX - d.x0;
const dyp = e.clientY - d.y0;
if (!d.moved && Math.hypot(dxp, dyp) < 5) return;
d.moved = true;
const ppb = seqTl.ppb;
const dx = dxp / ppb;
if (d.kind === 'loop') {
seqTl.loopEnd = Math.max(tlMin(), tlQ(d.base + dx));
seqTl.loopEndSet = true;
const brace = document.querySelector('#tl-canvas .tl-loop');
const line = document.querySelector('#tl-canvas .tl-endline');
if (brace) brace.style.width = `${seqTl.loopEnd * ppb}px`;
if (line) line.style.left = `calc(var(--tl-head-w) + ${seqTl.loopEnd * ppb}px)`;
return;
}
if (d.kind === 'right' || d.kind === 'left') {
const c = tlClip(d.id);
if (!c) return;
const end0 = d.start0 + d.len0;
if (d.kind === 'right') {
const gap = tlGap(c.uid, d.start0, c.id);
const len = Math.max(tlMin(), tlQ(end0 + dx) - d.start0);
c.len = tlR(Math.min(len, (gap ? gap.to : Infinity) - d.start0));
} else {
const gap = tlGap(c.uid, end0 - TL_EPS * 10, c.id);
const s = Math.min(end0 - tlMin(), Math.max(gap ? gap.from : 0, tlQ(d.start0 + dx)));
c.start = tlR(s);
c.len = tlR(end0 - s);
}
d.el.style.left = `${c.start * ppb}px`;
d.el.style.width = `${c.len * ppb}px`;
return;
}
// move / new: a ghost on the track under the pointer
if (d.kind === 'new') tlFloat(d, e.clientX, e.clientY);
else d.el.classList.add('dragging');
const lane = tlLaneAt(e.clientX, e.clientY);
const g = tlGhost(lane);
d.target = null;
if (!lane || !g) return;
const uid = parseInt(lane.dataset.uid, 10);
let start;
let len;
let ok;
if (d.kind === 'new') {
start = tlQ(tlLaneX(lane, e.clientX) / ppb, true);
const want = d.play.startsWith('a:') ? tlSeqLen(seqEd.seqMap[d.play.slice(2)]) : seqTl.lastLen;
const gap = tlGap(uid, start);
len = gap ? tlR(Math.min(want, gap.to - start)) : want;
ok = !!gap && len >= tlMin() - TL_EPS;
} else {
start = tlQ(d.start0 + dx);
len = d.len0;
ok = tlFits(uid, start, len, d.id);
}
g.style.left = `${start * ppb}px`;
g.style.width = `${len * ppb}px`;
g.classList.toggle('bad', !ok);
if (ok) d.target = { uid, start, len };
}
function tlDragEnd(e, cancelled) {
const d = seqTl.drag;
seqTl.drag = null;
tlGhost(null);
const f = tlEl('tl-float');
if (f) f.remove();
if (!d) return;
if (d.kind === 'new') {
if (!d.moved) {
seqTl.brush = seqTl.brush === d.play ? '' : d.play;
tlRenderBrowser();
return;
}
if (!cancelled && d.target) {
const c = { id: seqTl.nextId++, uid: d.target.uid, start: d.target.start, len: d.target.len, play: d.play };
seqTl.clips.push(c);
seqTl.sel = { clip: c.id };
seqTl.brush = d.play;
}
tlRender();
return;
}
if (!d.moved && d.kind !== 'loop') return; // a click: the clip is selected already
if (d.kind === 'move') {
const c = tlClip(d.id);
if (c && !cancelled && d.target) {
c.uid = d.target.uid;
c.start = d.target.start;
}
tlRender();
return;
}
if (d.kind === 'right' || d.kind === 'left') {
const c = tlClip(d.id);
if (c && cancelled) {
c.start = d.start0;
c.len = d.len0;
} else if (c) seqTl.lastLen = c.len;
}
tlRender();
}
/* --------------------------------------------------------------- playhead */
function tlStartPoll() {
if (!seqTl.pollTimer) tlPoll();
if (!seqTl.raf) seqTl.raf = requestAnimationFrame(tlFrame);
}
async function tlPoll() {
seqTl.pollTimer = null;
const modal = tlEl('sequence-editor-modal');
if (!modal || !modal.classList.contains('active') || !seqTl.on) {
seqTl.head = null;
return;
}
if (sequenceEditorId) {
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.overlay && st.overlay.active && String(st.overlay.sequence_id) === sequenceEditorId) lanes = st.overlay.lanes;
else if (st && st.active && String(st.sequence_id) === sequenceEditorId) lanes = st.lanes;
if (Array.isArray(lanes)) {
const { map } = tlToLanes();
const li = lanes.findIndex((l, i) => l && l.started && !l.done && map[i]);
if (li >= 0) {
const l = lanes[li];
const m = map[li];
const timed = l.mode === 'time';
const s = m.starts[l.step] != null ? m.starts[l.step] : 0;
const into = timed ? (l.elapsed_ms || 0) / 1000 : l.beat_in_step || 0;
const looping = !!(st && st.active && String(st.sequence_id) === sequenceEditorId);
const now = performance.now();
const next = {
pos: s + into,
at: now,
rate: timed ? 1 : tlBpm() / 60,
max: m.ends[l.step] != null ? m.ends[l.step] : s + into,
wrap: looping ? tlLoopLen() : 0, // a looping sequence wraps at its window; a one-shot stops at its lane's end
};
// Keep the head where it was on screen and ease it onto the server's position, so a poll never jumps it
const old = seqTl.head;
if (old) {
const d = tlHeadDiff(tlHeadAt(old, now) + seqTl.headErr, tlHeadAt(next, now), next.wrap);
seqTl.headErr = Math.abs(d) < 0.5 ? d : 0;
} else seqTl.headErr = 0;
seqTl.headErrT = now;
seqTl.head = next;
} else seqTl.head = null;
} else seqTl.head = null;
} catch (_) {
/* try again: the head stays where it is */
}
} else {
seqTl.head = null;
}
seqTl.pollTimer = setTimeout(tlPoll, 250);
}
/** Where the head is at time now, extrapolated from its last poll. */
function tlHeadAt(h, now) {
const x = h.pos + ((now - h.at) / 1000) * h.rate;
return h.wrap > 0 ? ((x % h.wrap) + h.wrap) % h.wrap : Math.min(h.max, x);
}
/** a - b, the short way round a loop of length wrap (no wrap: plain difference). */
function tlHeadDiff(a, b, wrap) {
const d = a - b;
return wrap > 0 ? ((((d + wrap / 2) % wrap) + wrap) % wrap) - wrap / 2 : d;
}
function tlDrawHead() {
const ph = tlEl('tl-playhead');
const lcd = tlEl('tl-pos');
const h = seqTl.head;
const now = performance.now();
let pos = 0;
if (h) {
pos = tlHeadAt(h, now) + seqTl.headErr;
if (h.wrap > 0) pos = ((pos % h.wrap) + h.wrap) % h.wrap;
else pos = Math.min(h.max, pos);
seqTl.headErr *= Math.exp(-(now - seqTl.headErrT) / 150); // ease out the correction
seqTl.headErrT = now;
} else seqTl.headErr = 0;
if (ph) {
ph.hidden = !h;
if (h) ph.style.left = `calc(var(--tl-head-w) + ${pos * seqTl.ppb}px)`;
}
if (lcd) {
if (tlTimed()) lcd.textContent = `${pos.toFixed(1)} s`;
else lcd.textContent = `${Math.floor(pos / TL_BAR) + 1}.${Math.floor(pos % TL_BAR) + 1}`;
}
document.querySelectorAll('#tl-canvas .tl-clip').forEach((el) => {
const c = tlClip(parseInt(el.dataset.id, 10));
el.classList.toggle('playing', !!h && !!c && pos >= c.start - TL_EPS && pos < c.start + c.len);
});
}
function tlFrame() {
seqTl.raf = 0;
const modal = tlEl('sequence-editor-modal');
if (!modal || !modal.classList.contains('active') || !seqTl.on) return;
if (!seqTl.drag) tlDrawHead();
seqTl.raf = requestAnimationFrame(tlFrame);
}
/* -------------------------------------------------------------------- wire */
document.addEventListener('DOMContentLoaded', () => {
const on = (id, ev, fn) => {
const el = tlEl(id);
if (el) el.addEventListener(ev, fn);
};
on('tl-add-track', 'change', (e) => tlAddTrack(e.target.value));
on('tl-undo', 'click', tlUndo);
on('tl-redo', 'click', tlRedo);
on('tl-browser-search', 'input', tlRenderBrowser);
// The browser panel collapses to a strip with its arrow, giving the tracks the width; the choice is remembered
const setBrowser = (show) => {
const panel = document.querySelector('#seq-tl .tl-browser');
const btn = tlEl('tl-browser-toggle');
if (panel) panel.classList.toggle('collapsed', !show);
if (btn) {
btn.innerHTML = show ? '&#8250;' : '&#8249;';
btn.title = show ? 'Hide the browser' : 'Show the browser';
btn.setAttribute('aria-expanded', String(show));
}
};
let browserShown = true;
try {
browserShown = localStorage.getItem('seqTlBrowser') !== '0';
} catch (_) {
/* private mode */
}
setBrowser(browserShown);
on('tl-browser-toggle', 'click', () => {
browserShown = !browserShown;
setBrowser(browserShown);
try {
localStorage.setItem('seqTlBrowser', browserShown ? '1' : '0');
} catch (_) {
/* private mode */
}
});
on('tl-browser-refresh', 'click', async () => {
try {
const r = await fetch('/presets', { headers: { Accept: 'application/json' } });
if (r.ok) seqEd.presetsMap = await r.json();
seqEd.seqMap = await fetchSequencesMap();
} catch (_) {
/* keep what we have */
}
tlRender();
});
on('tl-snap', 'change', (e) => {
seqTl.snapAuto = e.target.value === 'auto';
seqTl.snap = seqTl.snapAuto ? tlAutoSnap() : parseFloat(e.target.value) || 1;
});
// The buttons zoom around where the pointer last was over the timeline (the middle until it has been)
on('tl-zoom-in', 'click', () => tlZoom(1.4, seqTl.hoverX));
const tlScroll = tlEl('tl-scroll');
if (tlScroll) {
tlScroll.addEventListener('wheel', tlWheel, { passive: false });
tlScroll.addEventListener('pointermove', (e) => {
seqTl.hoverX = e.clientX;
});
}
on('tl-zoom-out', 'click', () => tlZoom(1 / 1.4, seqTl.hoverX));
// Units dropdown: put the old value back first, so tlSetUnits sees a change and converts the clips
on('sequence-editor-mode', 'change', (e) => {
const timed = e.target.value === 'time';
e.target.value = timed ? 'beats' : 'time';
tlSetUnits(timed);
});
on('tl-play', 'click', async () => {
const ok = await saveSequenceEditor();
if (ok === false || !sequenceEditorId) return;
const zid = resolveZoneIdForPresetStripRefresh();
try {
if (!tlLoop()) await fireOneShot(sequenceEditorId, zid);
else await requestBackendSequencePlay(sequenceEditorId, zid, null);
} catch (err) {
alert(err.message || 'Could not play it.');
}
});
on('tl-stop', 'click', async () => {
// A one-shot plays over the zone: end it as well as the looping sequence
try {
await fetch('/sequences/overlay/stop', { method: 'POST', headers: { Accept: 'application/json' } });
} catch (_) {
/* the sequence stop below still runs */
}
await stopZoneSequencePlayback();
});
on('sequence-editor-loop', 'change', () => {
// Loop off makes a one-shot, which is timed in seconds: switch the clips over with it
if (!tlLoop()) tlSetUnits(true);
tlRender();
});
document.addEventListener('keydown', (e) => {
const modal = tlEl('sequence-editor-modal');
if (!seqTl.on || !modal || !modal.classList.contains('active')) return;
if (e.target && e.target.closest && e.target.closest('input, select, textarea, [contenteditable]')) return;
if (document.querySelector('.modal.active:not(#sequence-editor-modal)')) return;
const k = e.key.toLowerCase();
if ((e.ctrlKey || e.metaKey) && (k === 'z' || k === 'y')) {
e.preventDefault();
if (k === 'y' || e.shiftKey) tlRedo();
else tlUndo();
return;
}
const c = seqTl.sel && seqTl.sel.clip ? tlClip(seqTl.sel.clip) : null;
if (!c) return;
if (e.key === 'Delete' || e.key === 'Backspace') {
e.preventDefault();
tlDelete(c);
} else if (e.key === 'Escape') {
seqTl.sel = null;
tlRender();
} else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'd') {
e.preventDefault();
tlDuplicate(c);
}
});
});
window.seqTlOnOpen = seqTlOnOpen;