Separate Explore landing widths from investigation preferences

This commit is contained in:
Nick Beckley 2026-11-20 09:57:01 +00:00
parent 14adc02aa2
commit 5a0eba4570
4 changed files with 95 additions and 19 deletions

View File

@ -1,4 +1,5 @@
// 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');
@ -10,7 +11,15 @@ const base='http://127.0.0.1:5238', url=base+'/Writer/Explore?projectId=7&bookId
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()})));
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{
@ -102,9 +111,59 @@ const base='http://127.0.0.1:5238', url=base+'/Writer/Explore?projectId=7&bookId
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);
await journey.getByRole('link',{name:'Return to Explore',exact:true}).click();await journey.locator('[data-inline-investigation]').waitFor();close(await ratio(),preferred);
await journey.getByRole('link',{name:'Start another investigation',exact:true}).click();await ready();close(await ratio(),preferred);
await begin();await idle();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();
@ -120,11 +179,20 @@ const base='http://127.0.0.1:5238', url=base+'/Writer/Explore?projectId=7&bookId
}
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}: real Begin/answer/revision/save/resume/return/new; stable panels and chrome, intermediate animation frames, no default preference writes, pointer/keyboard/minimums/persistence, six widths/two themes, reduced motion.`);
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;});

View File

@ -63,7 +63,7 @@
<button class="btn btn-outline-secondary" name="operation" value="save">Save for later</button></div></form>
}
@if(row!=null){<form asp-controller="InvestigationCompanion" asp-action="Update" method="post" data-guidance-activate><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@ViewData["GuidanceVersion"]"/><button class="btn btn-outline-secondary" name="operation" value="activate">Keep this investigation alongside my work</button></form>}
<p class="writer3-caption"><a asp-controller="Writer" asp-action="Explore" asp-route-bookId="@Model.BookID" asp-route-projectId="@Model.ProjectID">Return to Explore</a> · <a asp-action="Index" asp-route-bookId="@Model.BookID">Start another investigation</a></p>
<p class="writer3-caption"><a data-explore-landing asp-controller="Writer" asp-action="Explore" asp-route-bookId="@Model.BookID" asp-route-projectId="@Model.ProjectID">Return to Explore</a> · <a data-explore-landing asp-action="Index" asp-route-bookId="@Model.BookID">Start another investigation</a></p>
</section>
<aside class="writer3-panel" aria-label="Your investigations">
@if(row!=null){<h2>Your answers</h2><p>Your answers are saved when you continue. Changing one recomputes the investigation; earlier versions remain in its history.</p><ol>@foreach(var a in row.Answers){var q=Model.Catalogue.Questions.Single(q=>q.Id==a.Question);<li><a asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-id="@row.ID" asp-route-question="@a.Question">@q.Text</a><p>@q.Options.Single(o=>o.Id==a.Option).Text</p></li>}</ol>}

View File

@ -6,10 +6,10 @@
const root = workspace.closest('[data-layout-owner]');
const key = `plotdirector.writerExploreLayout.v1.${root?.dataset.layoutOwner || 'device'}`;
const motion = matchMedia('(prefers-reduced-motion: reduce)');
let manual = null, ratio = .5, active = false, animation = 0, target = .5, drag = null, pointerFrame = 0, pointerX = null;
let investigationPreference = null, ratio = .5, active = !!new URLSearchParams(location.search).get('investigation') && location.hash !== '#new-investigation', animation = 0, target = .5, drag = null, pointerFrame = 0, pointerX = null;
try {
const saved = JSON.parse(localStorage.getItem(key));
if (saved?.version === 1 && Number.isFinite(saved.leftRatio) && saved.leftRatio >= .1 && saved.leftRatio <= .9) manual = saved.leftRatio;
if (saved?.version === 1 && Number.isFinite(saved.leftRatio) && saved.leftRatio >= .1 && saved.leftRatio <= .9) investigationPreference = saved.leftRatio;
} catch { /* Storage may be blocked or contain an old preference. */ }
function bounds() {
const size = parseFloat(getComputedStyle(workspace).getPropertyValue('--explore-divider-size'));
@ -31,7 +31,7 @@
}
function move(value, animate = false) {
stop(); target = value;
if (!animate || motion.matches || workspace.dataset.narrow === 'true') { paint(value); return; }
if (!animate || motion.matches || workspace.dataset.narrow === 'true' || Math.abs(value - ratio) < .0001) { paint(value); return; }
const from = ratio, started = performance.now();
workspace.dataset.resizeAnimating = 'true';
function tick(now) {
@ -43,8 +43,10 @@
animation = requestAnimationFrame(tick);
}
function save() {
manual = ratio; target = ratio;
try { localStorage.setItem(key, JSON.stringify({ version: 1, leftRatio: manual })); } catch { }
target = ratio;
if (!active) return; // Landing adjustments are temporary, never an investigation preference.
investigationPreference = ratio;
try { localStorage.setItem(key, JSON.stringify({ version: 1, leftRatio: investigationPreference })); } catch { }
}
function applyPointer() {
pointerFrame = 0;
@ -89,9 +91,11 @@
});
workspace.addEventListener('writer-explore:state', event => {
const next = event.detail.active;
if (next === active && !event.detail.initial) return;
if (next === active && !event.detail.initial && (active || target === .5 && !drag)) return; // Questions and an already-balanced landing retain their layout.
endDrag(); // Finish in the previous state before choosing the new state's target.
active = next;
if (manual === null && !drag) move(active ? .25 : .5, !event.detail.initial);
workspace.dataset.exploreState = active ? 'investigation' : 'landing';
move(active ? investigationPreference ?? .25 : .5, !event.detail.initial);
});
function measure() {
const narrow = workspace.clientWidth <= 800 || innerWidth <= 800;
@ -101,7 +105,7 @@
workspace.dataset.narrow = String(narrow); divider.tabIndex = narrow ? -1 : 0;
}
// Height changes from questions/reflow must not interrupt or restart an animation.
if (!animation) paint(manual ?? target);
if (!animation) paint(target);
}
let measuredWidth = 0;
new ResizeObserver(() => {
@ -110,7 +114,11 @@
endDrag(); stop(); measure();
}).observe(workspace);
window.addEventListener('resize', () => { endDrag(); stop(); measure(); });
window.addEventListener('pageshow', () => { if (!animation) measure(); });
window.addEventListener('pageshow', event => {
if (event.persisted && !active) { endDrag(); move(.5); }
else if (!animation) measure();
});
motion.addEventListener('change', () => { if (motion.matches && animation) { stop(); paint(target); } });
target = manual ?? .5; measure();
workspace.dataset.exploreState = active ? 'investigation' : 'landing';
target = active ? investigationPreference ?? .25 : .5; measure();
})();

View File

@ -3,11 +3,11 @@
const journey=root.querySelector('[data-explore-journey]'),message=root.querySelector('[data-explore-message]'),saved=root.querySelector('[data-explore-saved]'),workspace=root.closest('.writer3-workspace');let busy=false,dirty=false,current=null;
function tab(name){for(const b of root.querySelectorAll('[data-explore-tab]'))b.setAttribute('aria-selected',String(b.dataset.exploreTab===name));for(const p of root.querySelectorAll('[data-explore-pane]'))p.hidden=p.dataset.explorePane!==name;}
async function history(){const scroll=saved.scrollTop;try{const response=await fetch('/InvestigationCompanion/Saved?bookId='+root.dataset.book,{cache:'no-store'});if(!response.ok)throw Error();const rows=await response.json();saved.replaceChildren();if(!rows.length)saved.textContent='No saved investigations yet.';for(const row of rows){const card=document.createElement('article'),h=document.createElement('h4'),p=document.createElement('p'),a=document.createElement('a');h.textContent=row.concern;p.textContent=row.status+' · '+new Date(row.updatedUtc).toLocaleString();a.textContent=row.hasResults?'Continue / view results':'Continue';a.href=row.resultsUrl;card.append(h,p,a);saved.append(card);}saved.scrollTop=scroll;}catch{saved.textContent='Saved investigations could not load. Select this tab to retry.';}}
async function load(url,options={}){if(busy)return;busy=true;root.setAttribute('aria-busy','true');message.textContent='Loading investigation…';try{const response=await fetch(url,{...options,cache:'no-store',headers:{'X-Writer-Explore':'inline','X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw Error(response.status===409?'Another window changed this investigation. Your text is retained. Open Saved investigations to resume the latest version.':response.status===401?'Sign in again, then resume your saved investigation.':'The investigation could not be updated. Your entered answer remains here. Retry when connected.');const doc=new DOMParser().parseFromString(await response.text(),'text/html'),inline=doc.querySelector('[data-inline-investigation]');if(!inline&&!doc.querySelector('form[action*="Investigate/Start"]'))throw Error('Your session may have expired. Sign in and resume from Saved investigations.');journey.replaceChildren(...(inline?[inline]:doc.body.childNodes));current=inline?.dataset.inlineInvestigation||null;workspace.classList.toggle('writer21-investigating',!!current);workspace.dispatchEvent(new CustomEvent('writer-explore:state',{detail:{active:!!current}}));dirty=false;tab('new');message.textContent='';const address=new URL(location.href);if(current)address.searchParams.set('investigation',current);else address.searchParams.delete('investigation');window.history.replaceState(window.history.state,'',address);try{if(current)sessionStorage.setItem('writer.explore.active.'+root.dataset.book,current);else sessionStorage.removeItem('writer.explore.active.'+root.dataset.book);}catch{}await history();}catch(error){message.textContent=error.message;}finally{busy=false;root.removeAttribute('aria-busy');}}
async function load(url,options={}){if(busy)return;busy=true;root.setAttribute('aria-busy','true');message.textContent='Loading investigation…';try{const response=await fetch(url,{...options,cache:'no-store',headers:{'X-Writer-Explore':'inline','X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw Error(response.status===409?'Another window changed this investigation. Your text is retained. Open Saved investigations to resume the latest version.':response.status===401?'Sign in again, then resume your saved investigation.':'The investigation could not be updated. Your entered answer remains here. Retry when connected.');const doc=new DOMParser().parseFromString(await response.text(),'text/html'),inline=doc.querySelector('[data-inline-investigation]');if(!inline&&!doc.querySelector('form[action*="Investigate/Start"]'))throw Error('Your session may have expired. Sign in and resume from Saved investigations.');journey.replaceChildren(...(inline?[inline]:doc.body.childNodes));current=inline?.dataset.inlineInvestigation||null;workspace.classList.toggle('writer21-investigating',!!current);workspace.dispatchEvent(new CustomEvent('writer-explore:state',{detail:{active:!!current}}));dirty=false;tab('new');message.textContent='';const address=new URL(location.href);if(current)address.searchParams.set('investigation',current);else address.searchParams.delete('investigation');if(address.hash==='#new-investigation')address.hash='';window.history.replaceState(window.history.state,'',address);try{if(current)sessionStorage.setItem('writer.explore.active.'+root.dataset.book,current);else sessionStorage.removeItem('writer.explore.active.'+root.dataset.book);}catch{}await history();}catch(error){message.textContent=error.message;}finally{busy=false;root.removeAttribute('aria-busy');}}
for(const b of root.querySelectorAll('[data-explore-tab]'))b.addEventListener('click',()=>{tab(b.dataset.exploreTab);if(b.dataset.exploreTab==='saved')void history();});
root.addEventListener('input',()=>dirty=true);
root.addEventListener('submit',event=>{const form=event.target;if(form.matches('[data-guidance-activate]')){event.preventDefault();event.stopPropagation();if(busy)return;busy=true;fetch(form.action,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:new FormData(form)}).then(response=>{if(!response.ok)throw Error();message.textContent='This investigation is saved alongside your work.';window.dispatchEvent(new Event('investigation-guidance-updated'));}).catch(()=>message.textContent='Saved guidance could not be updated. Your investigation is retained; reload Saved investigations before retrying.').finally(()=>busy=false);return;}if(!form.closest('[data-explore-journey]')||form.matches('[data-guidance-navigation]'))return;event.preventDefault();event.stopPropagation();if(busy)return;if(!form.reportValidity())return;const data=new FormData(form);if(event.submitter?.name)data.set(event.submitter.name,event.submitter.value);if(event.submitter?.value==='answer'&&!data.get('option')){message.textContent='Choose an answer before continuing.';return;}void load(form.action,{method:'POST',body:data});},true);
root.addEventListener('click',event=>{const a=event.target.closest('a');if(!a)return;const url=new URL(a.href,location.href);if(url.origin!==location.origin||!url.pathname.startsWith('/Writer/Explore/Investigate'))return;event.preventDefault();if(dirty&&!confirm('Leave your unsaved answer and load this investigation?'))return;void load(url);});
root.addEventListener('click',event=>{const a=event.target.closest('a');if(!a)return;const url=new URL(a.href,location.href);const landing=a.matches('[data-explore-landing]');if(url.origin!==location.origin||!landing&&!url.pathname.startsWith('/Writer/Explore/Investigate'))return;event.preventDefault();if(dirty&&!confirm('Leave your unsaved answer and load this investigation?'))return;void load(landing?journey.dataset.openingUrl:url);});
window.addEventListener('beforeunload',event=>{if(dirty||busy){event.preventDefault();event.returnValue='';}});
window.addEventListener('hashchange',()=>{if(location.hash==='#new-investigation'&&(!dirty||confirm('Leave your unsaved answer and start another investigation?')))void load(journey.dataset.openingUrl);});let id=new URLSearchParams(location.search).get('investigation');if(location.hash==='#new-investigation')id=null;else if(!id&&document.referrer.startsWith(location.origin))try{id=sessionStorage.getItem('writer.explore.active.'+root.dataset.book);}catch{}workspace.dispatchEvent(new CustomEvent('writer-explore:state',{detail:{active:!!id,initial:true}}));void load(id?'/Writer/Explore/Investigate?bookId='+root.dataset.book+'&id='+encodeURIComponent(id):journey.dataset.openingUrl);
window.addEventListener('hashchange',()=>{if(location.hash==='#new-investigation'&&(!dirty||confirm('Leave your unsaved answer and start another investigation?')))void load(journey.dataset.openingUrl);});let id=new URLSearchParams(location.search).get('investigation');if(location.hash==='#new-investigation')id=null;workspace.dispatchEvent(new CustomEvent('writer-explore:state',{detail:{active:!!id,initial:true}}));void load(id?'/Writer/Explore/Investigate?bookId='+root.dataset.book+'&id='+encodeURIComponent(id):journey.dataset.openingUrl);
})();