diff --git a/templates/player.html b/templates/player.html index a26b67d..247486d 100644 --- a/templates/player.html +++ b/templates/player.html @@ -13,5 +13,6 @@ {% include "player/lyrics_modal.html" %} {% include "player/podcast_scripts.html" %} {% include "player/lyrics_scripts.html" %} +{% include "player/search_group_scripts.html" %} {% include "player/scripts.html" %} {% endblock body %} diff --git a/templates/player/scripts.html b/templates/player/scripts.html index 438c85f..4de7628 100644 --- a/templates/player/scripts.html +++ b/templates/player/scripts.html @@ -3484,6 +3484,7 @@ document.addEventListener('alpine:init', () => { }, async search(query, options = {}) { + Alpine.store('searchGroups')?.reset(); if (GUEST) return; const q = (query || '').trim(); if (!q) { @@ -3650,6 +3651,7 @@ document.addEventListener('alpine:init', () => { }, clearSearch() { + Alpine.store('searchGroups')?.reset(); this.stopFederationSearch(); this.searchQuery = ''; this.searchResults = null; @@ -4450,7 +4452,10 @@ document.addEventListener('alpine:init', () => { playSearchTrack(idx) { if (!this.searchResults || !this.searchResults.tracks) return; - Alpine.store('queue').playRelease(this.searchResults.tracks, idx); + const groups=Alpine.store('searchGroups'); + const visible=groups ? groups.rows(this.searchResults.tracks,'local',!this.similaritySearchLabel).filter(track=>!track._searchGroupHidden) : this.searchResults.tracks; + const position=groups ? visible.findIndex(track=>track._searchSourceIndex===idx) : idx; + if(position>=0) Alpine.store('queue').playRelease(visible, position); }, _setupScroll() { diff --git a/templates/player/search_group_scripts.html b/templates/player/search_group_scripts.html new file mode 100644 index 0000000..944653d --- /dev/null +++ b/templates/player/search_group_scripts.html @@ -0,0 +1,54 @@ + diff --git a/templates/player/shell.html b/templates/player/shell.html index 02524c3..2096b00 100644 --- a/templates/player/shell.html +++ b/templates/player/shell.html @@ -510,14 +510,20 @@ {{ t.player_duration }} - - + +
diff --git a/templates/player/styles.html b/templates/player/styles.html index c90a668..5e3d493 100644 --- a/templates/player/styles.html +++ b/templates/player/styles.html @@ -2794,6 +2794,23 @@ button.user-stat:hover { } /* Search results */ +.search-result-entry {display:grid;grid-template-rows:1fr;opacity:1;transition:grid-template-rows 160ms ease-out,opacity 130ms ease-out} +.search-result-entry.search-result-hidden {grid-template-rows:0fr;opacity:0;pointer-events:none} +.search-result-clip {min-height:0;overflow:hidden} +.search-track-title {display:flex;align-items:center;gap:6px} +.search-track-name {min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.search-version-toggle {display:inline-flex;align-items:center;justify-content:center;gap:3px;flex:none;padding:3px;border:0;border-radius:4px;color:var(--text-secondary);background:transparent;cursor:pointer;font:inherit;font-size:10px;line-height:1} +.search-version-toggle svg {width:16px;height:16px;flex:none} +.search-version-toggle:hover,.search-version-toggle[aria-expanded=true] {color:var(--accent);background:var(--bg-active)} +.search-version-toggle:focus-visible {outline:2px solid var(--accent);outline-offset:2px} +.search-track-variant .track-info {border-left:2px solid var(--border-color);padding-left:10px} +.search-variant-detail {margin-top:3px;color:var(--text-subdued);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.search-result-entry[data-search-source="local"] .search-variant-detail {display:none} +.search-result-entry .track-row:focus-visible {outline:2px solid var(--accent);outline-offset:-2px} +@media (max-width:900px), (pointer:coarse) and (max-width:1024px) { + .search-result-entry[data-search-source="local"] .search-variant-detail {display:block} +} +@media(prefers-reduced-motion:reduce) {.search-result-entry {transition:none}} .search-section { margin-bottom: 24px; } .federation-search-section { border-top: 1px solid var(--border); diff --git a/tests/browser-search-groups.cjs b/tests/browser-search-groups.cjs new file mode 100644 index 0000000..a42aa5d --- /dev/null +++ b/tests/browser-search-groups.cjs @@ -0,0 +1,78 @@ +const {chromium}=require(process.env.PLAYWRIGHT_MODULE||'playwright'); +const fs=require('node:fs'),assert=require('node:assert/strict'); +const html=fs.readFileSync('target/podcast-player-fixture.html','utf8'),alpine=fs.readFileSync('target/podcast-alpine.min.js','utf8'); +const local=(id,title='Still Loving You',artist='Scorpions')=>({id,title,artists:[{id:1,name:artist}],featured_artists:[],release_title:'Release '+id,release_id:id,duration_seconds:300+id,audio_format:'flac',lastfm_rating:87}); +const remote=(id,title='Still Loving You')=>({key:{content_id:'b3:'+String(id).padStart(64,'0')},metadata:{title,artists:[{name:'Scorpions'}],featured_artists:[],release:{title:'Remote release '+id},duration_seconds:300+id},availability:{state:'federated',local:null,federation:[{owner:'peer',item_id:String(id)}]}}); +const data={local:[local(1),local(2,'Another song'),local(3),local(4,'Still Loving You','Other artist'),local(5)],remote:[remote(11),remote(12),remote(13,'Other remote song')]}; +(async()=>{ + const browser=await chromium.launch({headless:true,...(process.env.CHROME_PATH?{executablePath:process.env.CHROME_PATH}:{})}); + try{ + for(const width of [1440,390,320]){ + const page=await browser.newPage({viewport:{width,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message)); + await page.route('**/*',route=>{ + const u=new URL(route.request().url()); + if(u.hostname==='groups.test'&&u.pathname==='/')return route.fulfill({contentType:'text/html',body:html}); + if(u.hostname==='cdn.jsdelivr.net'&&u.pathname.includes('alpine'))return route.fulfill({contentType:'application/javascript',body:alpine}); + if(u.pathname==='/api/player/artists')return route.fulfill({json:{items:[],total:0,has_more:false}}); + return route.fulfill({json:[]}); + }); + await page.goto('http://groups.test/');await page.waitForFunction(()=>window.Alpine?.store('searchGroups')&&Alpine.store('library')); + await page.evaluate(data=>{ + window.groupPlays=[]; + const library=Alpine.store('library');library.view='search';library.searchQuery='Still';library.searchLoading=false;library.similaritySearchLabel=''; + library.searchResults={artists:[],releases:[],tracks:data.local,podcasts:[]};library.federationSearch={loading:false,error:'',artists:[],releases:[],tracks:data.remote}; + Alpine.store('queue').playRelease=(tracks,index)=>window.groupPlays.push({source:'local',ids:tracks.map(t=>t.id),id:tracks[index].id}); + library.playFederatedTrack=track=>window.groupPlays.push({source:'federation',id:track.key.content_id}); + },data); + const localRows=page.locator('[data-search-source="local"]'),remoteRows=page.locator('[data-search-source="federation"]'); + await page.waitForFunction(()=>document.querySelectorAll('[data-search-source="local"]').length===5); + assert.equal(await localRows.count(),5);assert.equal(await remoteRows.count(),3); + assert.equal(await localRows.locator('.search-version-toggle:visible').count(),1); + assert.equal(await localRows.nth(1).getAttribute('inert')!==null,true); + assert.ok((await localRows.nth(1).boundingBox()).height<1);assert.ok((await localRows.nth(2).boundingBox()).height<1); + assert.equal(await localRows.first().locator('.search-version-toggle').getAttribute('aria-expanded'),'false'); + await localRows.first().locator('.search-track-name').click(); + assert.deepEqual(await page.evaluate(()=>window.groupPlays.at(-1)),{source:'local',ids:[1,2,4],id:1}); + await page.evaluate(()=>{window.groupPlays=[];window.groupNodes=[...document.querySelectorAll('[data-search-source="local"]')];}); + const animation=await page.evaluate(()=>new Promise(resolve=>{ + const head=document.querySelector('[data-search-source="local"]'),next=document.querySelectorAll('[data-search-source="local"]')[3],positions=[],start=performance.now(); + head.querySelector('.search-version-toggle').click(); + function sample(){positions.push(next.getBoundingClientRect().top);if(performance.now()-start<230)requestAnimationFrame(sample);else resolve(positions);} + requestAnimationFrame(sample); + })); + assert.ok(new Set(animation.map(y=>Math.round(y))).size>2,'siblings move smoothly instead of jumping'); + assert.equal(await page.evaluate(()=>window.groupPlays.length),0,'branch toggle does not play'); + assert.equal(await localRows.first().locator('.search-version-toggle').getAttribute('aria-expanded'),'true'); + assert.equal(await localRows.nth(1).getAttribute('inert'),null); + assert.equal(await page.evaluate(()=>window.groupNodes.every((node,index)=>node===document.querySelectorAll('[data-search-source="local"]')[index])),true,'stable DOM identities on toggle'); + for(let index=0;index<3;index++){ + const row=localRows.nth(index),box=await row.boundingBox(),actions=await row.locator('.track-actions').boundingBox(); + assert.ok(actions.x>=0&&actions.x+actions.width<=width,'actions fit viewport');assert.ok(actions.y>=box.y&&actions.y+actions.height<=box.y+box.height+1); + } + await localRows.nth(1).locator('.search-track-name').click();assert.equal(await page.evaluate(()=>window.groupPlays.at(-1).id),3,'expanded version plays its original content'); + await page.screenshot({path:`target/search-groups-expanded-${width}.png`}); + const closing=await page.evaluate(()=>new Promise(resolve=>{ + const rows=document.querySelectorAll('[data-search-source="local"]'),positions=[],start=performance.now();rows[0].querySelector('.search-version-toggle').click(); + function sample(){positions.push(rows[3].getBoundingClientRect().top);if(performance.now()-start<230)requestAnimationFrame(sample);else resolve(positions);}requestAnimationFrame(sample); + })); + assert.ok(new Set(closing.map(y=>Math.round(y))).size>2,'collapse also moves siblings smoothly'); + await page.waitForFunction(()=>document.querySelectorAll('[data-search-source="local"]')[1].getBoundingClientRect().height<1); + assert.equal(await localRows.nth(1).getAttribute('aria-hidden'),'true'); + await localRows.first().locator('.search-version-toggle').focus();await page.keyboard.press('Enter'); + await page.waitForFunction(()=>document.querySelector('[data-search-source="local"] .search-version-toggle').getAttribute('aria-expanded')==='true'); + await page.evaluate(()=>new Promise(resolve=>{const button=document.querySelector('[data-search-source="local"] .search-version-toggle');[0,20,40,60,80].forEach(delay=>setTimeout(()=>button.click(),delay));setTimeout(resolve,280);})); + assert.equal(await localRows.first().locator('.search-version-toggle').getAttribute('aria-expanded'),'false'); + assert.ok((await localRows.nth(1).boundingBox()).height<1,'rapid toggles settle in the final state'); + const remoteHead=remoteRows.first();await remoteHead.locator('.search-version-toggle').click(); + await page.evaluate(track=>Alpine.store('library').federationSearch.tracks.push(track),remote(14)); + await page.waitForFunction(()=>document.querySelectorAll('[data-search-source="federation"]').length===4); + assert.equal(await remoteHead.locator('.search-version-toggle').getAttribute('aria-expanded'),'true'); + assert.equal(await remoteHead.locator('.search-version-toggle span').textContent(),'3'); + await remoteRows.nth(1).locator('.search-track-name').click();assert.equal(await page.evaluate(()=>window.groupPlays.at(-1).id),remote(12).key.content_id); + assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false); + await page.emulateMedia({reducedMotion:'reduce'});assert.equal(await localRows.first().evaluate(el=>getComputedStyle(el).transitionDuration),'0s'); + assert.deepEqual(errors,[]);await page.close(); + } + console.log('Grouped local/federation search, animation, playback and streaming checks passed.'); + }finally{await browser.close();} +})().catch(error=>{console.error(error);process.exitCode=1;}); diff --git a/tests/search_groups.test.cjs b/tests/search_groups.test.cjs new file mode 100644 index 0000000..67b6ae5 --- /dev/null +++ b/tests/search_groups.test.cjs @@ -0,0 +1,30 @@ +const assert=require('node:assert/strict'),{test}=require('node:test'),fs=require('node:fs'),vm=require('node:vm'); +const script=fs.readFileSync(`${__dirname}/../templates/player/search_group_scripts.html`,'utf8').replace(/<\/?script>/g,''); +function setup(){const stores={queue:{playRelease(tracks,index){this.tracks=tracks;this.index=index;}}};const context=vm.createContext({document:{documentElement:{lang:'en'},addEventListener(_,fn){fn();}},Alpine:{store(name,value){if(value)stores[name]=value;return stores[name];}}});vm.runInContext(script,context);return {groups:stores.searchGroups,stores,context};} +const local=(id,title='Still Loving You',artist='Scorpions')=>({id,title,artists:[{id:1,name:artist}],release_title:'Album '+id}); +const ids=rows=>Array.from(rows,row=>row.id); +test('groups nonadjacent titles by performer, preserving original indices and versions',()=>{ + const {groups}=setup(),tracks=[local(1),local(2,'Other'),local(3,' STILL LOVING YOU '),local(4,'Still Loving You','Someone else'),local(5,'Still Loving You (Live)')]; + const rows=groups.rows(tracks,'local');assert.deepEqual(ids(rows),[1,3,2,4,5]);assert.equal(rows[0]._searchGroupCount,2);assert.equal(rows[1]._searchGroupHidden,true);assert.equal(rows[1]._searchSourceIndex,2); + assert.equal(rows[2]._searchGroupCount,1);assert.equal(rows[3]._searchGroupCount,1);assert.equal(rows[4]._searchGroupCount,1);assert.equal(tracks[0]._searchGroupKey,undefined); +}); +test('expansion survives streamed federation updates and resets for a new search',()=>{ + const {groups}=setup();const remote=id=>({key:{content_id:'b3:'+id},metadata:{title:'Song',artists:[{name:'Artist'}]},availability:{federation:[{owner:'peer',item_id:id}]}}); + let rows=groups.rows([remote(1),remote(2)],'federation');groups.toggle(rows[0]); + rows=groups.rows([remote(1),remote(2),remote(3)],'federation');assert.equal(rows[0]._searchGroupCount,3);assert.ok(rows.every(row=>!row._searchGroupHidden)); + assert.equal(new Set(rows.map(row=>row._searchRowId)).size,3);assert.equal(rows[0]._searchGroupControls.split(' ').length,2); + groups.reset();assert.equal(groups.rows([remote(1),remote(2)],'federation')[1]._searchGroupHidden,true); +}); +test('audio similarity keeps its original ungrouped ranking',()=>{ + const {groups}=setup(),tracks=[local(1),local(2,'Other'),local(3)];const rows=groups.rows(tracks,'local',false); + assert.deepEqual(ids(rows),[1,2,3]);assert.ok(rows.every(row=>row._searchGroupCount===1&&!row._searchGroupHidden)); +}); +test('playing a grouped search uses the selected source identity and only visible versions',()=>{ + const {groups,stores,context}=setup(),template=fs.readFileSync(`${__dirname}/../templates/player/scripts.html`,'utf8'); + const method=template.slice(template.indexOf(' playSearchTrack(idx)'),template.indexOf(' _setupScroll()',template.indexOf(' playSearchTrack(idx)'))); + vm.runInContext('this.library={'+method+'};',context);const library=context.library;library.searchResults={tracks:[local(1),local(2,'Other'),local(3)]}; + library.playSearchTrack(0);assert.deepEqual(ids(stores.queue.tracks),[1,2]);assert.equal(stores.queue.index,0); + library.playSearchTrack(1);assert.equal(stores.queue.tracks[stores.queue.index].id,2); + groups.toggle(groups.rows(library.searchResults.tracks,'local')[0]);library.playSearchTrack(2); + assert.deepEqual(ids(stores.queue.tracks),[1,3,2]);assert.equal(stores.queue.tracks[stores.queue.index].id,3); +});