60 lines
12 KiB
JavaScript
60 lines
12 KiB
JavaScript
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 c.addCookies([{name:'fixture-focus-reader',value:'mapped',url:base}]);
|
|
await c.addInitScript(()=>{window.__focusEvents=[];window.__positions=[];window.addEventListener('plotdirector:narrative-focus-changed',e=>window.__focusEvents.push({chapterID:e.detail.chapterID,sceneID:e.detail.sceneID,version:e.detail.version}));document.addEventListener('reader:focus-positioned',e=>window.__positions.push(e.detail));});
|
|
const active='.pd-ribbon-panel:not([hidden])',command=async kind=>{const menu=p.locator(active+' .pd-ribbon-focus details[data-compact=true]');if(await menu.count()&&!await menu.evaluate(n=>n.open))await menu.locator('summary').click();await p.locator(active+' [data-global-focus='+kind+']').click();},go=()=>command('go'),state=()=>p.evaluate(()=>window.PlotDirectorNarrativeFocus.state),set=t=>p.evaluate(t=>window.PlotDirectorNarrativeFocus.set(t),t);
|
|
const clear=()=>p.evaluate(()=>{window.__positions=[];window.__focusEvents=[];});
|
|
async function positioned(scene){await p.waitForFunction(id=>window.__positions.some(e=>e.sceneID===id),scene);}
|
|
async function position(){return p.evaluate(()=>{const r=document.querySelector('.manuscript-reader'),n=r.querySelector(`[data-paragraph-id="${r.dataset.focusParagraph}"]`);return {id:r.dataset.focusParagraph,top:n?.getBoundingClientRect().top,revision:r.dataset.revision,version:r.dataset.version,chapter:r.dataset.chapterId};});}
|
|
async function choose(value){await clear();await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-position]').selectOption(value);await positioned(Number(value.split('/')[1]));}
|
|
await p.goto(base+'/Chapters/Details/21');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);
|
|
await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-position]').selectOption('22/32');await p.waitForURL(/Chapters\/Details\/22/);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.sceneID===32);assert.equal(await p.locator('[data-focus-chapter]').getAttribute('data-chapter'),'22');
|
|
await command('previous');await p.waitForURL(/Chapters\/Details\/21/);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.sceneID===101);assert.equal(await p.locator('[data-pd-context=scene][aria-current=location]').getAttribute('data-pd-context-id'),'101');
|
|
const form=p.locator('[data-focus-chapter] form:has(input[name=overwriteAuthor])');await form.locator('input[type=checkbox]').check();await set({chapterID:22,sceneID:32});assert.equal(await p.locator('[data-focus-chapter]').getAttribute('data-chapter'),'21');await go();assert.match(await p.locator('[data-focus-workspace-status]').textContent(),/Save or cancel/);await form.evaluate(n=>n.reset());await go();await p.waitForURL(/Chapters\/Details\/22/);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.sceneID===32);
|
|
const version=(await state()).version;await go();assert.equal((await state()).version,version,'aligned Chapter Go retains scene and version');assert.equal(await p.locator('[data-focus-workspace-status]').count(),0,'aligned chapter has no status strip or empty wrapper');
|
|
await p.goto(base+'/Writer/Review?projectId=7&bookId=12');await positioned(32);let baseline=await position();assert(baseline.id,'initial Review load positions verified scene');await clear();await go();await positioned(32);assert.deepEqual(await position(),baseline,'initial load and Go use identical accepted target and offset');
|
|
for(const scene of [31,101,32]){const chapter=scene===32?22:21;await choose(chapter+'/'+scene);baseline=await position();assert.equal((await p.evaluate(()=>window.__focusEvents.length)),1,'one authoritative event per successful selection');assert.equal(baseline.id,await p.locator(`[data-paragraph-id][data-scene-id="${scene}"]`).first().getAttribute('data-paragraph-id'));await clear();await go();await positioned(scene);assert.deepEqual(await position(),baseline,'Go leaves identical scene position unchanged');}
|
|
// Return to the same scene through canonical ribbon stepping and recent history.
|
|
await choose('21/101');baseline=await position();await clear();await command('previous');await positioned(31);await clear();await command('next');await positioned(101);assert.deepEqual(await position(),baseline);await choose('22/32');await clear();await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-recent]').selectOption('21/101');await positioned(101);assert.deepEqual(await position(),baseline,'recent, header and ribbon target the same paragraph/offset');
|
|
// A late context response must not replace an editor opened while navigation is loading.
|
|
await choose('21/31');let releaseContext;const contextGate=new Promise(r=>releaseContext=r);await p.route('**/WriterReview/Panel?*',async route=>{const response=await route.fetch();await contextGate;await route.fulfill({response}).catch(()=>{});});const contextRequest=p.waitForRequest('**/WriterReview/Panel?*');await set({chapterID:21,sceneID:101});await contextRequest;await p.locator('[data-authoring-edit]').first().click();const draft=p.locator('[data-authoring-form]:not([hidden]) textarea').first();await draft.fill('Unsaved chapter note during focus navigation');releaseContext();await p.unroute('**/WriterReview/Panel?*');await p.waitForFunction(()=>document.querySelector('[data-review-message]').textContent.includes('edits are retained'));assert.equal(await draft.inputValue(),'Unsaved chapter note during focus navigation');await p.locator('[data-authoring-form]:not([hidden]) [data-authoring-cancel]').click();await clear();await go();await positioned(101);
|
|
// A callback captured before navigation cannot undo a newer explicit target.
|
|
await p.evaluate(()=>window.__oldReadingAnchor=document.querySelector('.manuscript-reader').readerPreserveView());await choose('21/31');const beforeOldRestore=await position();await p.evaluate(()=>window.__oldReadingAnchor());assert.deepEqual(await position(),beforeOldRestore);
|
|
// Hold a chapter response, return to the displayed chapter, then deliver the stale response.
|
|
let release;const held=new Promise(r=>release=r);await p.route('**/Writer/ReviewContent?*',async route=>{const response=await route.fetch();await held;await route.fulfill({response}).catch(()=>{});});const requested=p.waitForRequest('**/Writer/ReviewContent?*');await set({chapterID:22,sceneID:32});await requested;await clear();await set({chapterID:21,sceneID:101});await positioned(101);release();await p.unroute('**/Writer/ReviewContent?*');await p.waitForTimeout(150);assert.equal((await position()).chapter,'21');assert.equal(await p.locator('[data-paragraph-id][data-scene-id="101"]').first().getAttribute('data-paragraph-id'),(await position()).id,'older chapter response cannot overwrite newer scene');
|
|
await choose('21/31');await clear();await p.locator(active+' [data-global-focus=next]').evaluate(n=>{n.click();n.click();});await positioned(101);assert.equal((await state()).sceneID,101);assert.equal(await p.evaluate(()=>window.__focusEvents.length),1,'rapid clicks accept one scoped update while the command is busy');assert.deepEqual(await p.evaluate(()=>window.__focusEvents.map(e=>[e.chapterID,e.sceneID])),[[21,101]]);
|
|
for(const width of [1666,950,650])for(const theme of ['modern-light','modern-dark']){await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);await p.setViewportSize({width,height:1050});await choose('21/101');const before=await position();await clear();await go();await positioned(101);const after=await position();assert.equal(after.id,before.id);assert(Math.abs(after.top-before.top)<1,'sticky/narrow reader offset is repeatable');await p.screenshot({path:`/tmp/pd-focus-sync-${installed?'pwa':'browser'}-${width}-${theme}.png`});}
|
|
await p.reload();await positioned(101);assert.equal((await position()).id,baseline.id,'refresh resolves the same accepted paragraph identity');
|
|
await c.addCookies([{name:'fixture-focus-reader',value:'unmapped',url:base}]);await p.goto(base+'/Writer/Review?projectId=7&bookId=12');await choose('22/32');assert.equal((await position()).id,'');assert.match(await p.locator('[data-review-focus-notice]').textContent(),/Precise scene positioning is unavailable/);assert.equal((await position()).chapter,'22');
|
|
await p.goto(base+'/fixture?desktop=StoryPoint');await p.waitForFunction(()=>document.querySelector('.pd-ribbon-panel:not([hidden]) .pd-ribbon-group[aria-label=Help]')||!matchMedia('(display-mode: standalone)').matches);
|
|
if(installed){const divider=await p.locator(active+' .pd-ribbon-focus').evaluate(n=>{const s=getComputedStyle(n);return {width:s.borderRightWidth,style:s.borderRightStyle,color:s.borderRightColor};});assert.equal(divider.width,'1px');assert.equal(divider.style,'solid');}
|
|
await p.route('**/StoryPoint?*',r=>r.fulfill({status:503,body:'Synthetic unavailable snapshot'}));await p.route('**/StoryPoint/Index?*',r=>r.fulfill({status:503,body:'Synthetic unavailable snapshot'}));await go();assert.match(await p.locator('[data-focus-workspace-status]').textContent(),/could not be loaded/);
|
|
await p.goto(base+'/fixture?desktop=Characters');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);assert(await p.locator(active+' [data-global-focus=go]').isDisabled());assert.match(await p.locator(active+' [data-global-focus=go]').getAttribute('title'),/does not support/);
|
|
// Success locations belong in the header, not duplicate page-level status strips.
|
|
for(const path of ['/Chapters/Details/21','/Writer/Chapter/21','/fixture?record=Chapters','/Scenes/Edit/31','/Writer/Index?projectId=7&bookId=12','/Writer/Write?projectId=7&bookId=12&objective=true','/fixture?desktop=Books','/fixture?desktop=StoryPoint','/fixture?record=Characters','/fixture?page=maps']){
|
|
await p.goto(base+path);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);
|
|
assert.equal(await p.locator('[data-focus-workspace-status]').count(),0,path+' has no redundant strip');
|
|
assert.doesNotMatch(await p.locator('main').first().innerText(),/Displaying current focus|Current narrative location:|Current Focus:/i,path);
|
|
assert.equal(await p.locator('[data-writer-global-location]').count(),0);
|
|
assert(await p.locator('[data-focus-label]').count());assert(await p.locator('[data-narrative-status][role=status]').count(),'header accessibility status retained');
|
|
if(path==='/Chapters/Details/21')for(const width of [1666,950]){await p.setViewportSize({width,height:1050});await p.screenshot({path:`/tmp/pd-focus-text-${installed?'pwa':'browser'}-${width}.png`});}
|
|
}
|
|
console.log(`PASS ${installed?'installed Chromium PWA':'Chromium'} focus synchronisation: stable-ID chapter follow/dirty guard/Go, identical initial/header/recent/ribbon/Go/refresh accepted positions, canonical boundaries, stale anchor/response rejection, missing-map fallback, repeatable sticky/narrow offsets, disabled explanations and Focus/Help divider.`);
|
|
}finally{await c.close();await b?.close();fs.rmSync(profile,{recursive:true,force:true});}
|
|
})().catch(e=>{console.error(e.stack);process.exitCode=1;});
|