const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'); const base=process.env.PD_NARRATIVE_TEST_URL||'http://127.0.0.1:5238'; (async()=>{ const installed=process.argv.includes('--installed'),profile=fs.mkdtempSync('/tmp/pd-narrative-pwa-'); const c=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1666,height:1050}}):await(await chromium.launch()).newContext({viewport:{width:1666,height:1050}}),b=c.browser(); try{ await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:null,defaultPauseOnEdit:true}})); await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false,state:'Disconnected',wordConnected:false}})); await c.route('**/native-companion/status*',r=>r.fulfill({json:{leases:[]}})); await c.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')})); await c.route('**/hubs/**',r=>r.abort()); await c.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()}))); let p; if(installed){const tab=c.pages()[0];await tab.goto(base+'/fixture');const d=await b.newBrowserCDPSession(),manifestId=base+'/Projects';await d.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture'});await d.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=c.waitForEvent('page');await d.send('PWA.launch',{manifestId,url:base+'/fixture'});p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else p=await c.newPage(); await p.goto(base+'/Writer/Write?projectId=7&bookId=12&objective=true'); await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus); const toggle=p.locator('[data-focus-toggle]'),popup=p.locator('.pd-focus-picker'); const open=async()=>{if(await toggle.getAttribute('aria-expanded')!=='true')await toggle.click();await expectOpen();}; const expectOpen=async()=>assert.equal(await toggle.getAttribute('aria-expanded'),'true'); const closed=async()=>{await p.waitForFunction(()=>document.querySelector('[data-focus-toggle]').getAttribute('aria-expanded')==='false');assert(!await popup.isVisible());}; const set=t=>p.evaluate(t=>window.PlotDirectorNarrativeFocus.set(t),t); await set({chapterID:21,sceneID:31}); const styles=await p.evaluate(()=>['appProjectMenu','appBookMenu','appNarrativeFocusMenu'].map(id=>{const n=document.getElementById(id),s=getComputedStyle(n),a=getComputedStyle(n,'::after');return [s.fontSize,s.padding,s.gap,s.color,s.borderRadius,a.borderTop,a.borderRight,a.borderLeft,a.marginLeft];})); assert.deepEqual(styles[1],styles[0]);assert.deepEqual(styles[2].filter((_,i)=>i!==1),styles[0].filter((_,i)=>i!==1)); assert(await p.evaluate(()=>{const a=getComputedStyle(document.getElementById('appProjectMenu')),b=getComputedStyle(document.getElementById('appBookMenu'));return a.borderRight===b.borderRight&&a.marginRight===b.marginRight&&a.paddingRight===b.paddingRight;}),'matching Project/Book separators'); await p.locator('[data-focus-label]').evaluate(n=>n.textContent='Current Focus: Short'); assert(await toggle.evaluate(n=>{const label=n.querySelector('[data-focus-label]'),b=n.getBoundingClientRect(),l=label.getBoundingClientRect();return b.right-l.right<30;}),'chevron follows short label without unused width'); await open();await p.locator('[data-focus-search]').fill('Departure');await expectOpen();assert.equal(await p.locator('[data-focus-position] option').count(),2); assert.equal(await p.locator('.pd-focus-picker [data-focus-step],.pd-focus-picker [data-global-focus]').count(),0); let release;const gate=new Promise(r=>release=r);await p.route('**/NarrativeFocus/Set',async r=>{await gate;await r.continue();}); await p.locator('[data-focus-position]').selectOption('22/32');await expectOpen();assert.match(await p.locator('[data-narrative-status]').textContent(),/Updating/);release();await closed();await p.unroute('**/NarrativeFocus/Set');assert.match(await toggle.textContent(),/Departure/); await open();await p.locator('[data-focus-search]').fill('');await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus=previous]').click();await closed(); await open();await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus=next]').click();await closed(); await open();await p.locator('[data-focus-recent]').selectOption('21/101');await closed(); await open();await p.locator('[data-focus-position]').selectOption('21/');await closed(); await open();await p.route('**/NarrativeFocus/Set',r=>r.fulfill({status:503,json:{message:'Temporary navigation failure. Please retry.'}}));await p.locator('[data-focus-position]').selectOption('21/31');await p.waitForFunction(()=>document.querySelector('[data-narrative-status]').textContent.includes('Temporary'));await expectOpen();assert(await p.locator('[data-focus-position]').isEnabled());await p.unroute('**/NarrativeFocus/Set');await p.locator('[data-focus-position]').selectOption('21/31');await closed(); assert(await toggle.evaluate(n=>n===document.activeElement),'successful selection returns keyboard focus'); await open();await p.locator('[data-focus-search]').focus();await p.keyboard.press('Escape');await closed();assert(await toggle.evaluate(n=>n===document.activeElement)); await open();await toggle.click();await closed(); await open();await p.locator('main').click({position:{x:5,y:150}});await closed(); for(const width of [1666,950,650])for(const theme of ['modern-light','modern-dark']){ await p.setViewportSize({width,height:1050});await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme?.(t),theme); const before=await toggle.boundingBox();await p.locator('[data-focus-label]').evaluate(n=>n.textContent='Current Focus: Chapter with a very long title '.repeat(12)); const after=await toggle.boundingBox();assert.equal(after.height,before.height);assert(after.width<=Math.max(before.width,448)); assert(await p.locator('[data-focus-label]').evaluate(n=>n.scrollWidth>n.clientWidth&&getComputedStyle(n).textOverflow==='ellipsis')); await open();const box=await popup.boundingBox();assert(box.x>=0&&box.x+box.width<=width+1,'popup fits viewport'); const layout=await popup.evaluate(n=>{const elements=['[data-focus-search]','[data-focus-position]','[data-focus-recent]'].map(s=>n.querySelector(s).getBoundingClientRect());const buttons=[...n.querySelectorAll('[data-focus-step]')].map(b=>{const r=b.getBoundingClientRect(),i=b.querySelector('svg').getBoundingClientRect();return {top:r.top,height:r.height,iconWidth:i.width,iconHeight:i.height};});return {aligned:elements.every(r=>Math.abs(r.left-elements[0].left)<1&&Math.abs(r.right-elements[0].right)<1),buttons};}); assert(layout.aligned,'popup fields and navigation row share horizontal edges');for(const b of layout.buttons){assert.equal(b.iconWidth,16);assert.equal(b.iconHeight,16);} await p.screenshot({path:`/tmp/pd-focus-popup-${installed?'pwa':'browser'}-${width}-${theme}.png`});await p.keyboard.press('Escape');await closed(); } await open();await p.goto(base+'/Timeline/Index?ProjectID=7&BookID=12');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await closed(); console.log(`PASS ${installed?'installed PWA':'Chromium'}: matching selector styles; confirmed scene/chapter/previous/next/recent dismissal; pending/failure/retry; search; outside/Escape/toggle/section dismissal; keyboard focus; long-label truncation; light/dark at 1666/950/650px.`); }finally{await c.close();await b?.close();fs.rmSync(profile,{recursive:true,force:true});} })().catch(e=>{console.error(e.stack);process.exitCode=1;});