';
}
// The slot's pinned-arrangement INDEX, resolved from the stored NAME
// against the slot's current chart (names survive rescans; an index
// wouldn't). null = no pin / the name isn't on this chart โ full song.
function _slotArrIndex(s) {
if (!s.arrangement || !Array.isArray(s.arrangements)) return null;
const m = s.arrangements.find((a) => a && (a.smart_name === s.arrangement || a.name === s.arrangement));
return (m && m.index != null) ? m.index : null;
}
function songRow(s, opts) {
opts = opts || {};
const handle = opts.draggable
? 'โ ฟ' : '';
const tuning = s.tuning_name
? '' + esc(s.tuning_name) + '' : '';
// โโ Curated-album slot extras (P6) โ mixes/saved emit none of this โโ
// A slot plays its RESOLVED chart (data-play-fn: the pinned file, or
// the work's current keeper when the pinned file is gone) with its
// pinned arrangement (data-play-arr); `missing` = the whole work left
// the library, so the row dims and loses play (denominator stays
// honest). โพ opens the slot editor (chart + arrangement pin).
const isAlbum = !!opts.album;
const missing = isAlbum && !!s.missing;
const playFn = s.resolved_filename || s.filename;
const arrIdx = isAlbum ? _slotArrIndex(s) : null;
const playAttrs = isAlbum && !missing
? ' data-play-fn="' + esc(playFn) + '"' + (arrIdx != null ? ' data-play-arr="' + arrIdx + '"' : '')
: '';
const acc = (isAlbum && typeof opts.acc === 'number')
? '' + Math.floor(opts.acc * 100) + '%'
: '';
const pin = (isAlbum && s.arrangement)
? '' + esc(s.arrangement) + '' : '';
const orphan = (isAlbum && s.resolved_from_orphan)
? '(auto)' : '';
const slotBtn = (isAlbum && !missing)
? '' : '';
return '
' +
handle +
'' +
'' + esc(s.title) + tuning + pin + orphan + '' +
'' + (missing ? 'Missing โ no version of this song is in your library' : esc(s.artist)) + '' +
acc +
(missing ? '' : '') +
slotBtn +
'' +
'
';
}
function wireSongRows(listEl, pid, onChange) {
listEl.querySelectorAll('li[data-fn]').forEach((li) => {
const fn = li.getAttribute('data-fn');
li.querySelector('[data-v3-play]')?.addEventListener('click', () => {
// playSong decodeURIComponent()s its arg for the highway WS, so
// pass an encoded filename (like the rest of v3) โ a raw name
// with %/#/?/ in it would otherwise misroute or throw.
// Album slots override the play target (data-play-fn = the
// orphan-resolved chart) + pass the pinned arrangement index;
// mix/saved rows carry neither attribute and behave as before.
const pfn = li.getAttribute('data-play-fn') || fn;
const pa = li.getAttribute('data-play-arr');
if (typeof window.playSong === 'function') {
window.playSong(encodeURIComponent(pfn), pa == null ? undefined : Number(pa));
}
});
li.querySelector('[data-remove]')?.addEventListener('click', async () => {
await fetch('/api/playlists/' + pid + '/songs/' + encodeURIComponent(fn), { method: 'DELETE' });
onChange();
});
});
// Drag-reorder.
let dragEl = null;
listEl.querySelectorAll('li[draggable="true"]').forEach((li) => {
li.addEventListener('dragstart', () => { dragEl = li; li.classList.add('opacity-50'); });
li.addEventListener('dragend', () => { li.classList.remove('opacity-50'); });
li.addEventListener('dragover', (e) => {
e.preventDefault();
if (!dragEl || dragEl === li) return;
const rect = li.getBoundingClientRect();
const after = (e.clientY - rect.top) > rect.height / 2;
li.parentNode.insertBefore(dragEl, after ? li.nextSibling : li);
});
li.addEventListener('drop', async (e) => {
e.preventDefault();
const order = Array.from(listEl.querySelectorAll('li[data-fn]')).map((x) => x.getAttribute('data-fn'));
await jsend('POST', '/api/playlists/' + pid + '/reorder', { order });
// Re-sync from the server: if /reorder was rejected (concurrent
// change) or the request failed, the optimistic DOM order would
// otherwise diverge from what was actually persisted.
onChange();
});
});
}
// โโ #v3-playlists โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ--
async function renderPlaylists() {
const root = document.getElementById('v3-playlists');
if (!root) return;
const lists = (await jget('/api/playlists')) || [];
// Drag-to-reorder is for user playlists only โ system ones (Saved for
// Later) stay pinned first by the server ordering.
const userCount = lists.filter((p) => !p.system_key).length;
root.innerHTML =
'
' +
'
' +
// Sort AโZ: clears the manual (drag) order server-side. Only worth
// showing once there are two user playlists to order.
(userCount > 1
? '' : '') +
// Curated album (P6): a hand-picked ORDERED set with a chosen chart
// per track โ same machinery as a playlist, kind='album'.
'' +
'' +
'
' +
(lists.length
? '
' + lists.map((p) =>
'').join('') + '
'
: '
No playlists yet. Create one to group songs.
') +
'
';
root.querySelector('#v3-pl-new')?.addEventListener('click', async () => {
const name = ((await window.uiPrompt({ title: 'New Playlist', label: 'Playlist name', okLabel: 'Create', placeholder: 'My Playlist' })) || '').trim();
if (!name) return;
await jsend('POST', '/api/playlists', { name });
renderPlaylists();
});
root.querySelector('#v3-pl-new-album')?.addEventListener('click', async () => {
const name = ((await window.uiPrompt({ title: 'New Album', label: 'Album name', okLabel: 'Create', placeholder: 'My Album' })) || '').trim();
if (!name) return;
await jsend('POST', '/api/playlists', { name, kind: 'album' });
renderPlaylists();
});
root.querySelector('#v3-pl-sort-az')?.addEventListener('click', async () => {
await jsend('POST', '/api/playlists/sort-alpha');
renderPlaylists();
});
root.querySelectorAll('[data-pl]').forEach((b) =>
b.addEventListener('click', () => renderPlaylistDetail(parseInt(b.getAttribute('data-pl'), 10))));
// Drag-reorder of the playlist cards themselves (mirrors wireSongRows).
// Only user playlists carry draggable="true"; system cards are neither
// drag sources nor drop targets, so nothing can be inserted ahead of
// them (and the server pins them first regardless).
const grid = root.querySelector('#v3-pl-grid');
if (grid) {
let dragEl = null;
grid.querySelectorAll('button[data-pl][draggable="true"]').forEach((card) => {
card.addEventListener('dragstart', () => { dragEl = card; card.classList.add('opacity-50'); });
card.addEventListener('dragend', () => { card.classList.remove('opacity-50'); });
card.addEventListener('dragover', (e) => {
e.preventDefault();
if (!dragEl || dragEl === card) return;
// Grid tiles flow leftโright then wrap, so the insert side
// is horizontal (the song rows' vertical-midpoint idiom,
// rotated); moving to another row targets that row's cards.
const rect = card.getBoundingClientRect();
const after = (e.clientX - rect.left) > rect.width / 2;
card.parentNode.insertBefore(dragEl, after ? card.nextSibling : card);
});
card.addEventListener('drop', async (e) => {
e.preventDefault();
const order = Array.from(grid.querySelectorAll('button[data-pl][draggable="true"]'))
.map((x) => parseInt(x.getAttribute('data-pl'), 10));
await jsend('POST', '/api/playlists/reorder', { order });
// Re-sync from the server: if /reorder was rejected
// (concurrent change) or the request failed, the optimistic
// DOM order would otherwise diverge from what persisted.
renderPlaylists();
});
});
}
}
async function renderPlaylistDetail(pid) {
const root = document.getElementById('v3-playlists');
if (!root) return;
const pl = await jget('/api/playlists/' + pid);
if (!pl) { renderPlaylists(); return; }
const isSystem = !!pl.system_key;
const isAlbum = pl.kind === 'album';
// Set-scoped repertoire (P6, ยง7.2): an album is a bounded practice SET
// with a denominator โ "N of M mastered", per-track accuracy, never one
// album score. Same 0.9 threshold as the library meter/green badge.
let best = {};
if (isAlbum) best = (await jget('/api/stats/best')) || {};
const slotAcc = (s) => best[s.resolved_filename || s.filename];
let meter = '';
if (isAlbum && pl.songs.length) {
const tracks = pl.songs.filter((s) => !s.missing);
const mastered = tracks.filter((s) => (slotAcc(s) || 0) >= 0.9).length;
const started = tracks.filter((s) => { const b = slotAcc(s); return typeof b === 'number' && b > 0 && b < 0.9; }).length;
const pct = tracks.length ? Math.max(0, Math.min(100, Math.round((mastered / tracks.length) * 100))) : 0;
meter =
'
Nothing saved yet. Use โSave for laterโ on a song to add it here.
') +
'
';
const listEl = root.querySelector('#v3-saved-songs');
if (listEl && pl) wireSongRows(listEl, pl.id, renderSaved);
}
// โโ Public: Save-for-later toggle for song cards/rows โโโโโโโโโโโโโโโโโ--
window.v3Saved = {
toggle: async function (filename) {
const res = await jsend('POST', '/api/saved/toggle', { filename });
return res ? res.saved : null;
},
};
window.v3Playlists = { refresh: renderPlaylists, refreshSaved: renderSaved };
// Lazy-render when these screens are shown (data can change between visits).
if (sm && typeof sm.on === 'function') {
sm.on('screen:changed', (e) => {
const id = e && e.detail && e.detail.id;
if (id === 'v3-playlists') renderPlaylists();
else if (id === 'v3-saved') renderSaved();
});
}
function boot() { renderPlaylists(); renderSaved(); }
// `defer` runs this at readyState 'interactive' โ later scripts have not
// evaluated yet, so wait for DOMContentLoaded (see static/v3/index.html).
if (document.readyState !== 'complete') document.addEventListener('DOMContentLoaded', boot, { once: true });
else boot();
})();