106 lines
22 KiB
JavaScript
106 lines
22 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();
|
|
const errors=[];p.on('pageerror',e=>errors.push(e.message));let objectiveWrites=0;p.on('request',r=>{if(r.method()==='POST'&&r.url().includes('/Writer/SaveObjective'))objectiveWrites++;});
|
|
await p.goto(base+'/Timeline/Index?ProjectID=7&BookID=12');await p.locator('.timeline-scene-card[data-scene-id="32"]').click();
|
|
await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.sceneID===32);assert.equal(await p.locator('.timeline-scene-card[aria-current=location]').getAttribute('data-scene-id'),'32');
|
|
assert(!new URL(p.url()).searchParams.has('navigateFocus'),'one-use navigation marker removed');
|
|
const url=base+'/Writer/Write?projectId=7&bookId=12&objective=true';await p.goto(url+'&setup=true');
|
|
await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);
|
|
assert.equal(await p.evaluate(()=>window.PlotDirectorNarrativeFocus.state.sceneID),32,'Writer shares the scene explicitly opened in Timeline');
|
|
const openFocus=async()=>{if(await p.locator('[data-focus-toggle]').getAttribute('aria-expanded')!=='true')await p.locator('[data-focus-toggle]').click();};
|
|
const go=async()=>{const menu=p.locator('.pd-ribbon-panel:not([hidden]) .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('.pd-ribbon-panel:not([hidden]) [data-global-focus=go]').click();};
|
|
const state=()=>p.evaluate(()=>window.PlotDirectorNarrativeFocus.state);
|
|
const set=t=>p.evaluate(t=>window.PlotDirectorNarrativeFocus.set(t),t);
|
|
assert(await set({chapterID:21,sceneID:31}));
|
|
const original=await p.locator('[data-objective-location]').textContent();
|
|
await p.locator('[data-focus-wizard]').waitFor({state:'visible'});
|
|
await p.locator('[data-focus-next]').click();await p.locator('[data-objective-chapter]').selectOption('21');await p.locator('[data-objective-scene]').selectOption('31');
|
|
const beforeEditor=await p.locator('[data-focus-wizard]').evaluate(f=>Object.fromEntries(new FormData(f)));
|
|
assert(await set({chapterID:22,sceneID:32}));assert.equal((await state()).sceneID,32);
|
|
assert.equal(await p.locator('[data-objective-location]').textContent(),original);
|
|
assert.deepEqual(await p.locator('[data-focus-wizard]').evaluate(f=>Object.fromEntries(new FormData(f))),beforeEditor,'open objective editor keeps explicit targets');
|
|
assert.equal(objectiveWrites,0,'global navigation never writes the objective');
|
|
await p.locator('#appBookMenu').click();const leaveDialog=p.waitForEvent('dialog');const leaveClick=p.locator('[data-app-book-choice="13"]').click().catch(error=>{if(!error.message.includes('ERR_ABORTED'))throw error;});const dialog=await leaveDialog;assert.equal(dialog.type(),'beforeunload');await dialog.dismiss();await leaveClick;assert.equal(new URL(p.url()).searchParams.get('bookId'),'12','unsaved objective protects a full book switch');assert.deepEqual(await p.locator('[data-focus-wizard]').evaluate(f=>Object.fromEntries(new FormData(f))),beforeEditor);
|
|
await p.locator('[data-focus-cancel]').click();await p.locator('[data-go-objective]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===31);
|
|
assert.equal(await p.locator('[data-objective-location]').textContent(),original);
|
|
await p.locator('[data-focus-toggle]').click();await openFocus();await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="next"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===101);await openFocus();await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="next"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32,'cross-chapter forward');
|
|
await openFocus();await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="previous"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===101);
|
|
await openFocus();await p.locator('[data-focus-search]').fill('Departure');assert.equal(await p.locator('[data-focus-position] option').count(),2);await p.locator('[data-focus-position]').selectOption('22/32');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32);await openFocus();await p.locator('[data-focus-search]').fill('');
|
|
await openFocus();await p.locator('[data-focus-recent]').selectOption('21/101');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===101);
|
|
const other=await c.newPage();await other.goto(url);await other.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await other.evaluate(()=>window.PlotDirectorNarrativeFocus.set({chapterID:22,sceneID:32}));await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32);
|
|
const stale=await state(),token=await p.locator('[data-narrative-focus] [name=__RequestVerificationToken]').inputValue();
|
|
const staleResponse=await c.request.post(base+'/NarrativeFocus/Set',{form:{projectId:7,bookId:12,chapterId:21,sceneId:31,version:stale.version-1,__RequestVerificationToken:token}});assert.equal(staleResponse.status(),409);
|
|
assert.equal((await c.request.post(base+'/NarrativeFocus/Set',{form:{projectId:7,bookId:12,chapterId:21,sceneId:31,version:stale.version}})).status(),400,'antiforgery required');
|
|
assert.equal((await c.request.get(base+'/NarrativeFocus/Read?projectId=8&bookId=12')).status(),404,'scope isolation');
|
|
const isolated=await require('playwright').request.newContext({extraHTTPHeaders:{Cookie:'fixture-user=5'}});const isolatedState=await(await isolated.get(base+'/NarrativeFocus/Read?projectId=7&bookId=12')).json();assert.equal(isolatedState.sceneID,31,'another author has independent focus');await isolated.dispose();
|
|
await other.close();await p.reload();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.sceneID===32);assert.equal(await p.locator('[data-objective-location]').textContent(),original);
|
|
await p.goto(base+'/Writer/Write?projectId=7&bookId=13');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);assert.equal((await state()).sceneID,null,'book focus never leaks');
|
|
await p.goto(base+'/fixture?page=floorplans');await p.waitForFunction(()=>document.querySelector('[data-floor-plan-initialized=true]'));
|
|
const focusBefore=await state();await p.locator('#floorPlanOccupancy').evaluate(n=>n.click());await p.locator('[data-occupancy-scene-select]').selectOption('101');await p.locator('[data-occupancy-next]').click();const scrubber=p.locator('.pd-scene-explorer input[type=range]');await scrubber.focus();await scrubber.press('ArrowLeft');assert.equal(await p.locator('[data-occupancy-scene-select]').inputValue(),'101');await scrubber.press('ArrowRight');assert.equal(await p.locator('[data-occupancy-scene-select]').inputValue(),'32');assert.equal((await state()).version,focusBefore.version,'floor-plan local scene navigation never writes focus');
|
|
const local=await p.locator('[data-occupancy-scene-select]').inputValue();await set({chapterID:21,sceneID:31});assert.equal(await p.locator('[data-occupancy-scene-select]').inputValue(),local,'global focus leaves local explorer alone');
|
|
const floorVersion=(await state()).version;await go();assert.equal(await p.locator('[data-occupancy-scene-select]').inputValue(),'31');assert.equal((await state()).version,floorVersion,'Go aligns local occupancy without writing focus');await p.locator('[data-occupancy-scene-select]').selectOption('32');
|
|
await p.locator('.pd-scene-explorer button').filter({hasText:'Set Current Focus Here'}).click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32);
|
|
await p.reload();await p.waitForFunction(()=>document.querySelector('[data-floor-plan-initialized=true]'));assert.equal(await p.locator('[data-occupancy-scene-select]').inputValue(),'32','local explorer restore');
|
|
for(const width of [1666,950])for(const theme of ['modern-light','modern-dark']){await p.setViewportSize({width,height:1050});await p.evaluate(theme=>window.PlotDirectorApplyApplicationTheme?.(theme),theme);await p.locator('#floorPlanOccupancy').evaluate(n=>n.click());await p.screenshot({path:`/tmp/pd-narrative-${installed?'pwa':'browser'}-${width}-${theme}.png`});}
|
|
await p.setViewportSize({width:1666,height:1050});
|
|
await p.goto(url);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await set({chapterID:21,sceneID:31});
|
|
const sceneCard=p.locator('[data-key="Scene-31"]');await sceneCard.waitFor();await sceneCard.locator('[data-authoring-edit]').click();await sceneCard.locator('[name=ScenePurposeNotes]').fill('Unsaved scene 31 intention');
|
|
const editorNode=await sceneCard.locator('[data-authoring-form]').elementHandle();await set({chapterID:21});
|
|
assert.equal(await sceneCard.locator('[name=ScenePurposeNotes]').inputValue(),'Unsaved scene 31 intention');assert(await editorNode.evaluate(n=>n.isConnected),'unsaved inline editor stays mounted');assert.equal(await sceneCard.locator('[name=sceneId]').inputValue(),'31','inline save remains bound to original scene');
|
|
await sceneCard.locator('[data-authoring-cancel]').click();await p.getByRole('button',{name:'Show current focus',exact:true}).click();await p.waitForFunction(()=>!document.querySelector('[data-key="Scene-31"]')&&document.querySelector('[data-key="Goals-21"]'));
|
|
await p.locator('[data-narrative-scene="31"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===31);assert.equal(objectiveWrites,0,'Go to scene does not edit an objective');
|
|
await set({});await p.goto(base+'/Writer/Review?projectId=7&bookId=12');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus&&document.querySelector('[data-writer-word]'));assert.equal((await state()).chapterID,null,'displaying the Reader default does not set global focus');assert.equal(await p.locator('[data-writer-word]').getAttribute('data-chapter-id'),'21','Reader Word target remains its accepted chapter independently of an empty global focus');
|
|
await p.goto(base+'/Writer/Review?projectId=7&bookId=12&chapterId=21');
|
|
await p.waitForFunction(()=>document.querySelector('[data-writer-review]')?.canChangeNarrative);
|
|
await p.waitForFunction(()=>document.querySelector('[data-review-panel]'));
|
|
await p.evaluate(()=>{window.__columns=document.querySelector('[data-review-columns]');window.__left=document.getElementById('review-chapter-notes');window.__word=document.querySelector('[data-writer-word]');window.__work=document.querySelector('[data-writer-work]');});
|
|
let documentLoads=0;const countNavigation=request=>{if(request.isNavigationRequest()&&request.resourceType()==='document')documentLoads++;};p.on('request',countNavigation);
|
|
await p.locator('#reader-pause-toggle').evaluate(n=>n.click());assert(await p.locator('#reader-pause').isChecked());
|
|
assert(await set({chapterID:22,sceneID:32}));
|
|
await p.waitForFunction(()=>document.querySelector('.manuscript-reader')?.dataset.chapterId==='22');
|
|
assert(await p.locator('#reader-pause').isChecked(),'existing pause state survives in-place navigation');assert.equal(await p.locator('#reader-pause-toggle').textContent(),'Resume updates');
|
|
assert.equal(documentLoads,0,'global chapter navigation refreshes Review without page navigation');p.off('request',countNavigation);
|
|
assert(await p.evaluate(()=>window.__columns===document.querySelector('[data-review-columns]')&&window.__left===document.getElementById('review-chapter-notes')&&window.__word===document.querySelector('[data-writer-word]')&&window.__work===document.querySelector('[data-writer-work]')),'stable columns, session bindings and Word object');
|
|
await p.locator('[data-review-scope-new="Chapter"]').evaluate(n=>n.click());await p.locator('[data-review-form] textarea[name=Observation]').fill('Unsaved review on chapter 22');
|
|
assert(await set({chapterID:21,sceneID:31}));assert.equal(await p.locator('.manuscript-reader').getAttribute('data-chapter-id'),'22');assert.equal(await p.locator('[data-review-form] textarea[name=Observation]').inputValue(),'Unsaved review on chapter 22');assert.equal(await p.locator('[data-review-form] [name=ChapterID]').inputValue(),'22','annotation stays bound to original chapter');
|
|
await p.locator('[data-review-cancel]').click();await p.locator('[data-review-focus-notice] button').click();await p.waitForFunction(()=>document.querySelector('.manuscript-reader')?.dataset.chapterId==='21');
|
|
await p.waitForFunction(()=>document.querySelector('[data-review-panel]'));
|
|
await p.screenshot({path:`/tmp/pd-narrative-${installed?'pwa':'browser'}-Review.png`});
|
|
await p.goto(base+'/fixture?page=relationships');await p.waitForFunction(()=>window.PlotDirectorRelationshipWorkspace&&window.PlotDirectorNarrativeFocus);
|
|
const relationshipState=await p.evaluate(()=>{const w=window.PlotDirectorRelationshipWorkspace;return {cast:w.cast,relationships:w.relationships(),links:w.cy.edges().map(e=>({characterRelationshipID:e.data('relationshipID'),sourceCharacterID:Number(e.data('source').slice(2)),targetCharacterID:Number(e.data('target').slice(2)),relationshipLabel:e.data('label'),cssClass:e.classes().join(' '),intensity:e.data('intensity')}))};});
|
|
await p.route('**/RelationshipMap/State?**',r=>r.fulfill({json:relationshipState}));const versionBefore=(await state()).version;
|
|
await p.locator('#rwTimeline').fill('31');await p.waitForTimeout(250);assert.equal((await state()).version,versionBefore,'Relationships scrubber is local');
|
|
const relationshipPosition=await p.locator('#rwTimeline').inputValue();await set({chapterID:22,sceneID:32});assert.equal(await p.locator('#rwTimeline').inputValue(),relationshipPosition);
|
|
const explorerBox=await p.locator('.rw-timeline .pd-scene-explorer').boundingBox(),timelineBox=await p.locator('.rw-timeline').boundingBox();assert(explorerBox.y+explorerBox.height<=timelineBox.y+timelineBox.height+1,'all Relationship Scene Explorer controls fit the timeline row');
|
|
const relationshipVersion=(await state()).version;await go();assert.equal(await p.locator('.pd-scene-explorer select').inputValue(),'32');assert.equal((await state()).version,relationshipVersion);
|
|
await p.screenshot({path:`/tmp/pd-narrative-${installed?'pwa':'browser'}-Relationships.png`});
|
|
for(const width of [950,650]){await p.setViewportSize({width,height:1050});await p.waitForTimeout(80);const fit=await p.locator('.rw-timeline').evaluate(row=>{const controls=row.querySelector('.pd-scene-explorer').getBoundingClientRect(),box=row.getBoundingClientRect();return controls.bottom<=box.bottom+1&&controls.right<=box.right+1;});assert(fit,'responsive Relationship Scene Explorer fits');await p.screenshot({path:`/tmp/pd-narrative-${installed?'pwa':'browser'}-Relationships-${width}.png`});}await p.setViewportSize({width:1666,height:1050});
|
|
const mapFixture=await(await c.request.get(base+'/map-story-fixture')).json();mapFixture.scenes.push({...mapFixture.scenes[0],sceneID:31,bookID:12});await p.route('**/Maps/Story?**',r=>r.fulfill({json:mapFixture}));
|
|
await p.goto(base+'/fixture?page=maps&story=true');await p.waitForFunction(()=>window.PlotDirectorMapWorkspace);await p.locator('button[data-mode=story]').evaluate(n=>n.click());await p.waitForFunction(()=>window.PlotDirectorStoryOverlay?.data&&window.PlotDirectorNarrativeFocus);
|
|
const mapVersion=(await state()).version;await p.locator('#mapStoryLens').evaluate(n=>{n.value='scene';n.dispatchEvent(new Event('change',{bubbles:true}));});
|
|
await p.locator('#mapStoryScene').evaluate(n=>{n.value='90';n.dispatchEvent(new Event('change',{bubbles:true}));});assert.equal((await state()).version,mapVersion,'Maps scene selection is local');
|
|
const mapScene=await p.locator('#mapStoryScene').inputValue();await set({chapterID:21,sceneID:31});assert.equal(await p.locator('#mapStoryScene').inputValue(),mapScene,'global focus retains map position and journey context');const mapFocusVersion=(await state()).version;await go();assert.equal(await p.locator('#mapStoryScene').inputValue(),'31');assert.equal((await state()).version,mapFocusVersion);
|
|
assert.match(await p.locator('#mapsDetailContent').innerText(),/Harbour morning/);
|
|
await p.locator('#mapStoryScene').evaluate(n=>{n.value='90';n.dispatchEvent(new Event('change',{bubbles:true}));});const filteredPosition=await p.locator('#mapStoryScene').inputValue();const excludedMapping=mapFixture.scenes.find(s=>s.sceneID===31).position.featureID?'unmapped':'mapped';await p.locator('#mapStoryMapping').evaluate((n,value)=>{n.value=value;n.dispatchEvent(new Event('change',{bubbles:true}));},excludedMapping);await go();assert.match(await p.locator('[data-focus-workspace-status]').textContent(),/mapping or planning filters/);assert.equal(await p.locator('#mapStoryScene').inputValue(),filteredPosition,'filtered Go preserves the existing local map target');assert.equal(await p.locator('#mapStoryMapping').inputValue(),excludedMapping);await p.locator('#mapStoryMapping').evaluate(n=>{n.value='all';n.dispatchEvent(new Event('change',{bubbles:true}));});await p.locator('#mapStoryLayer').evaluate(n=>n.click());assert.equal(await p.evaluate(()=>window.PlotDirectorStoryOverlay.state.visible),false);await go();assert.equal(await p.evaluate(()=>window.PlotDirectorStoryOverlay.state.visible),true,'Go reveals a hidden story layer');assert.equal((await state()).version,mapFocusVersion);
|
|
|
|
await p.screenshot({path:`/tmp/pd-narrative-${installed?'pwa':'browser'}-Maps.png`});
|
|
await p.goto(base+'/Timeline/Index?ProjectID=7');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.bookID===12);assert.match(await p.locator('[data-focus-label]').textContent(),/A Distant Shore/);await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-book]').selectOption('13');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.bookID===13);assert.equal((await state()).sceneID,null);assert.equal(await p.locator('.timeline-scene-card').count(),3,'focus book selection preserves project-wide Timeline');assert(!new URL(p.url()).searchParams.has('BookID'));await p.locator('[data-focus-book]').selectOption('12');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.bookID===12);
|
|
await p.locator('[data-focus-position]').selectOption('23/');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.chapterID===23);assert(await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="next"]').isDisabled(),'no following scene after the final empty chapter');assert(await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="previous"]').isEnabled());await openFocus();await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="previous"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32);await set({chapterID:21,sceneID:31});
|
|
let reopened;if(installed){const d=await b.newBrowserCDPSession(),opened=c.waitForEvent('page');await d.send('PWA.launch',{manifestId:base+'/Projects',url:base+'/Timeline/Index?ProjectID=7'});reopened=await opened;await reopened.waitForLoadState();assert(await reopened.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else{reopened=await c.newPage();await reopened.goto(base+'/Timeline/Index?ProjectID=7');}await reopened.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.bookID===12);assert.equal(await reopened.evaluate(()=>window.PlotDirectorNarrativeFocus.state.sceneID),31,'reopened workspace restores its authorised focus book and location');await reopened.close();
|
|
const searchMilliseconds=await p.evaluate(()=>{const focus=window.PlotDirectorNarrativeFocus.state,original=focus.positions,input=document.querySelector('[data-focus-search]');focus.positions=Array.from({length:5000},(_,i)=>({chapterID:Math.floor(i/50)+1,chapterNumber:Math.floor(i/50)+1,chapterTitle:'Synthetic chapter',sceneID:20000+i,sceneNumber:i%50+1,label:`Chapter ${Math.floor(i/50)+1} · Scene ${i+1}`}));const start=performance.now();for(const value of ['Scene 499','']){input.value=value;input.dispatchEvent(new Event('input'));}const elapsed=performance.now()-start;focus.positions=original;input.value='';input.dispatchEvent(new Event('input'));return elapsed;});assert(searchMilliseconds<1500,'5000-scene header search remains responsive');console.log(`Focus search, 5000 scenes: ${searchMilliseconds.toFixed(1)}ms`);
|
|
assert.deepEqual(errors,[]);console.log(`PASS ${installed?'installed Chromium PWA':'Chromium'} narrative focus: independent objective/editor, Go to objective, manuscript neighbours across chapters, search, recency, windows, persistence, book/security scope, antiforgery, floor-plan local isolation/promotion/persistence unsaved inline/Review editor protection, stable Review refresh, local Relationships/Maps positions, keyboard scene stepping and themed responsive rendering`);
|
|
}finally{await c.close();await b?.close();fs.rmSync(profile,{recursive:true,force:true});}
|
|
})().catch(e=>{console.error(e.stack);process.exitCode=1;});
|