diff --git a/docs/development.md b/docs/development.md index b073bc3..146567e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -61,6 +61,8 @@ retention and administrator actions: ```bash node --test tests/podcasts.test.cjs +FURU_PODCAST_RENDER_FIXTURE=1 cargo test renders_podcast_navigation_and_views +node tests/browser-podcast-ui.cjs FURU_PODCAST_TEST_DATABASE_URL=postgresql://... cargo test podcasts -- --include-ignored FURU_PODCAST_TEST_DATABASE_URL=postgresql://... cargo test admin_unicode_search -- --include-ignored ``` @@ -72,6 +74,12 @@ offline unsubscribe replay, legacy-peer filtering, and private Unicode search. T admin fixture exercises list counts, all three catalogue lists and the track picker with Cyrillic and Greek searches. Use a PostgreSQL build with ICU support; running these fixtures on a database created with locale `C` covers the locale regression. +The browser UI fixture checks direct list/detail hashes on first load and reload, +back navigation, RSS artwork and broken-image fallbacks, explicit subscriptions, +compact search cards and mobile layout. It uses isolated API fixtures with the +rendered application. Set `PLAYWRIGHT_MODULE` and `CHROME_PATH` as for the other +browser tests. Optional `ALPINE_FIXTURE` points to a local Alpine.js bundle for +offline browser runs; otherwise the page loads Alpine from its normal CDN. The access regression suite uses a disposable migrated database and a local OIDC provider with signed tokens and PKCE: diff --git a/src/federation/mod.rs b/src/federation/mod.rs index 2ce9ddc..bb2cce6 100644 --- a/src/federation/mod.rs +++ b/src/federation/mod.rs @@ -722,7 +722,7 @@ impl Federation { .map(|r| Arc::clone(&r.podcast_dht)) .context("federation is not running")?; let hits = overlay.search(query, 100).await?; - Ok(Value::Array(hits.into_iter().map(|hit| json!({"id":hit.podcast_id,"url":hit.feed_url,"metadata":{"title":hit.card.title,"author":hit.card.author,"description":hit.card.description}})).collect())) + Ok(Value::Array(hits.into_iter().map(|hit| json!({"id":hit.podcast_id,"url":hit.feed_url,"metadata":{"title":hit.card.title,"author":hit.card.author,"description":hit.card.description,"image_url":hit.card.image_url}})).collect())) } async fn similarity_services(&self) -> Result<(Arc, Arc)> { diff --git a/src/podcasts/tests.rs b/src/podcasts/tests.rs index bff7971..d6a2eb2 100644 --- a/src/podcasts/tests.rs +++ b/src/podcasts/tests.rs @@ -33,6 +33,11 @@ fn renders_podcast_navigation_and_views() { 2 ); assert!(html.contains("/api/podcasts/action")); + assert!( + html.find("Alpine.store('podcasts',").unwrap() + < html.find("Alpine.store('library',").unwrap(), + "podcast navigation must be registered before library.init restores the hash" + ); if std::env::var_os("FURU_PODCAST_RENDER_FIXTURE").is_some() { std::fs::write("target/podcast-player-fixture.html", html).unwrap(); } @@ -187,6 +192,22 @@ async fn postgres_multiuser_progress_retention_and_admin() { 1 ); let request = |value| serde_json::from_value::(value).unwrap(); + let preview = action( + pool.clone(), + config.clone(), + 99, + false, + request(json!({"action":"detail","id":podcast})), + ) + .await + .unwrap(); + assert_eq!(preview["subscribed"], false); + let count: i64 = + sqlx::query_scalar("SELECT count(*) FROM furumusic__podcast_subscription WHERE user_id=99") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(count, 0); action( pool.clone(), config.clone(), @@ -196,6 +217,18 @@ async fn postgres_multiuser_progress_retention_and_admin() { ) .await .unwrap(); + assert!( + action( + pool.clone(), + config.clone(), + 99, + false, + request(json!({"action":"detail","id":podcast})) + ) + .await + .is_err(), + "private podcasts must not be exposed by the detail route" + ); assert_eq!( list(&pool, 2, false).await.unwrap()["mine"] .as_array() diff --git a/src/podcasts/web.rs b/src/podcasts/web.rs index c7a3dd2..82cf70e 100644 --- a/src/podcasts/web.rs +++ b/src/podcasts/web.rs @@ -104,17 +104,22 @@ async fn action( } match body.action.as_str() { "list" => return list(&pool, user, false).await, + "detail" => { + let detail:Option=sqlx::query_scalar("SELECT jsonb_build_object('id',p.id,'url',p.origin_url,'metadata',p.metadata,'subscribed',EXISTS(SELECT 1 FROM furumusic__podcast_subscription s WHERE s.user_id=$1 AND s.podcast_id=p.id),'episodes',(SELECT count(*) FROM furumusic__podcast_episode e WHERE e.podcast_id=p.id)) FROM furumusic__podcast p WHERE p.id=$2 AND EXISTS(SELECT 1 FROM furumusic__podcast_subscription s WHERE s.podcast_id=p.id AND (s.user_id=$1 OR s.shared))").bind(user).bind(&body.id).fetch_optional(&pool).await?; + return detail.context("podcast not found"); + } "admin_list" => return list(&pool, user, true).await, "add" => { let id = subscribe(&pool, user, &body.url).await?; sync::ensure_subscribed(&pool, user, &id).await?; sync::seed_user(&pool, user).await?; let checked = refresh(&pool, &id).await; + let download_id = id.clone(); tokio::spawn(async move { - let _ = download_pending(&pool, &config, Some(&id)).await; + let _ = download_pending(&pool, &config, Some(&download_id)).await; }); return Ok( - json!({"ok":true,"warning":checked.err().map(|_| "Feed check failed; the subscription was saved") }), + json!({"ok":true,"id":id,"warning":checked.err().map(|_| "Feed check failed; the subscription was saved") }), ); } "remove" => { diff --git a/templates/player.html b/templates/player.html index 158f87b..648494b 100644 --- a/templates/player.html +++ b/templates/player.html @@ -4,11 +4,12 @@ {% block head_extra %} {% include "player/styles.html" %} +{% include "player/podcast_styles.html" %} {% endblock head_extra %} {% block body %} {% include "player/shell.html" %} {% include "player/modals.html" %} -{% include "player/scripts.html" %} {% include "player/podcast_scripts.html" %} +{% include "player/scripts.html" %} {% endblock body %} diff --git a/templates/player/podcast_artwork.html b/templates/player/podcast_artwork.html new file mode 100644 index 0000000..a0e0c75 --- /dev/null +++ b/templates/player/podcast_artwork.html @@ -0,0 +1,23 @@ + + diff --git a/templates/player/podcast_card.html b/templates/player/podcast_card.html new file mode 100644 index 0000000..bd29c22 --- /dev/null +++ b/templates/player/podcast_card.html @@ -0,0 +1,18 @@ + diff --git a/templates/player/podcast_episodes.html b/templates/player/podcast_episodes.html new file mode 100644 index 0000000..86ea81a --- /dev/null +++ b/templates/player/podcast_episodes.html @@ -0,0 +1,61 @@ +

+
+ +
+

+ diff --git a/templates/player/podcast_scripts.html b/templates/player/podcast_scripts.html index 39d5f24..43f92cd 100644 --- a/templates/player/podcast_scripts.html +++ b/templates/player/podcast_scripts.html @@ -2,11 +2,19 @@ document.addEventListener('alpine:init', () => { const labels = { podcasts: ['Podcasts', 'Подкасты'], + episodes: ['Episodes', 'Выпуски'], + subscribeHint: [ + 'Subscribe to listen and save episodes.', + 'Подпишитесь, чтобы слушать и сохранять выпуски.', + ], + notFound: ['Podcast not found.', 'Подкаст не найден.'], + showMore: ['Show more', 'Подробнее'], + showLess: ['Show less', 'Свернуть'], add: ['Add', 'Добавить'], mine: ['My podcasts', 'Мои подкасты'], public: ['Public podcasts', 'Публичные подкасты'], - results: ['Podcast search results','Результаты поиска подкастов'], - noMatches: ['No matching podcasts.','Подходящих подкастов нет.'], + results: ['Podcast search results', 'Результаты поиска подкастов'], + noMatches: ['No matching podcasts.', 'Подходящих подкастов нет.'], empty: ['Add an RSS or Atom feed.', 'Добавьте RSS или Atom ленту.'], check: ['Check episodes', 'Проверить выпуски'], checkAll: ['Check all', 'Проверить все'], @@ -65,6 +73,12 @@ episodes: [], hasMore: false, selected: null, + selectedId: null, + loading: false, + adding: false, + failedArtwork: {}, + descriptionExpanded: false, + _navigation: 0, url: '', query: '', filter: '', @@ -105,32 +119,77 @@ }, async load() { const data = await this.api('list'); - this.mine = data.mine; + this.mine = data.mine.map((pod) => ({ ...pod, subscribed: true })); this.public = data.public; + if (this.selected) { + const current = + this.mine.find((p) => p.id === this.selected.id) || + this.public.find((p) => p.id === this.selected.id); + this.selected = { + ...this.selected, + ...current, + subscribed: this.mine.some((p) => p.id === this.selected.id), + }; + } }, - enter() { - if (location.hash !== '#podcasts') - Alpine.store('library')._beginNavigation('#podcasts'); - Alpine.store('library').view = 'podcasts'; + artwork(pod) { + const url = pod?.metadata?.image_url; + return url && !this.failedArtwork[url] ? url : null; + }, + artworkFailed(pod) { + const url = pod?.metadata?.image_url; + if (url) this.failedArtwork[url] = true; + }, + description(pod) { + const text = pod?.metadata?.description || ''; + return !this.descriptionExpanded && text.length > 360 + ? text.slice(0, 360).trimEnd() + '…' + : text; + }, + navigate(hash, view, options = {}) { + const library = Alpine.store('library'); + library._beginNavigation(hash, options); + library.view = view; + library.currentArtist = null; + library.currentRelease = null; + library.currentPlaylist = null; Alpine.store('mobile')?.closeLibrary(); - const loading = this.task(async () => { - await this.load(); - this.message = ''; - }); + this.ensurePolling(); + }, + ensurePolling() { if (!this.poller) this.poller = setInterval(() => { - if (Alpine.store('library').view === 'podcasts' && !this.busy) + if ( + ['podcasts', 'podcast_detail'].includes(Alpine.store('library').view) && + !this.busy && + !this.loading + ) this.update().catch(() => {}); }, 5000); - return loading; + }, + async enter(options = {}) { + const token = ++this._navigation; + this.navigate('#podcasts', 'podcasts', options); + this.selected = null; + this.selectedId = null; + this.episodes = []; + this.message = ''; + this.loading = true; + try { + await this.load(); + } catch (error) { + if (token === this._navigation) this.message = error.message; + } finally { + if (token === this._navigation) { + this.loading = false; + Alpine.store('library')._afterNavigation(options); + } + } }, async update() { await this.load(); - if (this.selected && !this.mine.some((p) => p.id === this.selected.id)) { - this.selected = null; - this.episodes = []; - } - if (this.selected) await this.loadEpisodes(); + if (this.selected?.subscribed) await this.loadEpisodes(); + else this.episodes = []; }, async loadEpisodes(append = false) { const id = this.selected.id; @@ -149,29 +208,63 @@ this.message = ''; }); }, - open(pod) { - this.selected = pod; + async open(pod, options = {}) { + const id = typeof pod === 'string' ? pod : pod.id; + const token = ++this._navigation; + this.selectedId = id; + this.descriptionExpanded = false; + const cached = + this.mine.find((p) => p.id === id) || + this.public.find((p) => p.id === id) || + (typeof pod === 'object' ? pod : null); + this.selected = cached + ? { + ...cached, + subscribed: this.mine.some((p) => p.id === id) || !!cached.subscribed, + } + : null; this.episodes = []; this.hasMore = false; this.filter = ''; this.season = ''; - this.task(async () => { - await this.loadEpisodes(); - this.message = ''; - }); + this.message = ''; + this.loading = true; + this.navigate('#podcast?id=' + encodeURIComponent(id), 'podcast_detail', options); + try { + await this.load(); + if (token !== this._navigation) return; + const detail = + this.mine.find((p) => p.id === id) || + this.public.find((p) => p.id === id) || + this.selected || + (await this.api('detail', { id })); + if (token !== this._navigation) return; + this.selected = { ...detail, subscribed: this.mine.some((p) => p.id === id) }; + if (this.selected.subscribed) await this.loadEpisodes(); + } catch (error) { + if (token === this._navigation) + this.message = error.message || this.text('notFound'); + } finally { + if (token === this._navigation) { + this.loading = false; + Alpine.store('library')._afterNavigation(options); + } + } }, openResult(pod) { + return this.open(pod); + }, + subscribe(pod = this.selected) { return this.task(async () => { - if (!pod.subscribed) await this.api('add', { url: pod.url }); + await this.api('add', { url: pod.url || pod.metadata.feed_url }); await this.load(); - this.selected = this.mine.find((p) => p.id === pod.id) || pod; - this.episodes = []; - this.hasMore = false; - this.filter = ''; - this.season = ''; - Alpine.store('library')._beginNavigation('#podcasts'); - Alpine.store('library').view = 'podcasts'; - await this.loadEpisodes(); + if (this.selectedId === pod.id) { + this.selected = this.mine.find((p) => p.id === pod.id) || { + ...pod, + subscribed: true, + }; + await this.loadEpisodes(); + } this.message = ''; }); }, @@ -180,6 +273,8 @@ const result = await this.api('add', { url: url || this.url }); this.url = ''; await this.load(); + this.adding = false; + if (result.id) await this.open(result.id); this.message = result.warning || this.text('done'); }); }, @@ -188,8 +283,13 @@ this.task(async () => { const result = await this.api('remove', { id: pod.id }); if (this.selected?.id === pod.id) { + ++this._navigation; + this.loading = false; this.selected = null; + this.selectedId = null; this.episodes = []; + this.navigate('#podcasts', 'podcasts'); + Alpine.store('library')._afterNavigation(); } await this.load(); this.message = this.text(result.publication_pending ? 'pending' : 'done'); @@ -250,18 +350,28 @@ }); }, search() { - const query=this.query.trim(); + const query = this.query.trim(); return this.task(async () => { const data = await this.api('search', { query }); - if(this.query.trim()!==query){this.message='';return;} + if (this.query.trim() !== query) { + this.message = ''; + return; + } this.hits = data.hits; - this.searched=true; + this.searched = true; this.message = this.text('done'); }); }, - resetSearch(){this.searched=false;this.hits=[];}, + resetSearch() { + this.searched = false; + this.hits = []; + }, publicCards() { - return [...new Map((this.searched?this.hits:this.public).map((p) => [p.id, p])).values()]; + return [ + ...new Map( + (this.searched ? this.hits : this.public).map((p) => [p.id, p]), + ).values(), + ]; }, seasons() { return [ diff --git a/templates/player/podcast_search_card.html b/templates/player/podcast_search_card.html new file mode 100644 index 0000000..2568fa3 --- /dev/null +++ b/templates/player/podcast_search_card.html @@ -0,0 +1,15 @@ + diff --git a/templates/player/podcast_styles.html b/templates/player/podcast_styles.html new file mode 100644 index 0000000..15ad293 --- /dev/null +++ b/templates/player/podcast_styles.html @@ -0,0 +1,39 @@ + diff --git a/templates/player/podcasts.html b/templates/player/podcasts.html index 496257e..c391f61 100644 --- a/templates/player/podcasts.html +++ b/templates/player/podcasts.html @@ -1,174 +1,211 @@ - + + diff --git a/templates/player/scripts.html b/templates/player/scripts.html index 91ae09b..8d91499 100644 --- a/templates/player/scripts.html +++ b/templates/player/scripts.html @@ -2670,7 +2670,11 @@ document.addEventListener('alpine:init', () => { if (this.view !== 'artists' || this.artistsPage === 0) this.goArtists(options); else if (options.restoreScroll) this._restoreScrollPosition(hash); } else if (view === 'podcasts') { - Alpine.store('podcasts').enter(); + Alpine.store('podcasts').enter(options); + } else if (view === 'podcast') { + const podcastId = new URLSearchParams(params).get('id'); + if(podcastId)Alpine.store('podcasts').open(podcastId,options); + else Alpine.store('podcasts').enter(options); } else if (view === 'uploads' && !id) { if (this.view !== 'my_uploads' || this.artistsPage === 0) this.goMyUploads(options); else if (options.restoreScroll) this._restoreScrollPosition(hash); diff --git a/templates/player/shell.html b/templates/player/shell.html index f1608bd..8126c76 100644 --- a/templates/player/shell.html +++ b/templates/player/shell.html @@ -75,7 +75,7 @@ {{ t.player_my_uploads }} - +
@@ -447,20 +447,6 @@
- +

diff --git a/tests/browser-podcast-ui.cjs b/tests/browser-podcast-ui.cjs new file mode 100644 index 0000000..b2f16a5 --- /dev/null +++ b/tests/browser-podcast-ui.cjs @@ -0,0 +1,85 @@ +// Render first: FURU_PODCAST_RENDER_FIXTURE=1 cargo test renders_podcast_navigation_and_views +// Uses the real rendered application with isolated API/feed fixtures; no user data. +const {chromium}=require(process.env.PLAYWRIGHT_MODULE||'playwright'); +const fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict'); +const root=path.resolve(__dirname,'..'); +const html=fs.readFileSync(path.join(root,'target/podcast-player-fixture.html'),'utf8'); +const alpinePath=process.env.ALPINE_FIXTURE||path.join(root,'target/podcast-alpine.min.js'); +const cover='https://feeds.example.test/cover.svg'; +const description='A long RSS description, shown only on the detail page. '.repeat(150); +const mine=[ + {id:'pod1:own',metadata:{title:'A podcast about sound',author:'Sound studio',description,image_url:cover},episodes:2,new_episodes:1,shared:false}, + {id:'pod1:broken',metadata:{title:'A missing cover',author:'Test publisher',image_url:'https://feeds.example.test/missing.jpg'},episodes:0,new_episodes:0,shared:false}, + {id:'pod1:none',metadata:{title:'No RSS artwork',author:null},episodes:0,new_episodes:0,shared:false}, +]; +const publicPod={id:'pod1:public',url:'https://feeds.example.test/public.xml',metadata:{title:'Public podcast',author:'Another publisher',description,image_url:cover},subscribed:false}; +const episode={id:'ep1:one',metadata:{title:'First episode',podcast_id:'pod1:own',published_at_ms:1700000000000,duration_ms:60000},cached:false,downloading:false,position_ms:0,completed:false,error:null}; + +(async()=>{ + const browser=await chromium.launch({headless:true,...(process.env.CHROME_PATH?{executablePath:process.env.CHROME_PATH}:{})}); + try{ + const page=await browser.newPage({viewport:{width:1440,height:1000}}),errors=[],actions=[]; + page.on('pageerror',error=>errors.push(error.message)); + await page.route('**/*',async route=>{ + const url=new URL(route.request().url()); + if(url.hostname==='cdn.jsdelivr.net'&&url.pathname.includes('alpine')&&fs.existsSync(alpinePath))return route.fulfill({contentType:'application/javascript',body:fs.readFileSync(alpinePath,'utf8')}); + if(url.hostname==='feeds.example.test')return url.pathname==='/cover.svg'?route.fulfill({contentType:'image/svg+xml',body:'SOUND'}):route.fulfill({status:404,body:''}); + if(url.hostname==='podcast-ui.test'&&url.pathname==='/')return route.fulfill({contentType:'text/html',body:html}); + if(url.pathname==='/api/podcasts/action'){ + const body=route.request().postDataJSON();actions.push(body); + if(body.action==='list')return route.fulfill({json:{mine,public:[publicPod]}}); + if(body.action==='episodes')return route.fulfill({json:{episodes:[{...episode,metadata:{...episode.metadata,podcast_id:body.id}}],has_more:false}}); + if(body.action==='add'){mine.push({...publicPod,episodes:1,new_episodes:1,shared:false});publicPod.subscribed=true;return route.fulfill({json:{ok:true,id:publicPod.id}});} + return route.fulfill({json:{ok:true}}); + } + if(url.pathname==='/api/player/search')return route.fulfill({json:{artists:[{id:1,name:'A musician',image_url:cover,release_count:1,track_count:1}],releases:[],tracks:[],podcasts:[publicPod,mine[0]]}}); + if(url.pathname.startsWith('/api/'))return route.fulfill({json:[]}); + if(url.hostname==='cdn.jsdelivr.net')return route.continue(); + return route.fulfill({status:404,body:''}); + }); + const settled=async view=>{await page.waitForFunction(v=>window.Alpine?.store('library')?.view===v&&!Alpine.store('podcasts').loading,view);}; + await page.goto('http://podcast-ui.test/#podcasts');await settled('podcasts'); + assert.equal(await page.locator('.card-grid .podcast-tile').count(),4); + assert.equal(await page.locator('.podcast-description').count(),0); + await page.waitForFunction(()=>document.querySelector('.podcast-tile img')?.naturalWidth>0); + await page.waitForFunction(()=>Alpine.store('podcasts').failedArtwork['https://feeds.example.test/missing.jpg']); + assert.equal(await page.locator('.podcast-tile[title="A missing cover"] svg').count(),1); + await page.screenshot({path:path.join(root,'target/podcast-ui-grid.png')}); + + await page.locator('.podcast-tile[title="A podcast about sound"]').click();await settled('podcast_detail'); + assert.ok(page.url().endsWith('#podcast?id=pod1%3Aown')); + await page.getByRole('heading',{name:'First episode',exact:true}).waitFor(); + assert.equal(await page.locator('.podcast-detail > template').count(),1); + assert.ok((await page.locator('.podcast-detail .podcast-description').first().innerText()).length<400); + await page.screenshot({path:path.join(root,'target/podcast-ui-detail.png')}); + await page.getByRole('button',{name:'Show more',exact:true}).click(); + assert.equal(await page.locator('.podcast-detail .podcast-description').first().innerText(),description.trim()); + await page.getByRole('button',{name:'Show less',exact:true}).click(); + await page.reload();await settled('podcast_detail'); + await page.getByRole('heading',{name:'First episode',exact:true}).waitFor(); + await page.goBack();await settled('podcasts'); + + await page.locator('.podcast-tile[title="Public podcast"]').click();await settled('podcast_detail'); + assert.equal(actions.filter(a=>a.action==='add').length,0); + await page.getByRole('button',{name:'Subscribe',exact:true}).click(); + await page.getByRole('button',{name:'Publish',exact:true}).waitFor(); + assert.equal(actions.filter(a=>a.action==='add').length,1); + + await page.evaluate(()=>Alpine.store('library').search('sound')); + await page.locator('.search-release-card.podcast-tile').first().waitFor(); + const headings=await page.locator('.search-section-title').allTextContents(); + assert.ok(headings.indexOf('Artists')document.documentElement.scrollWidth>innerWidth),false); + await page.screenshot({path:path.join(root,'target/podcast-ui-mobile-detail.png')}); + assert.deepEqual(errors,[]); + console.log('PASS: cold list/detail hashes, back navigation, RSS artwork/fallbacks, explicit subscribe, compact ordered search, desktop/mobile'); + } finally {await browser.close();} +})().catch(error=>{console.error(error);process.exitCode=1;}); diff --git a/tests/podcasts.test.cjs b/tests/podcasts.test.cjs index c6023fe..20693c0 100644 --- a/tests/podcasts.test.cjs +++ b/tests/podcasts.test.cjs @@ -4,7 +4,7 @@ const {test} = require('node:test'); const vm = require('node:vm'); const source = readFileSync(`${__dirname}/../templates/player/podcast_scripts.html`, 'utf8').replace(/<\/?script>/g, ''); function setup(responder=()=>({})) { - const calls=[],stores={library:{view:'artists',_beginNavigation(){}},mobile:{closeLibrary(){}},player:{_playLocal(track,options){this.currentTrack=track;this.options=options;},seek(){}}}; + const calls=[],stores={library:{view:'artists',_beginNavigation(){},_afterNavigation(){}},mobile:{closeLibrary(){}},player:{_playLocal(track,options){this.currentTrack=track;this.options=options;},seek(){}}}; vm.runInNewContext(source,{ document:{documentElement:{lang:'ru'},addEventListener(_,fn){fn();}}, Alpine:{store(name,value){if(value)stores[name]=value;return stores[name];}}, @@ -74,7 +74,7 @@ test('opening podcast navigation starts polling and search results open existing const {store,stores,calls}=setup(body=>body.action==='list'?{mine:[podcast],public:[]}:body.action==='episodes'?{episodes:[],has_more:false}:{}); await store.enter();assert.equal(store.poller,1);assert.equal(stores.library.view,'podcasts'); stores.library.view='search';await store.openResult(podcast); - assert.equal(stores.library.view,'podcasts');assert.equal(store.selected.id,'show'); + assert.equal(stores.library.view,'podcast_detail');assert.equal(store.selected.id,'show'); assert.equal(calls.filter(c=>c.action==='add').length,0); }); @@ -84,3 +84,38 @@ test('podcast search displays matching results instead of retaining unrelated pu assert.deepEqual(Array.from(store.publicCards(),p=>p.id),['matching']); store.resetSearch();assert.deepEqual(Array.from(store.publicCards(),p=>p.id),['unrelated']); }); + +test('public podcast cards preview details without subscribing; only the subscribe button adds the feed',async()=>{ + const pod={id:'public',url:'https://example.test/feed',metadata:{title:'Public',image_url:'https://example.test/cover.jpg'}}; + let subscribed=false; + const {store,stores,calls}=setup(body=>{ + if(body.action==='add'){subscribed=true;return {id:pod.id};} + if(body.action==='list')return {mine:subscribed?[pod]:[],public:[pod]}; + return {episodes:[],has_more:false}; + }); + await store.open(pod);assert.equal(stores.library.view,'podcast_detail'); + assert.equal(store.selected.subscribed,false);assert.equal(calls.filter(c=>c.action==='add').length,0); + assert.equal(calls.filter(c=>c.action==='episodes').length,0); + await store.subscribe();assert.equal(store.selected.subscribed,true); + assert.equal(calls.filter(c=>c.action==='add').length,1);assert.equal(calls.filter(c=>c.action==='episodes').length,1); + assert.equal(store.artwork(pod),pod.metadata.image_url);store.artworkFailed(pod);assert.equal(store.artwork(pod),null); +}); + +test('back navigation wins over a slow detail request',async()=>{ + let finish; + const {store,stores}=setup(body=>body.action==='detail'?new Promise(resolve=>{finish=resolve;}):{mine:[],public:[]}); + const opened=store.open('slow');while(!finish)await new Promise(resolve=>setImmediate(resolve)); + await store.enter();finish({id:'slow',metadata:{title:'Old'}});await opened; + assert.equal(stores.library.view,'podcasts');assert.equal(store.selected,null);assert.equal(store.loading,false); +}); + +test('hash routing restores both the podcast list and a selected podcast',()=>{ + const script=readFileSync(`${__dirname}/../templates/player/scripts.html`,'utf8'); + const start=script.indexOf(' _navigateFromHash(options = {}) {');const end=script.indexOf(' _scrollElement()',start); + const calls=[],location={hash:'#podcasts'}; + const context=vm.createContext({GUEST:false,location,URLSearchParams,Alpine:{store(){return {enter(options){calls.push(['list',options]);},open(id,options){calls.push(['detail',id,options]);}};}}}); + const library=vm.runInContext('({'+script.slice(start,end)+'})',context);library.goArtists=()=>{throw Error('unexpected artist navigation');}; + library._navigateFromHash({fromHash:true});assert.equal(calls[0][0],'list');assert.equal(calls[0][1].fromHash,true); + location.hash='#podcast?id='+encodeURIComponent('pod1:fixture');library._navigateFromHash({fromHash:true}); + assert.equal(calls[1][0],'detail');assert.equal(calls[1][1],'pod1:fixture'); +});