Up Next: a queue that plays on by itself (#473)

Playing was one episode at a time: when one ended nothing followed. Up Next
is a per-account queue on the server (table `queue`, GET and PUT
/api/queue), so the phone and the browser share it. The page adds to it from
a row or the reader, reorders it by drag or arrow keys, and plays the next
when one ends; what is playing leaves it as it starts, as Overcast's does. An
episode 90% played leaves it on the server too, which covers the phone
playing on while the page is frozen.

The iOS app is told what follows (`{t:'next'}`, gated on the app saying it
can) and starts it at the end of an episode; the page takes it up through
nowPlaying as it does the car's pick. The Swift is not compiled here.

The page stub answered every unknown address with [], whose `.entries` is
Array.prototype.entries, so the queue read a function as its list; it now
answers /api/queue as an entry list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 14:31:40 +00:00
parent 2ebe77b21e
commit c65b80a06c
24 changed files with 445 additions and 41 deletions

View File

@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Up Next: line episodes up with the list button on a row or in the reader (`q`, or `Shift Q` to play one next), move them by their handles, and each plays when the one before it ends. The player has a Next button while something is lined up, and the lock screen's next-track button does the same (#473).
- The page reads ipx's answers in protobuf, with a decoder of its own and no library, and in JSON from a server that has none; offline, a kept answer still shows what was read offline (#470).
- On a phone, back and the item's actions (read, pin, open, share) float over the text as it scrolls, so they are at hand anywhere in a long post without scrolling back to the top; pressing one there keeps your place (#456).
- Share on an episode offers Share link, Share from where you are, and Copy link, with a link to the episode's page on ipx-play that anyone can play; an episode of a private feed offers its own page in the same menu, never its file, which a paid feed signs for you, and says why there is no page anyone can play. An admin sets ipx-play up in Admin, Directory (#447, #452, #454, #455).

View File

@@ -696,6 +696,10 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
#listening .txt small .fd{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
#listening .txt small .left{flex:none;color:var(--dim)}
#listening .childrow:not(.now) .eq{display:none}
/* Up Next's handle: dragged, it takes the pointer, so the list does not scroll under the finger. */
#listening .grip{width:22px;margin-left:-4px;color:var(--faint);cursor:grab;touch-action:none}
#listening .grip svg{width:12px;height:12px}
#listening .childrow.dragging{border-color:var(--accent);cursor:grabbing}
#listening .rail{position:absolute;left:0;right:0;bottom:0;height:3px;background:var(--raise)}
#listening .rail i{display:block;height:100%;width:0;background:var(--faint);transition:width .25s linear}
#listening .now{border-color:color-mix(in srgb,var(--accent2) 60%,var(--line))}
@@ -1011,7 +1015,7 @@ body.adminpage #logbox{height:calc(100dvh - 230px);min-height:240px}
/* A table, as the original's was: unread, kept, title, feed, file, size, published. */
.ephead,.ep{
display:grid;gap:8px;align-items:center;
grid-template-columns:22px 22px minmax(120px,1fr) minmax(0,160px) 56px minmax(0,72px) minmax(0,92px) 64px;
grid-template-columns:22px 22px minmax(120px,1fr) minmax(0,160px) 56px minmax(0,72px) minmax(0,92px) 96px;
}
/* A pixel more side padding than a row's: a row has a 1px border the heading has not, and without
it every heading sat a pixel left of its column. */
@@ -1081,7 +1085,7 @@ body.playing .eq i:nth-child(3){animation-delay:-.6s}
.ep .file .dlbar{position:absolute;left:0;right:0;bottom:-5px;margin:0}
.ep .rowacts{justify-content:flex-end}
/* One feed's own table has no need of a Feed column; All Subscriptions does. */
#split.one .ephead,#split.one .ep{grid-template-columns:22px 22px minmax(120px,1fr) 56px minmax(0,72px) minmax(0,92px) 64px}
#split.one .ephead,#split.one .ep{grid-template-columns:22px 22px minmax(120px,1fr) 56px minmax(0,72px) minmax(0,92px) 96px}
#split.one .h-fd,#split.one .ep .fd{display:none}
.dot{width:3px;height:3px;border-radius:50%;background:var(--faint);flex:none}
.ep .rowacts{display:flex;gap:2px;align-items:flex-start;opacity:0;transition:opacity .12s}

View File

@@ -29,7 +29,7 @@ const WEB_VERSION = JSON.parse(fs.readFileSync(path.join(here, '..', 'package.js
// The files are one script, concatenated in this order, not modules: they share one top-level
// scope, as the single inline script did, and code that runs at load needs what came before it.
const PAGES: Record<string, { script: string, src: string[] }> = {
'index.html': { script: 'app.js', src: ['util', 'wire', 'theme', 'feeds', 'feedpage', 'items', 'player', 'dialogs', 'signals', 'gestures', 'offline', 'events', 'native'] },
'index.html': { script: 'app.js', src: ['util', 'wire', 'theme', 'feeds', 'feedpage', 'items', 'player', 'upnext', 'dialogs', 'signals', 'gestures', 'offline', 'events', 'native'] },
'admin.html': { script: 'admin.js', src: ['util', 'wire', 'theme', 'admin'] },
'login.html': { script: 'login.js', src: ['login'] },
};

View File

@@ -59,6 +59,7 @@
<button class="iconbtn" id="pback" title="Back 15 seconds (←)" aria-label="Back 15 seconds" data-icon="back"></button>
<button class="iconbtn" id="pplay" title="Play or pause (space)" aria-label="Play or pause" data-icon="play"></button>
<button class="iconbtn" id="pfwd" title="Forward 30 seconds (→)" aria-label="Forward 30 seconds" data-icon="fwd"></button>
<button class="iconbtn" id="pnext" hidden title="Play the next in Up Next" aria-label="Play the next in Up Next" data-icon="next"></button>
</div>
<div id="seekrow">
<span id="pcur">0:00</span>

View File

@@ -318,6 +318,7 @@ async function renderListed(v: {title: string, icon: string, url?: string, blurb
</div>
<div class="childlist" id="listening"></div>`;
$('#count').textContent=v.title;
if(v===VIEWS[':upnext']){ drawUpNext(); return; }
// The search box looks through these too, title and text, as it does a feed's items (#127).
await renderListening(S.q?`${v.url}&q=${encodeURIComponent(S.q)}`:v.url!,$('#listening',box),
n=>{ if(VIEWS[S.feed ?? '']===v) $('#count').textContent=`${v.title}: ${plural(n,'episode')}`; });
@@ -342,22 +343,25 @@ async function renderListening(url: string,box: HTMLElement,counted: (n: number)
function drawListening(box: HTMLElement,rows: Entry[]){
box.innerHTML=rows.length?'':S.q?`<p class="hint">Nothing you are listening to mentions “${esc(S.q)}”.</p>`
:'<p class="hint">Nothing in progress. Episodes you start and do not finish show up here.</p>';
for(const e of rows){
// Carries its episode, for paintListenRow to repaint as the player moves.
const el: HTMLDivElement & {entry?: Entry}=document.createElement('div');
el.className='childrow';
el.entry=e;
el.innerHTML=artHTML(e.image||feedArt(e.feed_id),e.title||'')+
`<div class="txt"><b>${EQ}<span>${esc(entryName(e).text)}</span></b>`+
`<small><span class="fd">${esc(feedName(e.feed_id))}</span><span class="left"></span></small></div>`+
`<button class="iconbtn" data-a="play"></button>`+
`<button class="iconbtn" data-a="remove" title="Remove from Currently Listening" aria-label="Remove from Currently Listening">${ICON.close}</button>`+
`<div class="rail"><i></i></div>`;
el.onclick=ev=>(ev.target as Element).closest('[data-a=remove]')?forget(e)
:el.classList.contains('now')&&!audio.paused?audio.pause():play(e);
paintListenRow(el);
box.appendChild(el);
}
for(const e of rows) box.appendChild(listenRow(e,'Remove from Currently Listening',()=>forget(e)));
}
/// An episode's row in Currently Listening and Up Next: its art, how far in, play, and a button
/// to take it out of the list, which `remove` does.
function listenRow(e: Entry,removeLabel: string,remove: ()=>void){
// Carries its episode, for paintListenRow to repaint as the player moves.
const el: HTMLDivElement & {entry?: Entry}=document.createElement('div');
el.className='childrow';
el.entry=e;
el.innerHTML=artHTML(e.image||feedArt(e.feed_id),e.title||'')+
`<div class="txt"><b>${EQ}<span>${esc(entryName(e).text)}</span></b>`+
`<small><span class="fd">${esc(feedName(e.feed_id))}</span><span class="left"></span></small></div>`+
`<button class="iconbtn" data-a="play"></button>`+
`<button class="iconbtn" data-a="remove" title="${removeLabel}" aria-label="${removeLabel}">${ICON.close}</button>`+
`<div class="rail"><i></i></div>`;
el.onclick=ev=>(ev.target as Element).closest('[data-a=remove]')?remove()
:el.classList.contains('now')&&!audio.paused?audio.pause():play(e);
paintListenRow(el);
return el;
}
/// One row's time left, progress and play button, taken from the player when it is the one in it.

View File

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

View File

@@ -34,6 +34,8 @@ const VIEWS: Record<string,{title: string, icon: string, url?: string, blurb?: s
':directory':{title:'Directory',icon:ICON.directory,url:'/api/directory'},
':listening':{title:'Currently Listening',icon:ICON.audio,url:'/api/entries?filter=in_progress&limit=50',
blurb:'Episodes you started and have not finished, across every feed you subscribe to. Pick one up where you left off.'},
':upnext':{title:'Up Next',icon:ICON.queue,url:'/api/queue',
blurb:'Episodes lined up to play, in order. Each one plays when the one before it ends.'},
':all':{title:'All Subscriptions',icon:ICON.all},
};
/// Whether a feed's items are in All Subscriptions, or in Signals: not when it, or the OPML or
@@ -116,7 +118,8 @@ function renderFeeds(){
el.className='place'+(S.feed===id?' sel':'');
el.tabIndex=0; el.dataset.id=id;
el.innerHTML=`<span class="ico">${v.icon}</span><b>${v.title}</b>`+(id===':all'
?`<span class="badge${unreadAll?'':' zero'}" title="${unreadAll} unread">${unreadAll>999?'999+':unreadAll}</span>`:'');
?`<span class="badge${unreadAll?'':' zero'}" title="${unreadAll} unread">${unreadAll>999?'999+':unreadAll}</span>`
:id===':upnext'&&upNext.length?`<span class="badge" title="${plural(upNext.length,'episode')}">${upNext.length}</span>`:'');
asLink(el,S.feed===id);
el.onclick=()=>{ selectFeed(id); nav(false); };
el.onpointerenter=el.ontouchstart=()=>prefetch(id);

View File

@@ -207,6 +207,7 @@ function epEl(e: Entry){
<span class="size">${enc?mb(enc.length):''}</span>
<span class="date">${dateOf(e.published)}</span>
<div class="rowacts">
${enc&&playsKind(enc)?queueButton(e):''}
${playable?`<button class="iconbtn" data-a="play" title="Play" aria-label="Play">${ICON.play}</button>`:
(enc&&!has?`<button class="iconbtn" data-a="get" title="Download this ${
enc.state==='skipped'?kindOf(enc):'file'}">${ICON.download}</button>`:'')}
@@ -439,6 +440,7 @@ function detailHtml(e: Entry){
aria-label="Mark ${e.read?'unread':'read'}" aria-pressed="${!!e.read}">${e.read?ICON.check:ICON.unread}</button>
<button class="btn ico" data-a="flag" title="${e.flagged?'Pinned: never deleted. Unpin':'Pin, so it is never deleted'}"
aria-label="${e.flagged?'Unpin':'Pin'}" aria-pressed="${!!e.flagged}">${e.flagged?ICON.pinOn:ICON.pin}</button>
${e.enclosures.some(playsKind)?queueButton(e,'btn ico'):''}
${webUrl(e.link)?`<a class="btn ico" href="${esc(webUrl(e.link))}" target="_blank" rel="noopener noreferrer"
title="Open the original" aria-label="Open the original">${ICON.open}</a>
<button class="btn ico" data-a="share" title="Share" aria-label="Share">${ICON.share}</button>`:''}</span>`;
@@ -626,6 +628,7 @@ async function epAction(a: string, e: Entry, el: HTMLElement|null, encId?: numbe
try{
if(a==='play'){ haptic('tap'); play(e, encId!=null ? enc : undefined); }
if(a==='offline' && enc) await toggleKept(enc, entryName(e).text);
if(a==='queue'||a==='playnext'){ haptic('tap'); await toggleQueued(e, a==='playnext'); }
if(a==='share') await shareEpisode(e, encId??null);
if(a==='flag'){ e.flagged=!e.flagged; await api(path+'/flags',{method:'POST',body:JSON.stringify({flagged:e.flagged})}); haptic('tap'); redraw(); }
if(a==='read'){ await setRead(e,!e.read); haptic(e.read?'done':'tap'); redraw(); }

View File

@@ -115,6 +115,14 @@ function wireDeviceSettings(){
$<HTMLButtonElement>('#sptokenclear').onclick=()=>host({t:'clearToken'});
}
/// An episode as the phone's player takes it, to play now (`load`) or after this one (`next`).
function hostItem(e: Entry|null, enc: {id: number}, url: string){
return {url, enc:enc.id, feedId:e?.feed_id ?? player.feed, guid:e?.guid ?? player.guid,
title:e ? entryName(e).text : '', feedTitle:feedName(e?.feed_id ?? player.feed),
artwork:(e && e.image) || feedArt(e?.feed_id ?? player.feed) || null,
position:(e && e.position) || 0, duration:(e && e.duration) || null};
}
function installNativePlayback(){
const post = ipxHost!;
const M = HTMLMediaElement.prototype;
@@ -165,15 +173,10 @@ function installNativePlayback(){
realPause.call(audio);
realRemoveAttribute('src');
realLoad.call(audio);
const e = player.entry, f = player.feed;
post({t:'load', url:v, enc:player.enc, feedId:f, guid:player.guid,
title:e ? entryName(e).text : '', feedTitle:feedName(f),
artwork:(e && e.image) || feedArt(f) || null,
// Where the host starts is not this: the seek to where you left off is player.ts's, on
// loadedmetadata, so one piece of code decides it. This is for the host's now-playing
// display before the file has loaded.
position:(e && e.position) || 0, duration:(e && e.duration) || null,
rate:audio.playbackRate, volume:audio.volume});
// Where the host starts is not the position in it: the seek to where you left off is
// player.ts's, on loadedmetadata, so one piece of code decides it. That is for the host's
// now-playing display before the file has loaded.
post({t:'load', ...hostItem(player.entry, {id:player.enc!}, v), rate:audio.playbackRate, volume:audio.volume});
},
});
@@ -222,6 +225,9 @@ function installNativePlayback(){
// Not moved: nothing here played it, so there is no place of the page's own to save.
player.guid=m.guid; player.feed=m.feedId; player.entry=e; player.enc=m.enc;
player.src=enc?mediaSrc(enc):undefined; player.moved=false; player.marked=false; player.saveAt=m.cur||0;
// The phone went on to the next in Up Next by itself (#473): it is under way, so out of it.
const was=upNext.find(x=>x.guid===m.guid&&x.feed_id===m.feedId);
if(was){ player.entry=e||was; startedPlaying(was); }
$('#partwrap').innerHTML=artHTML(m.artwork||feedArt(m.feedId),feedName(m.feedId));
$('#ptitle').textContent=m.title||'';
$('#pfeed').textContent=m.feedTitle||'';
@@ -262,7 +268,7 @@ function installNativePlayback(){
// Not playback's, so not gated on it: the app says what it keeps whether or not it plays.
if(m.t==='kept'||m.t==='keepFailed'){ hostKept(m); return; }
// Sent at ready, so a page newer than the app offers only what the app can do.
if(m.t==='host'){ hostCan.clear(); for(const c of m.can||[]) hostCan.add(c); paintRoute(); return; }
if(m.t==='host'){ hostCan.clear(); for(const c of m.can||[]) hostCan.add(c); paintRoute(); hostNext(); return; }
if(m.t==='sleep'||m.t==='slept'){ hostSleep(m); return; }
if(m.t==='push'){ hostPush(m); return; }
if(m.t==='appSettings'){ hostAppSettings(m); return; }

View File

@@ -85,6 +85,8 @@ function play(e: Entry,enc=e.enclosures.find(isPlayable)){
mediaSession(e,f);
player.marked=false;
paintDead();
startedPlaying(e);
hostNext();
}
const go=()=>audio.play().catch(playFailed);
if(wait) wait.then(go,playFailed); else go();
@@ -97,7 +99,7 @@ function mediaSession(e: Entry,f: Feed|undefined){
artwork:(e.image||(f&&f.image))?[{src:artSrc((e.image||f?.image)!),sizes:'512x512'}]:[],
});
const h: Record<string,()=>void>={play:()=>audio.play(),pause:()=>audio.pause(),
seekbackward:()=>audio.currentTime-=15,seekforward:()=>audio.currentTime+=30};
seekbackward:()=>audio.currentTime-=15,seekforward:()=>audio.currentTime+=30,nexttrack:playNext};
for(const k in h){ try{navigator.mediaSession.setActionHandler(k as MediaSessionAction,h[k])}catch{} }
}
audio.addEventListener('timeupdate',()=>{
@@ -136,7 +138,7 @@ function savePos(){
deadair:player.src?.includes('/deadair')?player.enc:undefined})],{type:'application/json'}));
}
audio.addEventListener('pause',savePos);
audio.addEventListener('ended',()=>{savePos();markPlayed();$<HTMLButtonElement>('#pplay').innerHTML=ICON.play});
audio.addEventListener('ended',()=>{savePos();markPlayed();$<HTMLButtonElement>('#pplay').innerHTML=ICON.play;playNext()});
// body.playing is what sets the EQ bars moving.
audio.addEventListener('play',()=>{ $<HTMLButtonElement>('#pplay').innerHTML=ICON.pause; document.body.classList.add('playing'); });
audio.addEventListener('pause',()=>{ $<HTMLButtonElement>('#pplay').innerHTML=ICON.play; document.body.classList.remove('playing'); });
@@ -175,6 +177,7 @@ audio.addEventListener('error',()=>{ if(audio.error) report('player_error',{msg:
$<HTMLButtonElement>('#pplay').onclick=()=>{haptic('tap');audio.paused?audio.play():audio.pause()};
$<HTMLButtonElement>('#pback').onclick=()=>audio.currentTime-=15;
$<HTMLButtonElement>('#pfwd').onclick=()=>audio.currentTime+=30;
$<HTMLButtonElement>('#pnext').onclick=()=>{ if(!playNext()) toast('Nothing in Up Next is ready to play.'); };
$<HTMLInputElement>('#seek').oninput=(e: Event)=>{const d=audio.duration;if(d)audio.currentTime=d*Number((e.target as HTMLInputElement).value)/1000};
$<HTMLSelectElement>('#rate').onchange=(e: Event)=>{audio.playbackRate=+(e.target as HTMLSelectElement).value;localStorage.setItem('ipx.rate',(e.target as HTMLSelectElement).value)};
/// What the app said it can do itself (`{t:'host', can}`, native.ts): empty in a browser, and in
@@ -301,7 +304,7 @@ document.addEventListener('keydown',ev=>{
// Feedly's keys, vim's j and k among them: a letter to move through items or feeds, g and a
// letter to go somewhere, ? to list them. None fire with Ctrl, Alt or Cmd held, so the browser's
// own shortcuts still work, or while a dialog is open.
const GO: Record<string,string>={a:':all',d:':directory',l:':listening'};
const GO: Record<string,string>={a:':all',d:':directory',l:':listening',u:':upnext'};
let gAt=0;
function stepEntry(by: number){
if(VIEWS[S.feed ?? '']?.url||!S.entries.length) return;
@@ -318,10 +321,12 @@ function stepFeed(by: number){
}
const KEYS: Record<string,()=>void>={
j:()=>stepEntry(1), n:()=>stepEntry(1), k:()=>stepEntry(-1), p:()=>stepEntry(-1),
J:()=>stepFeed(1), K:()=>stepFeed(-1),
J:()=>stepFeed(1), K:()=>stepFeed(-1), N:()=>$<HTMLButtonElement>('#pnext').click(),
// The toolbar's own buttons, so a key does exactly what the click does, and nothing while
// they are disabled.
o:()=>$<HTMLButtonElement>('#tbPlay').click(), m:()=>$<HTMLButtonElement>('#tbRead').click(), s:()=>$<HTMLButtonElement>('#tbFlag').click(),
o:()=>$<HTMLButtonElement>('#tbPlay').click(),
q:()=>{ const e=cur(); if(e) epAction('queue',e,null); }, Q:()=>{ const e=cur(); if(e) epAction('playnext',e,null); },
m:()=>$<HTMLButtonElement>('#tbRead').click(), s:()=>$<HTMLButtonElement>('#tbFlag').click(),
v:()=>{ const u=webUrl(cur()?.link); if(u) window.open(u,'_blank','noopener'); },
A:()=>$('#content .fhead [data-a="read"], #content .fhead [data-a="readall"]')?.click(),
r:async()=>{ await loadFeeds(true); if(S.feed){ renderFeed(); loadEntries(); } },
@@ -343,17 +348,17 @@ function keysModal(){
const rows=[
['Go to'],
[g('a'),'All Subscriptions'],[g('d'),'Directory'],
[g('l'),'Currently Listening'],[g('s'),'Settings'],
[g('u'),'Up Next'],[g('l'),'Currently Listening'],[g('s'),'Settings'],
[k('Shift')+' '+k('J'),'Next feed'],[k('Shift')+' '+k('K'),'Previous feed'],
[k('/'),'Search items, Currently Listening or the Directory'],[k('r'),'Refresh'],[k('['),'Show or hide the feed list'],
['Items'],
[k('j')+' or '+k('n'),'Next item'],[k('k')+' or '+k('p'),'Previous item'],
[k('Shift')+' '+k('A'),'Mark all read'],
['The selected item'],
[k('o'),'Play it'],[k('m'),'Mark it read or unread'],[k('s'),'Pin it, or unpin it'],
[k('o'),'Play it'],[k('q'),'Add it to Up Next, or take it out'],[k('Shift')+' '+k('Q'),'Play it next'],[k('m'),'Mark it read or unread'],[k('s'),'Pin it, or unpin it'],
[k('v'),'Open the original in a new tab'],
['The player'],
[k('Space'),'Play or pause'],[k('←')+' '+k('→'),'Back 15 seconds, forward 30'],
[k('Space'),'Play or pause'],[k('←')+' '+k('→'),'Back 15 seconds, forward 30'],[k('Shift')+' '+k('N'),'Play the next in Up Next'],
['Anywhere'],
[k('?'),'This list'],[k('Esc'),'Close a dialog'],
];

121
web/src/upnext.ts Normal file
View File

@@ -0,0 +1,121 @@
/* ---------------- Up Next ---------------- */
/// Up Next (#473): the episodes lined up to play, kept on the server so the phone and the browser
/// share one. What is playing is not in it: an episode leaves Up Next as it starts, as Overcast's
/// does, so the first one in it is always the one that follows.
let upNext: Entry[]=[];
/// The next one in the list that can play now, the one playing aside. One not downloaded yet is
/// passed over, to wait in the list until it is.
const nextUp=(list: Entry[], playing: string|null)=>list.find(e=>entryKey(e)!==playing&&e.enclosures.some(isPlayable));
const queued=(e: Entry)=>upNext.some(x=>entryKey(x)===entryKey(e));
function loadUpNext(){
api('/api/queue').then((r: ListPage)=>{ upNext=r.entries; upNextChanged(); }).catch(()=>{});
}
/// Saves Up Next in this order and takes the server's answer, which leaves out what was not
/// yours to queue. Drawn at once from what was asked, so a drag lands where it was dropped.
async function saveUpNext(list: Entry[]){
upNext=list; upNextChanged();
try{
const r: ListPage=await api('/api/queue',{method:'PUT',body:JSON.stringify(list.map(e=>({feed_id:e.feed_id,guid:e.guid})))});
upNext=r.entries;
}catch(err){ toast(why(err),true); loadUpNext(); return; }
upNextChanged();
}
function upNextChanged(){
renderFeeds();
if(S.feed===':upnext') drawUpNext();
// The rows' and the reader's buttons say whether each is in it.
for(const b of $$<HTMLButtonElement>('[data-a=queue]')) paintQueueButton(b);
hostNext();
}
/// Adds an episode at the end, or first with `next`, or takes it out if it is in already and
/// neither was asked. A file still on the feed's server is fetched now, so it is here by its turn.
async function toggleQueued(e: Entry, next=false){
const rest=upNext.filter(x=>entryKey(x)!==entryKey(e));
if(queued(e)&&!next){ await saveUpNext(rest); toast('Removed from Up Next'); return; }
const enc=e.enclosures.find(isPlayable)||e.enclosures.find(playsKind);
if(!enc){ toast('There is nothing to play in this item.',true); return; }
await saveUpNext(next?[e,...rest]:[...rest,e]);
if(!enc.path){
await api(`/api/enclosures/${enc.id}/download`,{method:'POST'}).catch(()=>{});
enc.state='pending';
}
toast((next?'Plays next':'Added to Up Next')+(enc.path?'':'. Downloading it first.'));
}
function paintQueueButton(b: HTMLButtonElement){
const key=b.dataset.key, on=!!key&&upNext.some(x=>entryKey(x)===key);
const label=on?'Remove from Up Next':'Add to Up Next';
b.setAttribute('aria-pressed',String(on)); b.title=label; b.setAttribute('aria-label',label);
b.innerHTML=on?ICON.queued:ICON.queue;
}
/// The toggle on a row or in the reader, drawn with its state.
const queueButton=(e: Entry,cls='iconbtn')=>`<button class="${cls}" data-a="queue" data-key="${esc(entryKey(e))}" aria-pressed="${queued(e)}"
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.
function playNext(){
const e=nextUp(upNext,player.guid?player.feed+'\n'+player.guid:null);
if(e) play(e);
return !!e;
}
/// Playing takes an episode out of Up Next: it is under way, and Currently Listening has it now.
function startedPlaying(e: Entry){
if(queued(e)) saveUpNext(upNext.filter(x=>entryKey(x)!==entryKey(e)));
}
/// 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);
$<HTMLButtonElement>('#pnext').hidden=!next;
try{
if(!ipxHost||!hostCan.has('next')) return;
const e=next, enc=e?.enclosures.find(isPlayable);
ipxHost(e&&enc?{t:'next',...hostItem(e,enc,mediaSrc(enc))}:{t:'next'});
}catch{}
}
/// Up Next's place: the list, a handle on each row to drag it up or down (or its arrow keys),
/// and a button to take it out.
function drawUpNext(){
const box=$('#listening'); if(!box) return;
$('#count').textContent=`Up Next: ${plural(upNext.length,'episode')}`;
box.innerHTML=upNext.length?'':'<p class="hint">Nothing lined up. Add an episode with its Up Next button, and it plays when the one before it ends.</p>';
for(const e of upNext){
const el=listenRow(e,'Remove from Up Next',()=>saveUpNext(upNext.filter(x=>entryKey(x)!==entryKey(e))));
el.insertAdjacentHTML('afterbegin',`<button class="iconbtn grip" title="Drag to move, or use the arrow keys" aria-label="Move ${esc(entryName(e).text)}">${ICON.grip}</button>`);
box.appendChild(el);
}
for(const g of $$<HTMLButtonElement>('.grip',box)) grip(g,box);
}
/// One row's handle. A drag moves the row among the others as the pointer goes, and saves where
/// it is let go; Up and Down move it one place, for a keyboard.
function grip(g: HTMLButtonElement,box: HTMLElement){
const row=g.closest<HTMLElement>('.childrow')!;
const save=()=>{
const list=$$<HTMLElement & {entry?: Entry}>('.childrow',box).map(r=>r.entry!);
if(list.some((e,i)=>e!==upNext[i])) saveUpNext(list);
};
g.onclick=ev=>ev.stopPropagation();
g.onkeydown=ev=>{
const [up,down]=[row.previousElementSibling,row.nextElementSibling];
if(ev.key==='ArrowUp'&&up) box.insertBefore(row,up);
else if(ev.key==='ArrowDown'&&down) box.insertBefore(down,row);
else return;
ev.preventDefault(); g.focus(); save();
};
g.onpointerdown=ev=>{
ev.preventDefault(); ev.stopPropagation();
g.setPointerCapture(ev.pointerId);
row.classList.add('dragging');
g.onpointermove=m=>{
const over=$$<HTMLElement>('.childrow',box).find(r=>r!==row&&m.clientY<r.getBoundingClientRect().bottom);
if(over&&m.clientY>over.getBoundingClientRect().top+over.offsetHeight/2) box.insertBefore(row,over.nextElementSibling);
else if(over) box.insertBefore(row,over);
else box.appendChild(row);
};
g.onpointerup=g.onpointercancel=()=>{ g.onpointermove=null; row.classList.remove('dragging'); save(); };
};
}

View File

@@ -90,6 +90,12 @@ const ICON: Record<string,string>={
left:fa('0 0 512 512','<path fill="currentColor" d="M9.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 288 480 288c17.7 0 32-14.3 32-32s-14.3-32-32-32l-370.7 0 105.4-105.4c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/>'), // solid/arrow-left
// Drawn here: Font Awesome's free set has no AirPlay. A screen with a triangle under it, as Apple's.
airplay:fa('0 0 512 512','<path fill="currentColor" d="M64 48l384 0c26.5 0 48 21.5 48 48l0 256c0 26.5-21.5 48-48 48l-56 0 0-56 48 0 0-240-368 0 0 240 48 0 0 56-56 0c-26.5 0-48-21.5-48-48L16 96c0-26.5 21.5-48 48-48zM256 288l144 176-288 0z"/>'),
// Up Next (#473): a list, with a plus to add to it or a tick once in it, the state in the
// shape. Drawn here, so the two are the same list and differ only in that mark.
queue:fa('0 0 512 512','<path fill="currentColor" d="M32 96a32 32 0 0 1 32-32h384a32 32 0 0 1 0 64H64a32 32 0 0 1-32-32zm0 160a32 32 0 0 1 32-32h384a32 32 0 0 1 0 64H64a32 32 0 0 1-32-32zm32 128h160a32 32 0 0 1 0 64H64a32 32 0 0 1 0-64zm320-64a32 32 0 0 1 32 32v48h48a32 32 0 0 1 0 64h-48v48a32 32 0 0 1-64 0v-48h-48a32 32 0 0 1 0-64h48v-48a32 32 0 0 1 32-32z"/>'),
queued:fa('0 0 512 512','<path fill="currentColor" d="M32 96a32 32 0 0 1 32-32h384a32 32 0 0 1 0 64H64a32 32 0 0 1-32-32zm0 160a32 32 0 0 1 32-32h384a32 32 0 0 1 0 64H64a32 32 0 0 1-32-32zm32 128h160a32 32 0 0 1 0 64H64a32 32 0 0 1 0-64z"/><path fill="none" stroke="currentColor" stroke-width="60" stroke-linecap="round" stroke-linejoin="round" d="M300 404l54 54 116-116"/>'),
next:fa('0 0 320 512','<path fill="currentColor" d="M52.5 440.6c-9.5 7.9-22.8 9.7-34.1 4.4S0 428.4 0 416V96c0-12.4 7.2-23.7 18.4-29s24.5-3.6 34.1 4.4l192 160L256 241V96c0-17.7 14.3-32 32-32s32 14.3 32 32v320c0 17.7-14.3 32-32 32s-32-14.3-32-32V271l-11.5 9.6-192 160z"/>'),
grip:fa('0 0 320 512','<path fill="currentColor" d="M40 352a40 40 0 1 1 0 80 40 40 0 1 1 0-80zm240 0a40 40 0 1 1 0 80 40 40 0 1 1 0-80zM40 216a40 40 0 1 1 0 80 40 40 0 1 1 0-80zm240 0a40 40 0 1 1 0 80 40 40 0 1 1 0-80zM40 80a40 40 0 1 1 0 80 40 40 0 1 1 0-80zm240 0a40 40 0 1 1 0 80 40 40 0 1 1 0-80z"/>'),
subbed:fa('0 0 512 512','<path fill="currentColor" d="M256 512a256 256 0 1 1 0-512 256 256 0 1 1 0 512zM374 145.7c-10.7-7.8-25.7-5.4-33.5 5.3L221.1 315.2 169 263.1c-9.4-9.4-24.6-9.4-33.9 0s-9.4 24.6 0 33.9l72 72c5 5 11.8 7.5 18.8 7s13.4-4.1 17.5-9.8L379.3 179.2c7.8-10.7 5.4-25.7-5.3-33.5z"/>'), // solid/circle-check
};
// What is playing, as the icon's EQ bars; the stylesheet moves them.