Smart playlists (#476)

A playlist is the episodes of the podcasts chosen, those set to play first
ahead of the rest, newest or oldest first, unplayed only or all, kept up to
date by itself (table `playlists`, /api/playlists). It sits in a folder of its
own in the feed list, as Signals do. Played from one, an episode goes on to
the playlist's next once Up Next has nothing.

The priority ids are written into the ORDER BY, which the page query uses
twice, so they are quoted there rather than bound; they are also only ever
feed ids this person subscribes to.

The folder row first borrowed Signals' `sigs` class, which the tests use to
mean Signals' folder; four Signals tests failed until it had its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 14:54:19 +00:00
parent 2faca684da
commit 02ee6d74c1
17 changed files with 540 additions and 11 deletions

View File

@@ -139,3 +139,4 @@ function offerReload(){
connect();
loadFeeds().then(preloadLists).catch(()=>{});
loadUpNext();
loadPlaylists();

View File

@@ -23,6 +23,9 @@ function renderFeed(){
const v=VIEWS[S.feed ?? ''];
if(v&&v.url) return renderListed(v);
if(S.feed===SIGNALS) return renderSignals();
if(S.feed===PLAYLISTS) return renderPlaylists();
const pl=playlistOf(S.feed);
if(pl) return renderPlaylist(pl);
const f=v?null:S.feeds.find(x=>x.id===S.feed);
const sg=signalOf(S.feed);
$<HTMLButtonElement>('#tbRemove').disabled=!f;

View File

@@ -20,7 +20,7 @@ async function loadFeeds(keepSel?: boolean){
// All Subscriptions rather than picking one alphabetically. Nothing to land on at all (a
// brand new account) leaves S.feed alone, so the empty state's own message shows instead.
if(!keepSel && S.feeds.length){
const known = S.feed && (VIEWS[S.feed] || S.feed===SIGNALS || signalOf(S.feed) || S.feeds.some(f=>f.id===S.feed));
const known = S.feed && (VIEWS[S.feed] || S.feed===SIGNALS || signalOf(S.feed) || S.feed===PLAYLISTS || playlistOf(S.feed) || S.feeds.some(f=>f.id===S.feed));
selectFeed(known ? S.feed! : ':all');
}
}
@@ -129,6 +129,7 @@ function renderFeeds(){
}
list.appendChild(places);
signalFolder(list,q);
playlistFolder(list,q);
const shown=S.feeds.filter(f=>!q||(f.title||f.id).toLowerCase().includes(q));
if(!shown.length){ list.insertAdjacentHTML('beforeend','<p class="empty" style="padding:20px 8px">No feeds.</p>'); return done(); }

View File

@@ -78,7 +78,7 @@ function preloadLists(){
/// `quiet` for a refresh nobody asked for (a live update): not a wait anyone sees, so not timed.
async function loadEntries(append?: boolean, quiet?: boolean){
// The Directory lists feeds, and Currently Listening draws its own episodes.
if(!S.feed || VIEWS[S.feed]?.url || S.feed===SIGNALS) return;
if(!S.feed || VIEWS[S.feed]?.url || S.feed===SIGNALS || S.feed===PLAYLISTS || playlistOf(S.feed)) return;
const feed=S.feed, key=listKey(feed), asked=performance.now(), seq=++loadSeq;
// From asking to the list drawn: what someone waits for after a click, under that click's trace
// (#246). Once, when the list first shows: from what is kept, at once.

View File

@@ -72,6 +72,7 @@ function play(e: Entry,enc=e.enclosures.find(isPlayable)){
let wait: Promise<void>|null=null;
if(!resuming){
player.guid=e.guid; player.feed=e.feed_id; player.entry=e; player.enc=enc.id; player.moved=false;
playingFrom=null;
document.body.classList.toggle('has-video', kindOf(enc)==='video');
wait=setSrc(player.src=mediaSrc(enc));
audio.currentTime=0;

163
web/src/playlists.ts Normal file
View File

@@ -0,0 +1,163 @@
/* ---------------- smart playlists ---------------- */
/// Smart playlists (#476): the episodes of the podcasts chosen, those marked to play first ahead of
/// the rest, newest or oldest first, unplayed only or all. A playlist is a place, `:playlist:<id>`,
/// in a folder of their own in the feed list, as Signals are.
const PLAYLISTS=':playlists';
let playlists: Playlist[]=[];
/// The playlist the episode playing was started from, which goes on to its next when it ends, once
/// Up Next has nothing.
let playingFrom: Entry[]|null=null;
function playlistOf(view: string|null){
const m=/^:playlist:(\d+)$/.exec(view||'');
return m ? playlists.find(p=>p.id===Number(m[1])) : undefined;
}
function loadPlaylists(){
return api('/api/playlists').then((r: Playlist[])=>{ playlists=r; renderFeeds(); }).catch(()=>{});
}
/// The playlist's own art: its podcasts' artwork, four together, as a folder's is.
const playlistArt=(p: Playlist)=>folderArt({id:'',title:p.name,image:null} as Feed,S.feeds.filter(f=>p.feeds.includes(f.id)));
function playlistFolder(list: HTMLElement, q: string){
const mine=playlists.filter(p=>!q||p.name.toLowerCase().includes(q));
if(q&&!mine.length) return;
const open=expanded.has(PLAYLISTS)||!!q;
list.appendChild(feedRow(PLAYLISTS,'plists',
`<button class="chev" aria-expanded="${open}" title="Show or hide your playlists" aria-label="Show or hide your playlists">${ICON.caret}</button>`+
`<span class="fart"><div class="art">${ICON.queue}</div></span><div class="txt"><b>Playlists</b><small>${playlists.length?plural(playlists.length,'playlist'):'Episodes from the podcasts you choose'}</small></div>`,
()=>selectFeed(PLAYLISTS)));
$('.chev',list.lastElementChild!).onclick=(ev: Event)=>{ ev.stopPropagation(); toggleGroup(PLAYLISTS); };
if(!open) return;
for(const p of mine)
list.appendChild(feedRow(':playlist:'+p.id,'child',
`<span class="fart">${playlistArt(p)}</span><div class="txt"><b>${esc(p.name)}</b><small>${plural(p.feeds.length,'podcast')}</small></div>`+badgeHTML(p.items),
()=>selectFeed(':playlist:'+p.id)));
}
/// The folder's page: every playlist, and New playlist.
function renderPlaylists(){
$('#count').textContent=`Playlists: ${plural(playlists.length,'playlist')}`;
$<HTMLButtonElement>('#tbRemove').disabled=true;
syncTools(null);
const box=$('#content');
box.classList.add('plain');
box.innerHTML=`
<div class="fhead slim">
<div class="art">${ICON.queue}</div>
<div class="meta"><h2>Playlists</h2><div class="sub">Episodes from the podcasts you choose, kept up to date as new ones come.</div></div>
<div class="acts"><button class="btn ico" data-a="new" title="New playlist" aria-label="New playlist">${ICON.plus}</button></div>
</div>
<div class="childlist" id="plists"></div>`;
$<HTMLButtonElement>('#content .acts [data-a="new"]').onclick=()=>playlistModal();
const list=$('#plists');
if(!playlists.length){ list.innerHTML='<p class="empty">No playlists yet. Make one from the podcasts you want to hear in a row.</p>'; return; }
for(const p of playlists){
const el=document.createElement('div');
el.className='childrow';
el.innerHTML=playlistArt(p)+`<div class="txt"><b>${esc(p.name)}</b><small class="meta">${plural(p.feeds.length,'podcast')}</small></div>`+badgeHTML(p.items);
el.onclick=()=>selectFeed(':playlist:'+p.id);
list.appendChild(el);
}
}
/// A playlist's page: its episodes in its order. Play goes on through it; the cross marks one
/// played, which takes it out of an unplayed-only playlist.
async function renderPlaylist(p: Playlist){
$<HTMLButtonElement>('#tbRemove').disabled=true;
syncTools(null);
const box=$('#content');
box.classList.add('plain');
const how=[p.only_unplayed?'Unplayed episodes':'Every episode',p.oldest_first?'oldest first':'newest first',
p.priority.length?`${plural(p.priority.length,'podcast')} first`:''].filter(Boolean).join(', ');
box.innerHTML=`
<div class="fhead slim">
${playlistArt(p)}
<div class="meta"><h2>${esc(p.name)}</h2><div class="sub">${how}, from ${plural(p.feeds.length,'podcast')}</div></div>
<div class="acts">
<button class="btn ico" data-a="edit" title="Edit this playlist" aria-label="Edit this playlist">${ICON.settings}</button>
<button class="btn ico danger" data-a="rm" title="Delete this playlist" aria-label="Delete this playlist">${ICON.trash}</button>
</div>
</div>
<div class="childlist" id="listening"></div>`;
$<HTMLButtonElement>('#content .acts [data-a="edit"]').onclick=()=>playlistModal(p);
$<HTMLButtonElement>('#content .acts [data-a="rm"]').onclick=async()=>{
if(!await ask(`Delete the playlist ${p.name}? Its episodes stay in their podcasts.`,'Delete')) return;
try{ await api(`/api/playlists/${p.id}`,{method:'DELETE'}); toast('Deleted'); await loadPlaylists(); selectFeed(PLAYLISTS); }
catch(e){ toast(why(e),true); }
};
const list=$('#listening');
listLoading(list);
let rows: Entry[];
// shortcut: the first 200 only, with no Load more; page it as feeds do if a playlist is listened
// through that far.
try{ rows=(await api(`/api/playlists/${p.id}/entries?limit=200`) as ListPage).entries; }
catch(e){ list.innerHTML=`<p class="hint">${esc(why(e))}</p>`; return; }
if(!list.isConnected) return;
$('#count').textContent=`${p.name}: ${plural(p.items,'episode')}`;
list.innerHTML=rows.length?'':'<p class="hint">Nothing here yet. Episodes show up as your podcasts publish them.</p>';
for(const e of rows){
const el=listenRow(e,'Mark played',async()=>{ try{ await setRead(e,true); }catch(err){ toast(why(err),true); } renderPlaylist(p); loadPlaylists(); });
el.onclick=ev=>{
if((ev.target as Element).closest('[data-a=remove]')) return;
if(el.classList.contains('now')&&!audio.paused){ audio.pause(); return; }
playFrom(rows,e);
};
list.appendChild(el);
}
}
/// Plays an episode of a list that goes on to the list's next.
function playFrom(list: Entry[],e: Entry){
play(e);
// After play, which forgets the list it came from, and has painted Next and told the phone
// what follows without it.
if(inPlayer(e)){ playingFrom=list; hostNext(); }
}
/// The next in the playlist after the one playing, if it was started from one.
function nextInPlaylist(){
if(!playingFrom) return undefined;
const i=playingFrom.findIndex(inPlayer);
return i<0 ? undefined : nextUp(playingFrom.slice(i+1),null);
}
/// Making a playlist, or changing one: a name, the podcasts in it and which play first, and which
/// of their episodes.
function playlistModal(p?: Playlist){
const shows=S.feeds.filter(f=>f.podcast);
const row=(f: Feed)=>{
const id=esc(f.id), inIt=!!p?.feeds.includes(f.id), first=!!p?.priority.includes(f.id);
return `<div class="plshow">${artHTML(f.image,f.title||f.id)}
<label class="check"><input type="checkbox" data-in="${id}"${inIt?' checked':''}> ${esc(f.title||f.id)}</label>
<label class="check first"><input type="checkbox" data-first="${id}"${first?' checked':''}${inIt?'':' disabled'}> Play first</label></div>`;
};
openModal(`<h3>${p?'Edit playlist':'New playlist'}</h3>
<div class="field"><label for="plname">Name</label>
<input type="text" id="plname" value="${esc(p?.name||'')}" placeholder="Morning commute"></div>
<div class="field"><label>Podcasts</label>
${shows.length?`<div class="plshows">${shows.map(row).join('')}</div>`:'<p class="hint">Subscribe to a podcast first.</p>'}
<span class="hint">Episodes of those set to play first come before the rest.</span></div>
<div class="field">
<label class="check"><input type="checkbox" id="plunplayed"${p?.only_unplayed??true?' checked':''}> Only episodes you have not played</label>
<label class="check"><input type="checkbox" id="ploldest"${p?.oldest_first?' checked':''}> Oldest first</label></div>
<div class="cardacts"><button class="btn ico" onclick="closeModal()" title="Cancel" aria-label="Cancel">${ICON.close}</button>
<button class="btn ico primary" id="plsave" title="${p?'Save':'Make playlist'}" aria-label="${p?'Save':'Make playlist'}">${p?ICON.check:ICON.plus}</button></div>`);
// Play first means something only for a podcast in the playlist.
for(const box of $$<HTMLInputElement>('[data-in]')) box.onchange=()=>{
const first=$<HTMLInputElement>(`[data-first="${CSS.escape(box.dataset.in!)}"]`);
first.disabled=!box.checked; if(!box.checked) first.checked=false;
};
$<HTMLInputElement>('#plname').focus();
$<HTMLButtonElement>('#plsave').onclick=async()=>{
const name=$<HTMLInputElement>('#plname').value.trim();
const feeds=$$<HTMLInputElement>('[data-in]').filter(b=>b.checked).map(b=>b.dataset.in!);
if(!name){ $<HTMLInputElement>('#plname').focus(); return; }
if(!feeds.length){ toast('Choose at least one podcast.',true); return; }
const body=JSON.stringify({name,feeds,priority:$$<HTMLInputElement>('[data-first]').filter(b=>b.checked).map(b=>b.dataset.first!),
only_unplayed:$<HTMLInputElement>('#plunplayed').checked,oldest_first:$<HTMLInputElement>('#ploldest').checked});
try{
const r=p ? await api(`/api/playlists/${p.id}`,{method:'PATCH',body}) : await api('/api/playlists',{method:'POST',body});
closeModal(); toast(p?'Saved':'Playlist made');
if(!expanded.has(PLAYLISTS)) toggleGroup(PLAYLISTS);
await loadPlaylists(); selectFeed(':playlist:'+(p?p.id:r.id));
}catch(e){ toast(why(e),true); }
};
}

View File

@@ -148,6 +148,18 @@ interface State {
sort: {col: string, dir: 'asc' | 'desc'};
}
/// A smart playlist, `/api/playlists` (db.rs PlaylistRow, #476).
interface Playlist {
id: number;
name: string;
feeds: string[];
priority: string[];
only_unplayed: boolean;
oldest_first: boolean;
/** How many episodes it holds now. */
items: number;
}
/// An account, `/api/users` (web.rs list_users).
interface Account {
id: number;

View File

@@ -56,10 +56,13 @@ const queueButton=(e: Entry,cls='iconbtn')=>`<button class="${cls}" data-a="queu
title="${queued(e)?'Remove from Up Next':'Add to Up Next'}" aria-label="${queued(e)?'Remove from Up Next':'Add to Up Next'}">${queued(e)?ICON.queued:ICON.queue}</button>`;
/// What plays after this one ends, or the next button is pressed.
/// Up Next first; with nothing in it, the next in the playlist the one playing came from.
function playNext(){
const e=nextUp(upNext,player.guid?player.feed+'\n'+player.guid:null);
if(e) play(e);
return !!e;
if(e){ play(e); return true; }
const n=nextInPlaylist();
if(n&&playingFrom){ playFrom(playingFrom,n); return true; }
return false;
}
/// Playing takes an episode out of Up Next: it is under way, and Currently Listening has it now.
function startedPlaying(e: Entry){
@@ -69,7 +72,7 @@ function startedPlaying(e: Entry){
/// The phone's player is told what follows (#473), so with the screen locked, when the page is
/// frozen and cannot answer the end of an episode, it goes on to the next by itself.
function hostNext(){
const next=nextUp(upNext,player.guid?player.feed+'\n'+player.guid:null);
const next=nextUp(upNext,player.guid?player.feed+'\n'+player.guid:null)??nextInPlaylist();
$<HTMLButtonElement>('#pnext').hidden=!next;
try{
if(!ipxHost||!hostCan.has('next')) return;