Add a scrubbable timed lyric editor to the admin page, LRCLIB regeneration tooling with lyrics skills, and keep the five playback buttons on one row on phones

This commit is contained in:
Jonathan Sykes
2026-09-20 17:55:49 +08:00
parent b983c6ca3c
commit 2987f46037
8 changed files with 919 additions and 3 deletions

View File

@@ -53,6 +53,28 @@
.hidden { display: none !important; }
.src { font-family: var(--mono); font-size: 11px; color: var(--text-dim); }
.src.api, .src.auto { color: var(--warn); } .src.restore { color: var(--ok); }
/* --- lyric editor --- */
#leWrap { margin-top: 12px; }
#leWave { width: 100%; height: 72px; display: block; border: 1px solid var(--line); border-radius: 9px; background: var(--bg-1); cursor: pointer; touch-action: none; }
.le-clock { font-family: var(--mono); font-size: 18px; min-width: 96px; text-align: center; }
.le-clock b { color: var(--accent); }
.le-lines { max-height: 56vh; overflow-y: auto; border: 1px solid var(--line); border-radius: 9px; background: var(--bg-1); }
.le-line { display: flex; gap: 6px; align-items: center; padding: 4px 6px; border-bottom: 1px solid var(--line); }
.le-line:last-child { border-bottom: 0; }
.le-line.now { background: color-mix(in srgb, var(--accent) 16%, transparent); }
.le-line.next { background: color-mix(in srgb, var(--accent) 7%, transparent); }
.le-line.untimed .le-t { color: var(--warn); }
.le-t { font-family: var(--mono); font-size: 12px; width: 74px; flex: none; background: var(--bg-2); color: var(--text); border: 1px solid var(--line); border-radius: 6px; padding: 5px 4px; text-align: center; }
.le-line input.le-text { flex: 1 1 auto; min-width: 80px; background: transparent; border: 0; color: var(--text); font-size: 14px; padding: 5px 4px; }
.le-line input.le-text:focus { outline: 1px solid var(--accent); border-radius: 6px; }
.le-line.section input.le-text { font-weight: 700; color: var(--text-2); }
.le-line.cue input.le-text { font-style: italic; color: var(--warn); }
.le-mini { padding: 3px 6px; font-size: 12px; line-height: 1.1; flex: none; }
.le-kind { background: var(--bg-2); color: var(--text-2); border: 1px solid var(--line); border-radius: 6px; font-size: 11px; padding: 4px; flex: none; }
#leRaw { width: 100%; min-height: 40vh; background: var(--bg-1); color: var(--text); border: 1px solid var(--line); border-radius: 9px; padding: 10px; font-family: var(--mono); font-size: 12px; }
.pill { font-family: var(--mono); font-size: 11px; border: 1px solid var(--line); border-radius: 999px; padding: 2px 8px; color: var(--text-dim); }
.pill.on { color: var(--accent); border-color: var(--accent); }
</style>
</head>
<body>
@@ -101,6 +123,56 @@
<div id="injectMsg" class="msg"></div>
</section>
<section>
<div class="row" style="margin-bottom:10px">
<h2 style="margin:0">Lyric editor</h2>
<span class="spacer"></span>
<span id="leState" class="pill">no song loaded</span>
</div>
<p class="muted">Play the song here and time every line against it: <b>Set</b> stamps the playhead onto a line, <b>Tap</b> mode walks down the lines as you tap (Space), and the waveform scrubs. Saving writes a new shared revision — the old one stays restorable below.</p>
<form id="leLoadForm" class="row">
<input type="text" id="leId" placeholder="YouTube URL, video id, or upl_… id" />
<button class="primary" type="submit">Load</button>
<button type="button" id="leFromWeb" title="Fetch lyrics from LRCLIB for this song">⤓ LRCLIB</button>
</form>
<div id="leMsg" class="msg"></div>
<div id="leWrap" class="hidden">
<div class="row" style="margin-bottom:8px">
<b id="leTitle"></b><span class="muted" id="leMeta"></span>
</div>
<canvas id="leWave" height="72"></canvas>
<div class="row" style="margin:8px 0">
<button type="button" id="lePlay">▶︎ Play</button>
<button type="button" id="leBack">« 5s</button>
<button type="button" id="leFwd">5s »</button>
<span class="le-clock"><b id="leCur">0:00.00</b> / <span id="leDur">0:00</span></span>
<select id="leRate" class="le-kind" title="Playback speed">
<option value="0.5">0.5×</option><option value="0.75">0.75×</option>
<option value="1" selected>1×</option><option value="1.25">1.25×</option><option value="1.5">1.5×</option>
</select>
<button type="button" id="leTap">⏱ Tap mode</button>
<span class="spacer"></span>
<label class="muted"><input type="checkbox" id="leFollow" checked /> Follow</label>
<button type="button" id="leRawBtn">✎ Text</button>
</div>
<div class="row" style="margin-bottom:8px">
<input type="text" id="leTags" placeholder="Tags — e.g. Key G, 70 BPM, from LRCLIB (synced)" />
<label class="muted">Shift all <input type="text" id="leShift" value="0.0" style="width:66px;flex:none" /> s</label>
<button type="button" id="leShiftBtn">Apply shift</button>
<button type="button" id="leAddBtn">+ Line</button>
</div>
<div class="le-lines" id="leLines"></div>
<textarea id="leRaw" class="hidden" spellcheck="false"></textarea>
<div class="row" style="margin-top:10px">
<button class="primary" id="leSave" type="button">Save lyrics</button>
<button type="button" id="leReload">Discard changes</button>
<span class="spacer"></span>
<span class="muted" id="leDirty"></span>
</div>
</div>
</section>
<section>
<h2>Upload video / audio</h2>
<p class="muted">Uploads are served by this server and appear in search and in the app's 📁 Library. Title, artist, duration, cover art and embedded lyrics are read from the file; a separate cover image and manual title/artist override them.</p>
@@ -154,8 +226,9 @@
function videoIdFrom(input) {
const s = String(input || '').trim();
if (/^[A-Za-z0-9_-]{11}$/.test(s)) return s;
const m = s.match(/(?:v=|youtu\.be\/|shorts\/|embed\/|live\/)([A-Za-z0-9_-]{11})/);
if (/^[A-Za-z0-9_-]{11}$/.test(s) || /^upl_[a-f0-9]{12}$/.test(s)) return s;
const m = s.match(/(?:v=|youtu\.be\/|shorts\/|embed\/|live\/)([A-Za-z0-9_-]{11})/)
|| s.match(/(upl_[a-f0-9]{12})/);
return m ? m[1] : null;
}
@@ -176,6 +249,8 @@
loadTokens();
loadRevs();
loadUploads();
const want = videoIdFrom(new URLSearchParams(location.search).get('v') || '');
if (want) leOpen(want);
}
$('loginForm').addEventListener('submit', async (e) => {
@@ -257,6 +332,7 @@
<td><span class="src ${esc(r.source)}">${esc(r.source)}</span></td>
<td class="row">
<button data-view="${esc(r.videoId)}|${esc(r.kind)}|${r.rev}">View</button>
${r.kind === 'lyrics' ? `<button data-edit="${esc(r.videoId)}">Edit</button>` : ''}
<button data-restore="${esc(r.videoId)}|${esc(r.kind)}|${r.rev}">Restore</button>
</td>
</tr>`).join('');
@@ -279,6 +355,7 @@
$('revTable').addEventListener('click', async (e) => {
const v = e.target.dataset.view;
const r = e.target.dataset.restore;
if (e.target.dataset.edit) { leOpen(e.target.dataset.edit); return; }
if (v) {
const [id, kind, rev] = v.split('|');
const j = await api(`/api/notes/${id}/${kind}/revs/${rev}`);
@@ -306,6 +383,7 @@
<td class="muted">${Math.round(u.duration)}s · ${(u.size / 1048576).toFixed(1)} MB</td>
<td><code>${esc(u.id)}</code></td>
<td><a class="btn" href="/?v=${esc(u.id)}" target="_blank" rel="noopener">Play</a>
<button data-lyrics="${esc(u.id)}">Lyrics</button>
<button class="danger" data-del="${esc(u.id)}">Delete</button></td>
</tr>`).join('');
$('upTable').innerHTML = rows
@@ -347,6 +425,7 @@
});
$('upTable').addEventListener('click', async (e) => {
if (e.target.dataset.lyrics) { leOpen(e.target.dataset.lyrics); return; }
const id = e.target.dataset.del;
if (!id || !confirm('Delete this upload? The file is removed from the server.')) return;
const j = await api(`/api/admin/uploads/${encodeURIComponent(id)}`, { method: 'DELETE' });
@@ -354,6 +433,375 @@
loadUploads();
});
/* ========================================================================
* Lyric editor — the song plays here, so every line can be timed against
* what you actually hear. The rows are built ONCE per load and then only
* their classes/values change: rebuilding them would steal focus from the
* field being typed in and reset the scroll position.
* ====================================================================== */
const LE = {
id: '', rev: 0, lines: [], tags: [], offset: 0, dur: 0,
audio: null, peaks: null, rows: [], tap: false, dirty: false, raw: false,
};
const clamp2 = (n) => Math.round(n * 100) / 100;
function fmtT(t) {
if (t == null) return '';
const m = Math.floor(t / 60);
return `${m}:${(t - m * 60).toFixed(2).padStart(5, '0')}`;
}
function parseT(s) {
const v = String(s || '').trim();
if (!v) return null;
const m = v.match(/^(\d+):(\d{1,2}(?:\.\d+)?)$/);
const n = m ? Number(m[1]) * 60 + Number(m[2]) : Number(v);
return Number.isFinite(n) && n >= 0 ? clamp2(n) : null;
}
function leDirty(on) {
LE.dirty = on;
$('leDirty').textContent = on ? 'unsaved changes' : '';
$('leDirty').className = on ? 'muted' : 'muted';
}
function leSay(text, cls) { const m = $('leMsg'); m.className = 'msg' + (cls ? ' ' + cls : ''); m.textContent = text; }
async function leLoad(id, keepAudio) {
leSay('Loading…');
const [notes, streams] = await Promise.all([
api(`/api/notes/${id}`),
fetch(`/api/streams?v=${encodeURIComponent(id)}`, { credentials: 'same-origin' }).then((r) => r.json()).catch(() => ({})),
]);
const doc = (notes.lyrics && notes.lyrics.data) || { lines: [], tags: [], offset: 0 };
LE.id = id;
LE.rev = (notes.lyrics && notes.lyrics.rev) || 0;
LE.lines = (doc.lines || []).map((l) => ({ t: l.t == null ? null : clamp2(l.t), text: String(l.text || ''), kind: l.kind || 'line' }));
LE.tags = doc.tags || [];
LE.offset = Number(doc.offset) || 0;
const meta = (streams.data && streams.data.meta) || {};
LE.dur = Number(meta.duration) || 0;
$('leTitle').textContent = meta.title || id;
$('leMeta').textContent = ` ${meta.channel || ''} · ${LE.lines.length} lines · rev ${LE.rev}`;
$('leTags').value = LE.tags.join(', ');
$('leState').textContent = LE.lines.length ? `${LE.lines.filter((l) => l.t != null).length}/${LE.lines.length} timed` : 'no lyrics yet';
$('leState').className = 'pill' + (LE.lines.length && LE.lines.every((l) => l.t != null) ? ' on' : '');
$('leWrap').classList.remove('hidden');
leRender();
leDirty(false);
leSay(`Loaded ${id}`, 'ok');
if (!keepAudio) {
const url = (streams.data && streams.data.audioUrl)
|| ((streams.data && streams.data.qualities || []).find((q) => q.hasAudio) || {}).url || '';
if (LE.audio) { LE.audio.pause(); LE.audio.src = ''; }
LE.audio = null;
if (url) {
const a = new Audio(url);
a.preload = 'auto';
a.addEventListener('timeupdate', leTick);
a.addEventListener('seeked', leTick);
a.addEventListener('loadedmetadata', () => { if (a.duration) { LE.dur = a.duration; $('leDur').textContent = fmtT(a.duration).slice(0, -3); } leDraw(); });
a.addEventListener('play', () => { $('lePlay').textContent = '❚❚ Pause'; });
a.addEventListener('pause', () => { $('lePlay').textContent = '▶︎ Play'; });
a.addEventListener('error', () => leSay('No playable audio for this song on the server — you can still edit the text.', 'err'));
LE.audio = a;
} else {
leSay('This song is not cached on the server, so there is no audio to time against.', 'err');
}
$('leDur').textContent = fmtT(LE.dur).slice(0, -3);
LE.peaks = null;
fetch(`/api/media/${id}/peaks`, { credentials: 'same-origin' })
.then((r) => r.json()).then((j) => { if (j.ok) { LE.peaks = j.peaks; if (j.duration) LE.dur = j.duration; leDraw(); } })
.catch(() => { /* peaks are a nicety */ });
}
leDraw();
}
function leRow(line, i) {
const row = document.createElement('div');
row.className = 'le-line' + (line.t == null ? ' untimed' : '') + (line.kind !== 'line' ? ' ' + line.kind : '');
row.dataset.i = String(i);
row.innerHTML = `
<input class="le-t" value="${esc(fmtT(line.t))}" placeholder="—" title="Line time — type it, or use Set" />
<button class="le-mini" data-act="set" title="Stamp the playhead here (S)">Set</button>
<button class="le-mini" data-act="seek" title="Play from here">▶︎</button>
<button class="le-mini" data-act="nudge" data-d="-0.2" title="0.2 s earlier">−</button>
<button class="le-mini" data-act="nudge" data-d="0.2" title="0.2 s later">+</button>
<input class="le-text" value="${esc(line.text)}" />
<select class="le-kind" title="Line type">
<option value="line">line</option><option value="section">section</option><option value="cue">cue</option>
</select>
<button class="le-mini" data-act="add" title="Insert a line below">⏎</button>
<button class="le-mini danger" data-act="del" title="Delete this line">✕</button>`;
row.querySelector('.le-kind').value = line.kind;
return row;
}
function leRender() {
const box = $('leLines');
box.innerHTML = '';
LE.rows = LE.lines.map((l, i) => { const r = leRow(l, i); box.appendChild(r); return r; });
if (!LE.lines.length) box.innerHTML = '<div class="le-line muted" style="padding:12px">No lines yet — “+ Line”, paste them in ✎ Text, or pull them from LRCLIB.</div>';
$('leMeta').textContent = $('leMeta').textContent.replace(/\d+ lines/, `${LE.lines.length} lines`);
}
// Which line is sung at time t (doc offset included, as the app plays it).
function leIndexAt(t) {
let hit = -1;
for (let i = 0; i < LE.lines.length; i++) {
const lt = LE.lines[i].t;
if (lt != null && lt + LE.offset <= t) hit = i; else if (lt != null) break;
}
return hit;
}
let leLastIdx = -2;
function leTick() {
const t = LE.audio ? LE.audio.currentTime : 0;
$('leCur').textContent = fmtT(t);
const i = LE.tap ? leTapIdx() : leIndexAt(t);
if (i !== leLastIdx) {
// Clear every row, not just the previous pair: in tap mode (and after a
// seek) the index jumps, and a stale highlight would be left behind.
for (const r of LE.rows) r.classList.remove('now', 'next');
if (LE.rows[i]) LE.rows[i].classList.add('now');
if (LE.rows[i + 1]) LE.rows[i + 1].classList.add('next');
if ($('leFollow').checked && LE.rows[i]) LE.rows[i].scrollIntoView({ block: 'center', behavior: 'smooth' });
leLastIdx = i;
}
leDraw();
}
function leDraw() {
const c = $('leWave');
if (!c) return;
const w = c.clientWidth || 600, h = c.height;
const dpr = window.devicePixelRatio || 1;
if (c.width !== Math.round(w * dpr)) { c.width = Math.round(w * dpr); }
const g = c.getContext('2d');
g.setTransform(dpr, 0, 0, dpr, 0, 0);
const css = getComputedStyle(document.body);
g.clearRect(0, 0, w, h);
const dur = LE.dur || 1;
const cur = LE.audio ? LE.audio.currentTime : 0;
if (LE.peaks && LE.peaks.length) {
const n = LE.peaks.length, bw = w / n;
for (let i = 0; i < n; i++) {
const bh = Math.max(1, (LE.peaks[i] / 100) * (h - 8));
g.fillStyle = (i * dur) / n <= cur ? css.getPropertyValue('--accent') : css.getPropertyValue('--line');
g.fillRect(i * bw, (h - bh) / 2, Math.max(1, bw - 0.5), bh);
}
} else {
g.fillStyle = css.getPropertyValue('--line');
g.fillRect(0, h / 2 - 1, w, 2);
g.fillStyle = css.getPropertyValue('--accent');
g.fillRect(0, h / 2 - 1, (cur / dur) * w, 2);
}
// line markers
g.fillStyle = css.getPropertyValue('--text-2');
for (const l of LE.lines) {
if (l.t == null) continue;
const x = ((l.t + LE.offset) / dur) * w;
g.fillRect(x, 0, 1, 6);
g.fillRect(x, h - 6, 1, 6);
}
g.fillStyle = css.getPropertyValue('--text');
g.fillRect((cur / dur) * w - 1, 0, 2, h);
}
function leSeek(t) {
if (!LE.audio) return;
LE.audio.currentTime = Math.max(0, Math.min(LE.dur || 1e9, t));
leTick();
}
// Tap mode: the next line without a time (or the one after the playhead).
function leTapIdx() {
const i = LE.lines.findIndex((l) => l.t == null);
if (i >= 0) return i;
return Math.min(LE.lines.length - 1, leIndexAt(LE.audio ? LE.audio.currentTime : 0) + 1);
}
function leStamp(i) {
if (!LE.audio || i < 0 || i >= LE.lines.length) return;
LE.lines[i].t = clamp2(LE.audio.currentTime);
const row = LE.rows[i];
if (row) { row.querySelector('.le-t').value = fmtT(LE.lines[i].t); row.classList.remove('untimed'); }
leDirty(true);
leLastIdx = -2;
leTick();
}
$('leLoadForm').addEventListener('submit', (e) => {
e.preventDefault();
const id = videoIdFrom($('leId').value);
if (!id) { leSay('Not a YouTube URL, video id or upl_ id', 'err'); return; }
if (LE.dirty && !confirm('Discard the unsaved changes to the song you have open?')) return;
leLoad(id);
});
$('leFromWeb').addEventListener('click', async () => {
const id = LE.id || videoIdFrom($('leId').value);
if (!id) { leSay('Load a song first', 'err'); return; }
leSay('Asking LRCLIB…');
const j = await api(`/api/notes/${id}/lyrics/web`, { method: 'POST', body: { overwrite: true } });
if (!j.ok) { leSay(j.error || 'LRCLIB has nothing for this song', 'err'); return; }
await leLoad(id, true);
leSay(`LRCLIB: ${j.lines} ${j.synced ? 'synced' : 'plain'} lines saved as rev ${j.rev} — the previous version is restorable below.`, 'ok');
loadRevs();
});
$('leLines').addEventListener('click', (e) => {
const btn = e.target.closest('button[data-act]');
if (!btn) return;
const i = Number(btn.closest('.le-line').dataset.i);
const act = btn.dataset.act;
if (act === 'set') leStamp(i);
else if (act === 'seek') { leSeek((LE.lines[i].t || 0) + LE.offset); if (LE.audio && LE.audio.paused) LE.audio.play().catch(() => {}); }
else if (act === 'nudge') {
if (LE.lines[i].t == null) return;
LE.lines[i].t = clamp2(Math.max(0, LE.lines[i].t + Number(btn.dataset.d)));
btn.closest('.le-line').querySelector('.le-t').value = fmtT(LE.lines[i].t);
leDirty(true); leDraw();
} else if (act === 'add') {
LE.lines.splice(i + 1, 0, { t: null, text: '', kind: 'line' });
leRender(); leDirty(true);
const next = LE.rows[i + 1]; if (next) next.querySelector('.le-text').focus();
} else if (act === 'del') {
LE.lines.splice(i, 1);
leRender(); leDirty(true); leDraw();
}
});
$('leLines').addEventListener('input', (e) => {
const row = e.target.closest('.le-line');
if (!row) return;
const i = Number(row.dataset.i);
if (e.target.classList.contains('le-text')) { LE.lines[i].text = e.target.value; leDirty(true); }
});
$('leLines').addEventListener('change', (e) => {
const row = e.target.closest('.le-line');
if (!row) return;
const i = Number(row.dataset.i);
if (e.target.classList.contains('le-t')) {
LE.lines[i].t = parseT(e.target.value);
e.target.value = fmtT(LE.lines[i].t);
row.classList.toggle('untimed', LE.lines[i].t == null);
leDirty(true); leDraw();
} else if (e.target.classList.contains('le-kind')) {
LE.lines[i].kind = e.target.value;
row.classList.remove('section', 'cue');
if (e.target.value !== 'line') row.classList.add(e.target.value);
leDirty(true);
}
});
// Enter in a line = insert the next one below (writing lyrics by ear).
$('leLines').addEventListener('keydown', (e) => {
if (e.key !== 'Enter' || !e.target.classList.contains('le-text')) return;
e.preventDefault();
const i = Number(e.target.closest('.le-line').dataset.i);
LE.lines.splice(i + 1, 0, { t: null, text: '', kind: LE.lines[i].kind === 'section' ? 'line' : LE.lines[i].kind });
leRender(); leDirty(true);
if (LE.rows[i + 1]) LE.rows[i + 1].querySelector('.le-text').focus();
});
$('lePlay').addEventListener('click', () => {
if (!LE.audio) return;
if (LE.audio.paused) LE.audio.play().catch((err) => leSay('Playback failed: ' + err.message, 'err'));
else LE.audio.pause();
});
$('leBack').addEventListener('click', () => leSeek((LE.audio ? LE.audio.currentTime : 0) - 5));
$('leFwd').addEventListener('click', () => leSeek((LE.audio ? LE.audio.currentTime : 0) + 5));
$('leRate').addEventListener('change', () => { if (LE.audio) LE.audio.playbackRate = Number($('leRate').value); });
$('leTap').addEventListener('click', () => {
LE.tap = !LE.tap;
$('leTap').classList.toggle('primary', LE.tap);
leSay(LE.tap ? 'Tap mode: press Space (or S) on the beat to stamp the highlighted line; it then moves to the next one.' : '', LE.tap ? 'ok' : '');
leLastIdx = -2; leTick();
});
$('leWave').addEventListener('pointerdown', (e) => {
const r = e.currentTarget.getBoundingClientRect();
leSeek(((e.clientX - r.left) / r.width) * (LE.dur || 0));
});
window.addEventListener('resize', leDraw);
document.addEventListener('keydown', (e) => {
if ($('leWrap').classList.contains('hidden')) return;
const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName);
if (e.code === 'Space' && LE.tap && !typing) { e.preventDefault(); leStamp(leTapIdx()); return; }
if ((e.key === 's' || e.key === 'S') && !typing && !e.metaKey && !e.ctrlKey) { e.preventDefault(); leStamp(LE.tap ? leTapIdx() : leIndexAt(LE.audio ? LE.audio.currentTime : 0)); return; }
if (e.key === 'k' && !typing) { e.preventDefault(); $('lePlay').click(); }
});
$('leShiftBtn').addEventListener('click', () => {
const d = Number($('leShift').value);
if (!Number.isFinite(d) || !d) return;
for (const l of LE.lines) if (l.t != null) l.t = clamp2(Math.max(0, l.t + d));
leRender(); leDirty(true); leDraw();
leSay(`Shifted every timed line by ${d > 0 ? '+' : ''}${d}s`, 'ok');
});
$('leAddBtn').addEventListener('click', () => {
LE.lines.push({ t: LE.audio ? clamp2(LE.audio.currentTime) : null, text: '', kind: 'line' });
leRender(); leDirty(true);
const last = LE.rows[LE.rows.length - 1]; if (last) last.querySelector('.le-text').focus();
});
$('leTags').addEventListener('input', () => { LE.tags = $('leTags').value.split(',').map((s) => s.trim()).filter(Boolean); leDirty(true); });
// ✎ Text — the same LRC superset the app's own editor uses.
$('leRawBtn').addEventListener('click', () => {
LE.raw = !LE.raw;
$('leRaw').classList.toggle('hidden', !LE.raw);
$('leLines').classList.toggle('hidden', LE.raw);
$('leRawBtn').textContent = LE.raw ? '≡ Lines' : '✎ Text';
if (LE.raw) {
$('leRaw').value = LE.lines.map((l) => (l.t == null ? '' : `[${fmtT(l.t)}] `) + (l.kind === 'section' ? '# ' : l.kind === 'cue' ? '! ' : '') + l.text).join('\n');
} else {
LE.lines = $('leRaw').value.split('\n').map((raw) => {
let rest = raw.trim(), t = null;
const m = rest.match(/^\[(\d{1,3}):(\d{1,2}(?:[.:]\d{1,3})?)\]\s*/);
if (m) { t = clamp2(Number(m[1]) * 60 + Number(m[2].replace(':', '.'))); rest = rest.slice(m[0].length); }
let kind = 'line';
if (rest.startsWith('# ')) { kind = 'section'; rest = rest.slice(2); }
else if (rest.startsWith('! ')) { kind = 'cue'; rest = rest.slice(2); }
return { t, text: rest, kind };
}).filter((l) => l.text);
leRender(); leDirty(true); leDraw();
}
});
$('leReload').addEventListener('click', () => { if (LE.id && confirm('Throw away the unsaved changes and reload from the server?')) leLoad(LE.id, true); });
$('leSave').addEventListener('click', async () => {
if (!LE.id) return;
const lines = LE.lines.filter((l) => l.text.trim()).map((l) => ({ t: l.t, text: l.text.trim(), kind: l.kind }));
if (!lines.length) { leSay('Nothing to save', 'err'); return; }
const data = { lines, tags: LE.tags, offset: LE.offset };
leSay('Saving…');
let j = await api(`/api/notes/${LE.id}/lyrics`, { method: 'PUT', body: { data, baseRev: LE.rev } });
if (!j.ok && j.current) {
if (!confirm(`Someone else saved this song while you were editing (their rev ${j.current.rev}).\n\nOK = keep YOUR version, Cancel = load theirs.`)) {
await leLoad(LE.id, true);
return;
}
j = await api(`/api/notes/${LE.id}/lyrics`, { method: 'PUT', body: { data, force: true } });
}
if (!j.ok) { leSay(j.error || 'save failed', 'err'); return; }
LE.rev = j.rev;
leDirty(false);
const timed = lines.filter((l) => l.t != null).length;
$('leState').textContent = `${timed}/${lines.length} timed`;
$('leState').className = 'pill' + (timed === lines.length ? ' on' : '');
leSay(`Saved ${lines.length} lines as rev ${j.rev}.`, 'ok');
loadRevs();
});
window.addEventListener('beforeunload', (e) => { if (LE.dirty) { e.preventDefault(); e.returnValue = ''; } });
// "Edit" from the revisions feed and ?v= in the URL open a song here.
function leOpen(id) {
$('leId').value = id;
leLoad(id);
$('leWrap').scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function renderDocs() {
const o = location.origin;
$('apiDocs').textContent = `# Read (public)
@@ -388,6 +836,8 @@ curl ${o}/api/uploads?q=worship # public list / search
curl -X POST ${o}/api/notes/VIDEO_ID/lyrics/web \\
-H "Authorization: Bearer $YTP_TOKEN" -H "Content-Type: application/json" -d '{"overwrite": false}'
# Lyric editor deep link (admin): /admin?v=VIDEO_ID opens that song in the editor
# History (public)
curl ${o}/api/notes/VIDEO_ID/lyrics/revs
curl ${o}/api/notes/VIDEO_ID/lyrics/revs/3