PlotDirector/PlotLine.Tests/Browser/explore-divider.cjs

199 lines
18 KiB
JavaScript

// Real compiled Explore/Journey Razor and investigation engine; isolated memory repositories.
// Start the fixture host with PD_INV_CATALOGUE=Docs/Writer/Investigations/production-catalogue-v0.1.json.
// Run with --installed under xvfb-run for a real installed Chromium PWA.
const {chromium} = require('playwright');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const base='http://127.0.0.1:5238', url=base+'/Writer/Explore?projectId=7&bookId=12';
(async()=>{
const installed=process.argv.includes('--installed'), mode=installed?'installed-pwa':'browser';
const profile=installed?fs.mkdtempSync('/tmp/pd-explore-pwa-'):null;
const context=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1666,height:1050}}):await(await chromium.launch()).newContext({viewport:{width:1666,height:1050}});
const browser=context.browser(), evidence='/tmp/pd-explore-divider-evidence/'+mode;
fs.mkdirSync(evidence,{recursive:true});
await context.addInitScript(()=>{
localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()}));
window.exploreInitialPaints=[];
const set=CSSStyleDeclaration.prototype.setProperty;
CSSStyleDeclaration.prototype.setProperty=function(name,value,priority){
if(name==='--explore-ratio')window.exploreInitialPaints.push(Number(value));
return set.call(this,name,value,priority);
};
});
await context.route('**/native-companion/status*',r=>r.fulfill({json:{leases:[]}}));
await context.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'))}));
try{
let page;
if(installed){
const tab=context.pages()[0];await tab.goto(base+'/fixture');
const cdp=await browser.newBrowserCDPSession(),manifestId=base+'/Projects';
await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture'});
await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});
const opened=context.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:base+'/fixture'});
page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));
}else page=await context.newPage();
page.setDefaultTimeout(15000);
const errors=[];page.on('pageerror',e=>errors.push(e.message));
let navigations=0;page.on('request',r=>{if(r.isNavigationRequest()&&r.frame()===page.mainFrame())navigations++;});
const layout=page.locator('[data-explore-layout]'), divider=page.locator('[data-explore-divider]'), journey=page.locator('[data-explore-journey]');
const ratio=()=>layout.evaluate(n=>Number(n.style.getPropertyValue('--explore-ratio')));
const close=(a,b)=>assert(Math.abs(a-b)<.005,`${a} != ${b}`);
const idle=()=>page.waitForFunction(()=>!document.querySelector('[data-explore-layout]').hasAttribute('data-resize-animating'));
const ready=()=>journey.getByRole('button',{name:'Begin',exact:true}).waitFor();
const begin=async()=>{await journey.locator('[name=concern]').first().check();await journey.getByRole('button',{name:'Begin',exact:true}).click();await journey.locator('[data-inline-investigation]').waitFor();};
await page.goto(url);await ready();close(await ratio(),.5);
const nodes=await layout.evaluateHandle(n=>[n,n.querySelector('#explore-discovery'),n.querySelector('#explore-concern')]);
await page.screenshot({path:evidence+'/initial.png'});
await journey.locator('[name=concern]').first().check();
await journey.getByRole('button',{name:'Begin',exact:true}).scrollIntoViewIfNeeded();
await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));
await page.evaluate(()=>{
const w=document.querySelector('[data-explore-layout]');window.exploreFrames=[];window.exploreTransitions=0;window.exploreWrites=0;
const set=Storage.prototype.setItem;Storage.prototype.setItem=function(k,v){if(k.startsWith('plotdirector.writerExploreLayout.'))window.exploreWrites++;return set.call(this,k,v);};
new MutationObserver(records=>{for(const r of records)if(r.attributeName==='data-resize-animating'&&w.hasAttribute('data-resize-animating'))window.exploreTransitions++;}).observe(w,{attributes:true,attributeFilter:['data-resize-animating']});
window.exploreSampling=true;
function frame(t){
const r=document.querySelector('[data-ribbon-shell]').getBoundingClientRect();
const tabs=[...document.querySelectorAll('[data-guidance-expand],[data-help-expand]')].map(n=>{const b=n.getBoundingClientRect();return[b.x,b.y];});
window.exploreFrames.push({t,animating:w.hasAttribute('data-resize-animating'),ratio:Number(w.style.getPropertyValue('--explore-ratio')),ribbon:[r.x,r.y,r.width,r.height],tabs});
if(window.exploreSampling)requestAnimationFrame(frame);
}requestAnimationFrame(frame);
});
const beforeNavigation=navigations;
await begin();
await page.waitForFunction(()=>document.querySelector('[data-explore-layout]').hasAttribute('data-resize-animating'));
const screenshotSession=await context.newCDPSession(page);
const capture=screenshotSession.send('Page.captureScreenshot',{format:'png',captureBeyondViewport:false}).then(result=>fs.writeFileSync(evidence+'/intermediate.png',Buffer.from(result.data,'base64')));
// A real next-question response during the glide must neither restart it nor replace the outer panels.
const form=journey.locator('[data-investigation-answer]');
assert.equal(await form.count(),1);
await form.locator('[name=option]').first().evaluate(n=>{n.checked=true;n.dispatchEvent(new Event('input',{bubbles:true}));});
await form.locator('button[value=answer]').evaluate(n=>n.form.requestSubmit(n));
await page.waitForFunction(()=>!document.querySelector('[data-explore-investigation]').hasAttribute('aria-busy'));
await idle();await capture;close(await ratio(),.25);
await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));
await page.evaluate(()=>window.exploreSampling=false);
const frames=await page.evaluate(()=>window.exploreFrames);
fs.writeFileSync(evidence+'/animation-frames.json',JSON.stringify(frames,null,2));
assert(frames.filter(f=>f.ratio>.26&&f.ratio<.49).length>=4,'Continuous intermediate positions');
const moving=frames.filter(f=>f.animating),firstSettled=frames.find(f=>f.t>moving.at(-1).t&&!f.animating);
assert(moving.length>=4&&firstSettled,'Animation start and finish captured');
const duration=firstSettled.t-moving[0].t;assert(duration>=375&&duration<=650,`Observed ease-out duration ${duration} ms`);
for(const f of frames){assert.deepEqual(f.ribbon,frames[0].ribbon,'Ribbon stationary');assert.deepEqual(f.tabs,frames[0].tabs,'Side tabs stationary');}
assert.equal(await page.evaluate(()=>window.exploreTransitions),1,'Only discovery-to-active starts animation');
assert.equal(await page.evaluate(()=>window.exploreWrites),0,'Automatic defaults are not persisted as manual choices');
assert.equal(navigations,beforeNavigation,'AJAX investigation does not reload the document');
assert(await nodes.evaluate(ns=>ns.every(n=>n.isConnected)),'Workspace and outer panels stay mounted');
await page.screenshot({path:evidence+'/active.png'});
const id=new URL(page.url()).searchParams.get('investigation');assert(id);
const answerLinks=journey.locator('aside a');assert(await answerLinks.count()>0,'Your answers is retained');
await answerLinks.first().click();await form.waitFor();await idle();close(await ratio(),.25);
const explanation=journey.locator('textarea');
if(await explanation.count())await explanation.fill('Draft explanation retained while resizing');
const dragTo=async target=>{
const b=await divider.boundingBox(),w=await layout.boundingBox();
await page.mouse.move(b.x+b.width/2,b.y+100);await page.mouse.down();
await page.mouse.move(w.x+(w.width-b.width)*target+b.width/2,b.y+100,{steps:12});
await page.mouse.up();
};
await dragTo(.42);close(await ratio(),.42);
assert.equal(await page.evaluate(()=>window.exploreWrites),1,'Drag persists once at completion');
assert.equal(await layout.evaluate(n=>n.classList.contains('writer3-dragging')),false);
if(await explanation.count())assert.equal(await explanation.inputValue(),'Draft explanation retained while resizing');
await divider.focus();const old=await ratio();await divider.press('ArrowRight');assert(await ratio()>old);
await divider.press('Home');assert((await page.locator('#explore-discovery').boundingBox()).width>=259);assert(await page.locator('#explore-discovery').evaluate(n=>n.scrollWidth<=n.clientWidth+2));
await divider.press('End');assert((await page.locator('#explore-concern').boundingBox()).width>=359);assert(await page.locator('#explore-concern').evaluate(n=>n.scrollWidth<=n.clientWidth+2));
await dragTo(.4);const preferred=await ratio();
await journey.locator('button[value=save]').first().click();
await page.waitForFunction(()=>!document.querySelector('[data-explore-investigation]').hasAttribute('aria-busy'));
close(await ratio(),preferred);
await page.getByRole('tab',{name:'Saved investigations',exact:true}).click();
await page.locator(`[data-explore-saved] a[href*="${id}"]`).click();await journey.locator('[data-inline-investigation]').waitFor();await page.waitForFunction(()=>!document.querySelector('[data-explore-investigation]').hasAttribute('aria-busy'));
close(await ratio(),preferred);
await page.reload();await journey.locator('[data-inline-investigation]').waitFor();close(await ratio(),preferred);
assert.equal(await layout.getAttribute('data-explore-state'),'investigation');
assert((await page.evaluate(()=>window.exploreInitialPaints)).every(v=>Math.abs(v-.4)<.005),'Active refresh restores preference directly, without painting 50 percent');
const storage=()=>page.evaluate(()=>JSON.parse(localStorage.getItem(Object.keys(localStorage).find(k=>k.startsWith('plotdirector.writerExploreLayout.')))).leftRatio);
const settled=()=>page.waitForFunction(()=>!document.querySelector('[data-explore-investigation]').hasAttribute('aria-busy'));
const scriptedBegin=()=>journey.getByRole('button',{name:'Begin',exact:true}).evaluate(n=>{n.form.querySelector('[name=concern]').checked=true;n.form.requestSubmit(n);});
async function movement(name,from,to,action){
await settled();close(await ratio(),from);
await page.evaluate(()=>{window.scrollTo({top:0,behavior:'instant'});return new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)));});
const mounted=await layout.elementHandle(),nav=navigations;
await page.screenshot({path:`${evidence}/${name}-initial.png`});
await page.evaluate(()=>{
window.stateFrames=[];window.stateSampling=true;
function tick(t){const w=document.querySelector('[data-explore-layout]'),b=w.querySelector('[data-explore-divider]').getBoundingClientRect(),r=document.querySelector('[data-ribbon-shell]').getBoundingClientRect();
window.stateFrames.push({t,ratio:Number(w.style.getPropertyValue('--explore-ratio')),divider:b.x,ribbon:[r.x,r.y,r.width,r.height]});
if(window.stateSampling)requestAnimationFrame(tick);
}requestAnimationFrame(tick);
});
await action();
await page.waitForFunction(()=>document.querySelector('[data-explore-layout]').hasAttribute('data-resize-animating'));
const shot=await screenshotSession.send('Page.captureScreenshot',{format:'png',captureBeyondViewport:false});
fs.writeFileSync(`${evidence}/${name}-intermediate.png`,Buffer.from(shot.data,'base64'));
await idle();await settled();await page.evaluate(()=>new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r))));
await page.evaluate(()=>window.stateSampling=false);
const samples=await page.evaluate(()=>window.stateFrames),lo=Math.min(from,to),hi=Math.max(from,to);
assert(samples.filter(f=>f.ratio>lo+.005&&f.ratio<hi-.005).length>=4,`${name}: visible intermediate widths`);
assert(new Set(samples.map(f=>Math.round(f.divider))).size>=5,`${name}: divider actually moves`);
for(const f of samples)assert.deepEqual(f.ribbon,samples[0].ribbon,`${name}: stationary ribbon`);
close(await ratio(),to);close(await storage(),.4);
assert.equal(navigations,nav,`${name}: no document reload`);
assert(await mounted.evaluate(n=>n.isConnected),`${name}: workspace remains mounted`);
fs.writeFileSync(`${evidence}/${name}-frames.json`,JSON.stringify(samples,null,2));
await page.screenshot({path:`${evidence}/${name}-final.png`});
}
await movement('return-preferred',.4,.5,()=>journey.getByRole('link',{name:'Return to Explore',exact:true}).evaluate(n=>n.click()));
await ready();assert.equal(new URL(page.url()).searchParams.has('investigation'),false);
assert.equal(await layout.getAttribute('data-explore-state'),'landing');
// A landing adjustment must not change the saved investigation width, including on keyboard adjustment.
await dragTo(.6);await divider.focus();await divider.press('ArrowLeft');close(await storage(),.4);
await page.evaluate(()=>window.dispatchEvent(new PageTransitionEvent('pageshow',{persisted:true})));close(await ratio(),.5);close(await storage(),.4);
await dragTo(.6);await page.reload();await ready();close(await ratio(),.5);
assert((await page.evaluate(()=>window.exploreInitialPaints)).every(v=>v===.5),'Saved 40:60 never paints on landing refresh');
await movement('begin-preferred',.5,.4,scriptedBegin);
await journey.locator('[data-inline-investigation]').waitFor();
// A full-document navigation to plain Explore must land at 50:50 even with an active session-storage entry.
await settled();await page.goto(`${base}/Writer/Explore/Investigate?bookId=12&id=${id}`);
assert.equal(await layout.count(),0,'Standalone investigation has no mounted Explore workspace');
await page.getByRole('link',{name:'Return to Explore',exact:true}).click();await ready();close(await ratio(),.5);
assert((await page.evaluate(()=>window.exploreInitialPaints)).every(v=>v===.5),'Plain Explore does not resurrect the active session or its width');
await page.getByRole('tab',{name:'Saved investigations',exact:true}).click();
await page.locator(`[data-explore-saved] a[href*="${id}"]`).waitFor();
await movement('resume-preferred',.5,.4,()=>page.locator(`[data-explore-saved] a[href*="${id}"]`).evaluate(n=>n.click()));
await movement('new-investigation-landing',.4,.5,()=>journey.getByRole('link',{name:'Start another investigation',exact:true}).evaluate(n=>n.click()));
await ready();await movement('begin-another',.5,.4,scriptedBegin);
// Pointer cancellation and lost capture leave no stuck drag or selection suppression.
let b=await divider.boundingBox();await page.mouse.move(b.x+b.width/2,b.y+60);await page.mouse.down();
await divider.evaluate(n=>n.dispatchEvent(new PointerEvent('pointercancel',{pointerId:1})));await page.mouse.up();
assert.equal(await layout.evaluate(n=>n.classList.contains('writer3-dragging')),false);
for(const theme of ['modern-light','modern-dark'])for(const width of [1666,1280,1024,800,600,390]){
await page.setViewportSize({width,height:1050});await page.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);
await page.waitForFunction(()=>document.querySelector('[data-explore-layout]').dataset.narrow===String(document.querySelector('[data-explore-layout]').clientWidth<=800||innerWidth<=800));
if(width<=800)assert.equal(await divider.isVisible(),false);
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),`${theme}/${width} page overflow`);
for(const selector of ['#explore-discovery','#explore-concern'])assert(await page.locator(selector).evaluate(n=>n.scrollWidth<=n.clientWidth+2),`${theme}/${width} panel overflow`);
if(width===1280||width===600)await page.screenshot({path:`${evidence}/${theme}-${width}.png`});
if(width===600){await page.locator('#explore-concern').scrollIntoViewIfNeeded();await page.screenshot({path:`${evidence}/${theme}-questionnaire-600.png`});}
}
await page.setViewportSize({width:1666,height:1050});
await page.emulateMedia({reducedMotion:'reduce'});
await journey.getByRole('link',{name:'Return to Explore',exact:true}).evaluate(n=>n.click());await ready();await settled();close(await ratio(),.5);
assert.equal(await layout.getAttribute('data-resize-animating'),null);
await scriptedBegin();await settled();close(await ratio(),.4);
assert.equal(await layout.getAttribute('data-resize-animating'),null);
await page.evaluate(()=>{for(const key of Object.keys(localStorage))if(key.startsWith('plotdirector.writerExploreLayout.'))localStorage.removeItem(key);});
await page.goto(url+'#new-investigation');await ready();close(await ratio(),.5);
await begin();await idle();close(await ratio(),.25);
assert.equal(await layout.getAttribute('data-resize-animating'),null);
assert.equal(new URL(page.url()).hash,'','Begin clears the landing-only hash for reliable active refresh');
await page.reload();await journey.locator('[data-inline-investigation]').waitFor();close(await ratio(),.25);
assert((await page.evaluate(()=>window.exploreInitialPaints)).every(v=>v===.25),'Unpreferred active refresh paints 25 directly');
await journey.getByRole('link',{name:'Return to Explore',exact:true}).evaluate(n=>n.click());await ready();await settled();close(await ratio(),.5);
assert.equal(await layout.getAttribute('data-resize-animating'),null);
assert.deepEqual(errors,[]);
console.log(`PASS ${mode}: landing always 50:50; real forward/reverse/resume glides with saved 40:60, direct landing/active refresh, temporary landing drag, unchanged question widths, real save/revision lifecycle, pointer/keyboard/minimums, six widths/two themes, reduced motion.`);
}finally{await context.close();await browser.close();if(profile)fs.rmSync(profile,{recursive:true,force:true});}
})().catch(e=>{console.error(e);process.exitCode=1;});