PlotDirector/PlotLine.Tests/Browser/focus-ribbon-refinement.cjs

26 lines
12 KiB
JavaScript

// Real auth/controllers/SQL/SignalR, disposable fixture only. No physical Word claim.
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
const base=process.env.PD_SHARED_FOCUS_URL||'http://127.0.0.1:5258',installed=process.argv.includes('--installed');
(async()=>{const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),s=JSON.parse(fs.readFileSync('/tmp/shared-focus-browser-scope.json'));assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);const profile=installed?fs.mkdtempSync('/tmp/pd-focus-refinement-'):null,persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1500,height:1000}}):null,browser=persistent?.browser()||await chromium.launch();let step='login';const errors=[];
try{const c=persistent||await browser.newContext({viewport:{width:1500,height:1000}});c.on('page',p=>p.on('pageerror',e=>errors.push(e.message)));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.addInitScript(user=>{try{localStorage.setItem('plotdirector.desktop.v1.'+user,JSON.stringify({dismissedAt:Date.now()}));}catch{}},who.UserID);
const login=await c.newPage();await login.goto(base+'/Account/Login');await login.locator('[name=Email]').fill(who.Email);await login.locator('[name=Password]').fill(who.Password);await Promise.all([login.waitForURL(u=>u.pathname!='/Account/Login'),login.locator('button[type=submit]').click()]);let desktop;if(installed){await login.goto(`${base}/Projects/Details/${s.project}`);desktop=await browser.newBrowserCDPSession();await desktop.send('PWA.install',{manifestId:base+'/Projects',installUrlOrBundleUrl:`${base}/Projects/Details/${s.project}`});await desktop.send('PWA.changeAppUserSettings',{manifestId:base+'/Projects',displayMode:'standalone'});}
async function surface(url){if(!installed){const p=await c.newPage();await p.goto(url);return p;}const opened=c.waitForEvent('page');await desktop.send('PWA.launch',{manifestId:base+'/Projects',url});const p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));return p;}
const p=await surface(`${base}/Writer/Review?projectId=${s.project}&bookId=${s.book}&chapterId=${s.chapter1}`),active='.pd-ribbon-panel:not([hidden]) .pd-ribbon-focus';await p.waitForFunction(()=>window.PlotDirectorSharedFocus);
const state=()=>p.evaluate(()=>PlotDirectorNarrativeFocus.state),shared=()=>p.evaluate(()=>PlotDirectorSharedFocus.shared),waitScene=id=>p.waitForFunction(id=>PlotDirectorNarrativeFocus.state.sceneID===id,id);
const read=()=>p.evaluate(async url=>{const response=await fetch(url,{cache:'no-store'});if(!response.ok||response.redirected)throw Error('Authenticated history read failed');return response.json();},`${base}/NarrativeFocus/Read?projectId=${s.project}&bookId=${s.book}`);
async function choose(chapter,scene=null){if(await p.locator('[data-focus-toggle]').getAttribute('aria-expanded')!=='true')await p.click('[data-focus-toggle]');const expand=p.locator(`[data-focus-expand="${chapter}"]`);if(scene&&await expand.getAttribute('aria-expanded')!=='true')await expand.click();await p.locator(`[data-focus-target="${chapter}/${scene||''}"]`).click();await p.waitForFunction(t=>PlotDirectorNarrativeFocus.state.chapterID===t.chapter&&PlotDirectorNarrativeFocus.state.sceneID===t.scene,{chapter,scene});await p.waitForFunction(()=>document.querySelector('[data-focus-toggle]').getAttribute('aria-expanded')==='false');assert.equal(await p.evaluate(()=>document.activeElement.hasAttribute('data-focus-toggle')),true,'successful hierarchy selection restores header focus');}
async function history(){const toggle=p.locator(active+' [data-focus-history-toggle]');if(await toggle.getAttribute('aria-expanded')!=='true')await toggle.click();await p.waitForTimeout(170);return p.locator(active+' [data-focus-history-target]').evaluateAll(nodes=>nodes.map(n=>n.dataset.focusHistoryTarget));}
const closeHistory=async()=>{if(await p.locator(active+' [data-focus-history-toggle]').getAttribute('aria-expanded')==='true')await p.locator(active+' [data-focus-history-toggle]').press('Escape');};
step='static ribbon and hierarchy';assert.equal(await p.locator('[data-global-focus=go],[data-focus-search],[data-focus-recent],[data-focus-position],[data-word-ribbon-status]').count(),0);assert.deepEqual(await p.locator(active+' .pd-ribbon-commands').evaluate(row=>[...row.children].map(n=>n.matches('[data-global-focus]')?n.dataset.globalFocus:n.matches('[data-shared-focus-hold]')?'hold':n.matches('.pd-focus-history')?'history':'unknown')),['previous','hold','next','history']);assert.equal(await p.locator(active+' [data-shared-focus-status]').count(),0);assert.equal(await p.locator('[data-ribbon-word]').count(),3,'distinct Word caret actions retained');
await choose(s.chapter1,s.scene1);assert(await p.locator(active+' [data-global-focus=previous]').isDisabled());await choose(s.chapter1,s.scene2);await choose(s.chapter2,s.scene3);await p.waitForFunction(()=>PlotDirectorSharedFocus.held===false);
const b=await surface(`${base}/Writing/Context?projectId=${s.project}&bookId=${s.book}&sceneId=${s.scene1}`);await b.waitForFunction(s=>document.querySelector('[data-context-workspace]')?.contextController.position.sceneId===s.scene3,s);
step='history separated from narrative order';let items=await history();assert.equal(items[0],`${s.chapter1}/${s.scene2}`);assert(items.includes(`${s.chapter1}/${s.scene1}`));assert(!items.includes(`${s.chapter2}/${s.scene3}`));await p.locator(active+` [data-focus-history-target="${s.chapter1}/${s.scene1}"]`).click();await waitScene(s.scene1);await p.locator(active+' [data-global-focus=next]').click();await waitScene(s.scene2);await p.waitForFunction(()=>document.querySelector('.pd-ribbon-panel:not([hidden]) [data-global-focus=previous]').disabled===false);await p.locator(active+' [data-global-focus=previous]').click();await waitScene(s.scene1);await choose(s.chapter2,s.scene3);
const last=await p.evaluate(()=>PlotDirectorNarrativeFocus.state.positions.filter(x=>x.sceneID).at(-1));await choose(last.chapterID,last.sceneID);assert(await p.locator(active+' [data-global-focus=next]').isDisabled());await choose(s.chapter2,s.scene3);
step='refresh/reconnect do not duplicate visits';const before=await read();await p.reload();await p.waitForFunction(()=>PlotDirectorSharedFocus?.shared?.chapterID);await p.evaluate(async()=>{const c=PlotDirectorPresenceConnection;await c.stop();await c.start();document.dispatchEvent(new Event('pd-presence-ready'));await PlotDirectorSharedFocus.refresh();});assert.deepEqual((await read()).recent,before.recent);await p.waitForFunction(()=>!document.querySelector('.pd-ribbon-panel:not([hidden]) [data-shared-focus-hold]').disabled);
step='Held history isolates remote visits and retains local visits';await p.locator(active+' [data-shared-focus-hold]').click();assert.equal(await p.locator(active+' [data-shared-focus-hold] span').textContent(),'Resume');assert.match(await p.locator(active+' [data-focus-mode-icon]').getAttribute('d'),/l12 8/);const frozen=await history();await closeHistory();await b.selectOption('[data-context-scene]',String(s.scene1));await b.waitForFunction(s=>PlotDirectorSharedFocus.shared.sceneID===s.scene1,s);await b.selectOption('[data-context-scene]',String(s.scene2));await b.waitForFunction(s=>PlotDirectorSharedFocus.shared.sceneID===s.scene2,s);await p.waitForFunction(s=>PlotDirectorSharedFocus.shared.sceneID===s.scene2,s);await waitScene(s.scene3);assert.deepEqual(await history(),frozen);await closeHistory();const remote=(await read());await choose(s.emptyChapter);await choose(s.chapter1,s.scene1);assert.deepEqual((await read()).recent,remote.recent);items=await history();assert.equal(items[0],`${s.emptyChapter}/`);await closeHistory();await p.reload();await p.waitForFunction(()=>PlotDirectorSharedFocus?.held);await waitScene(s.scene1);assert((await history()).includes(`${s.chapter2}/${s.scene3}`));await closeHistory();await p.locator(active+' [data-shared-focus-hold]').click();await waitScene(s.scene2);assert.equal((await shared()).version,remote.version);assert.equal(await p.locator(active+' [data-shared-focus-hold] span').textContent(),'Hold');assert((await history()).includes(`${s.emptyChapter}/`),'a local held visit remains available after Resume');await closeHistory();
step='keyboard history';await closeHistory();await p.locator(active+' [data-focus-history-toggle]').press('ArrowDown');await p.waitForTimeout(250);const keyboardTarget=await p.evaluate(()=>document.activeElement.dataset.focusHistoryTarget);assert(keyboardTarget,'history retains keyboard focus after metadata refresh');await p.keyboard.press('Enter');await waitScene(Number(keyboardTarget.split('/')[1]));await p.waitForFunction(()=>document.querySelector('.pd-ribbon-panel:not([hidden]) [data-focus-history-toggle]').getAttribute('aria-expanded')==='false');assert.equal(await p.evaluate(()=>document.activeElement.hasAttribute('data-focus-history-toggle')),true);step='chapter-only and keyboard hierarchy';await choose(s.emptyChapter);assert.equal((await state()).sceneID,null);await p.click('[data-focus-toggle]');const chapter=p.locator(`[data-focus-target="${s.chapter1}/"]`);await chapter.focus();await chapter.press('ArrowRight');assert.equal(await p.locator(`[data-focus-expand="${s.chapter1}"]`).getAttribute('aria-expanded'),'true');await chapter.press('ArrowDown');assert.equal(await p.evaluate(()=>document.activeElement.dataset.focusTarget),`${s.chapter1}/${s.scene1}`);await p.keyboard.press('Enter');await waitScene(s.scene1);await p.click('[data-focus-toggle]');await p.keyboard.press('Escape');assert.equal(await p.evaluate(()=>document.activeElement.hasAttribute('data-focus-toggle')),true);
step='responsive dark layout, bounded dropdowns and fixed Hold geometry';for(const width of [1500,1000,650,390]){await p.setViewportSize({width,height:900});await p.evaluate(()=>window.PlotDirectorApplyApplicationTheme?.('modern-dark'));await p.locator(active+' [data-focus-history-toggle]').click();await p.waitForTimeout(120);const box=await p.locator(active+' .pd-focus-history-menu').boundingBox();assert(box&&box.x>=-1&&box.x+box.width<=width+1&&box.y+box.height<=901,'history bounds at '+width);await closeHistory();await p.click('[data-focus-toggle]');const picker=await p.locator('.pd-focus-picker').boundingBox();assert(picker.x>=-1&&picker.x+picker.width<=width+1&&picker.y+picker.height<=901);await p.keyboard.press('Escape');assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}
step='long manuscript hierarchy stays scrollable';const catalog=await read();await p.route('**/NarrativeFocus/Read?*',route=>route.fulfill({json:{...catalog,recent:[...catalog.recent,...catalog.recent,{chapterID:999999,sceneID:999999,sequence:999999}],positions:[...catalog.positions,...Array.from({length:200},(_,i)=>({chapterID:800000+i,chapterNumber:i+100,chapterTitle:'Long synthetic chapter '+('title '.repeat(25)),sceneID:null}))]}}));await p.click('[data-focus-toggle]');await p.waitForTimeout(250);assert(await p.locator('[data-focus-hierarchy]').evaluate(n=>n.scrollHeight>n.clientHeight&&n.clientHeight<600));await p.keyboard.press('Escape');const filtered=await history();assert.equal(new Set(filtered).size,filtered.length);assert(!filtered.includes('999999/999999'),'unresolvable history is never a valid target');await closeHistory();await p.unroute('**/NarrativeFocus/Read?*');await p.setViewportSize({width:1500,height:1000});await p.screenshot({path:`/tmp/focus-refinement-${installed?'pwa':'browser'}.png`});const bounds=await p.locator(active).boundingBox();await p.locator(active+' [data-shared-focus-hold]').click();const heldBounds=await p.locator(active).boundingBox();assert.equal(bounds.width,heldBounds.width);assert.equal(bounds.height,heldBounds.height);await p.locator(active+' [data-shared-focus-hold]').click();
assert.deepEqual(errors,[]);console.log('PASS real focus ribbon refinement '+(installed?'installed PWA':'browser')+': ordered controls, chapter hierarchy, keyboard/Escape, canonical Previous/Next, server history/reorder/dedupe, refresh/reconnect, independent held history/local visits, Resume without publication, Word caret controls, dark responsive bounded menus and stable Hold size.');
}catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await persistent?.close();await browser.close();if(profile)fs.rmSync(profile,{recursive:true,force:true});}})();