Unify contextual panel lifecycle and expose saved investigations

This commit is contained in:
Nick Beckley 2026-11-18 11:25:22 +00:00
parent 2496f7ab0b
commit ed362fe9c3
21 changed files with 201 additions and 291 deletions

View File

@ -0,0 +1,4 @@
const{chromium}=require('playwright'),fs=require('fs'),assert=require('node:assert/strict');
(async()=>{const b=await chromium.launch();try{const p=await b.newPage({viewport:{width:1440,height:1000}});const panel=side=>`<aside class="pd-context-panel" data-context-panel data-side="${side}" data-state="closed"><button class="plotline-help-collapsed-strip" data-panel-expand>Expand ${side}</button><div class="plotline-help-drawer-panel"><header class="plotline-help-drawer-header">${side}<button data-panel-pin>Pin</button><button data-panel-collapse>Collapse</button><button data-panel-close>Close</button></header><div class="plotline-help-drawer-content">${side} independent content</div></div></aside>`;await p.setContent(`<style>${fs.readFileSync('PlotLine/wwwroot/css/plotline-theme.css','utf8')}\n${fs.readFileSync('PlotLine/wwwroot/css/context-panels.css','utf8')}</style><div data-help-layout class="plotline-help-layout">${panel('left')}<div data-context-splitter="left"></div><main class="plotline-help-main">Main work</main><div data-context-splitter="right"></div>${panel('right')}</div>`);await p.addScriptTag({content:fs.readFileSync('PlotLine/wwwroot/js/context-panels.js','utf8')});await p.evaluate(()=>{window.panels={};for(const root of document.querySelectorAll('[data-context-panel]')){const values={};panels[root.dataset.side]=PlotDirectorContextPanels.create(root,{read:k=>values[k],write:(k,v)=>values[k]=v,changed:({state})=>{if(root.dataset.side==='right'){root.parentElement.classList.toggle('help-open',state!=='closed');root.parentElement.classList.toggle('help-collapsed',state==='collapsed');}}});}});
for(const left of['open','collapsed','closed'])for(const right of['open','collapsed','closed']){await p.evaluate(({left,right})=>{for(const[side,state]of Object.entries({left,right})){panels[side].open();if(state==='closed')panels[side].close();if(state==='collapsed')panels[side].collapse();}},{left,right});for(const[side,state]of Object.entries({left,right})){const r=p.locator(`[data-side=${side}]`);assert.equal(await r.isVisible(),state!=='closed');assert.equal(await r.locator('.plotline-help-drawer-panel').isVisible(),state==='open');assert.equal(await r.locator('[data-panel-expand]').isVisible(),state==='collapsed');}}
await p.evaluate(()=>{panels.left.open();panels.right.open();panels.left.pin();panels.left.collapse();panels.right.close();});assert.equal(await p.locator('[data-side=left]').getAttribute('data-state'),'collapsed');await p.evaluate(()=>panels.left.restore());assert.equal(await p.locator('[data-side=left]').getAttribute('data-state'),'collapsed');await p.evaluate(()=>panels.left.close());await p.evaluate(()=>panels.left.restore());assert.equal(await p.locator('[data-side=left]').isVisible(),false);await p.setViewportSize({width:800,height:1000});await p.evaluate(()=>{panels.left.open();panels.right.open()});assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));console.log('PASS shared panel lifecycle: nine state combinations, independent pins/close, collapsed pin restoration, closed restoration and narrow flow');}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1});

View File

@ -1,55 +1,4 @@
const {chromium}=require('playwright'),fs=require('fs'),assert=require('node:assert/strict');
const live=!!process.env.PD_GUIDANCE_IDENTITY,w=live?JSON.parse(fs.readFileSync(process.env.PD_GUIDANCE_IDENTITY)):{UserID:4,project:7,book:12,otherBook:13};
const base=live?'https://dev.plotdirector.com':'http://127.0.0.1:5238',out=process.env.PD_GUIDANCE_SCREENSHOTS;
(async()=>{const b=await chromium.launch();let state;try{
const c=await b.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(u=>{Object.defineProperty(navigator,'standalone',{value:true});localStorage.setItem('plotdirector.desktop.v1.'+u,JSON.stringify({dismissedAt:Date.now()}));},w.UserID);
const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));
const snap=async name=>{if(out){fs.mkdirSync(out,{recursive:true});await p.mouse.move(2,995);await p.waitForTimeout(150);await p.screenshot({path:out+'/'+name+'.png'});}};
const expandRibbon=async()=>{const toggle=p.locator('[data-ribbon-collapse]');if(await toggle.getAttribute('aria-expanded')==='false')await toggle.click();};
if(live){await p.goto(base+'/Account/Login');await p.locator('[name=Email]').fill(w.Email);await p.locator('[name=Password]').fill(w.Password);await Promise.all([p.waitForURL('**/Projects'),p.locator('button[type=submit]').click()]);}
await p.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`);await expandRibbon();await p.getByRole('link',{name:'Explore a concern',exact:true}).click();
if(live){await p.locator(`a[href*="id=${w.investigation}"]`).first().click();}
else{await p.locator('[name=concern][value=A]').check();await p.getByRole('button',{name:'Begin',exact:true}).click();for(const[q,o]of[['Q02','B'],['Q03','C'],['Q17','F'],['Q19','F'],['Q04','A'],['Q14','D'],['Q15','A'],['Q16','E']]){assert.equal(await p.locator('[data-investigation-answer] [name=question]').inputValue(),q);await p.locator(`[name=option][value=${o}]`).check();await p.getByRole('button',{name:'Continue',exact:true}).click();}w.investigation=await p.locator('[data-investigation-id]').getAttribute('data-investigation-id');}
await p.locator('[data-conclusion]').waitFor();assert.equal(await p.locator('form[target=_blank]').count(),0);const pages=c.pages().length;
if(live){await p.locator('form[action$="/Investigate/Open"]').first().getByRole('button').click();await p.waitForURL(/\/PlotLineWorkspace/);}
else{await p.getByRole('button',{name:'Keep this investigation alongside my work'}).click();await p.goto(`${base}/Writer/Write?projectId=${w.project}&bookId=${w.book}`);}
const root=p.locator('[data-investigation-companion]'),content=root.locator('[data-guidance-content]');await root.locator('#guidance-finding').waitFor();assert.equal(c.pages().length,pages);
assert.equal(await root.getAttribute('data-collapsed'),'false');assert(await p.locator('[data-app-back]').evaluate(n=>!!n.closest('#ribbon-surface')));assert.equal(await p.locator('.pd-ribbon-heading [data-app-back]').count(),0);await snap('Left-expanded-ribbon-Back');
assert((await root.locator('#guidance-finding option').count())>=2);await root.locator('#guidance-finding').selectOption('causality');await p.waitForFunction(()=>document.querySelector('#guidance-finding')?.value==='causality'&&!document.querySelector('#guidance-finding').disabled);await p.reload();await root.locator('#guidance-finding').waitFor();assert.equal(await root.locator('#guidance-finding').inputValue(),'causality');await root.locator('#guidance-finding').selectOption('disconnected');await p.waitForFunction(()=>document.querySelectorAll('.pd-guidance-tool').length===2&&!document.querySelector('#guidance-finding').disabled);
await root.getByText('Answers that informed this suggestion',{exact:true}).click();await root.locator('details').getByText('You answered:',{exact:true}).waitFor();
const first=root.locator('.pd-guidance-tool[data-capability=threads]');if(live)assert.equal(await first.locator('select').inputValue(),'Exploring');await first.locator('select').selectOption('Done');await p.waitForFunction(()=>document.querySelector('.pd-guidance-tool[data-capability=threads] select')?.value==='Done'&&!document.querySelector('#guidance-finding').disabled);await p.reload();await first.waitFor();assert.equal(await first.locator('select').inputValue(),'Done');
await p.route('**/InvestigationCompanion/Update',r=>r.fulfill({status:503,json:{message:'Simulated unconfirmed progress save; previous state retained.'}}));await first.locator('select').selectOption('Skipped');await root.locator('[data-guidance-message]').filter({hasText:'unconfirmed progress'}).waitFor();assert.equal(await first.locator('select').inputValue(),'Done');await p.unroute('**/InvestigationCompanion/Update');await p.reload();await first.waitFor();assert.equal(await first.locator('select').inputValue(),'Done');
// Right Help opens independently and does not replace guidance.
await p.evaluate(()=>PlotLineHelpDrawer.open('plotLines.workspace'));await p.locator('[data-help-content] .help-drawer-article').waitFor();await p.locator('[data-help-pin]').click();assert.equal(await root.getAttribute('data-collapsed'),'false');assert(await p.locator('[data-help-drawer]').isVisible());assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));assert((await p.locator('.plotline-help-main').boundingBox()).width>=560);await snap('Both-panels-expanded');
await p.locator('[data-guidance-resize]').focus();for(let n=0;n<12;n++)await p.keyboard.press('ArrowRight');await p.setViewportSize({width:1100,height:1000});await p.waitForTimeout(200);assert((await p.locator('.plotline-help-main').boundingBox()).width>=560);assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));if(live)assert(await p.locator('.plot-workspace-controls').evaluate(n=>{const r=n.closest('.plotline-help-main').getBoundingClientRect();return [...n.querySelectorAll('input:not([type=hidden]),select,button')].every(c=>{const b=c.getBoundingClientRect();return b.left>=r.left&&b.right<=r.right;});}));await snap('Both-panels-minimum-centre');await p.setViewportSize({width:1440,height:1000});for(let n=0;n<12;n++)await p.keyboard.press('ArrowLeft');
await root.locator('[data-guidance-collapse]').click();assert.equal(await root.getAttribute('data-collapsed'),'true');assert(await root.locator('.pd-investigation-panel').isHidden());await snap('Left-collapsed-tab');await p.reload();await root.locator('[data-guidance-expand]').waitFor();assert.equal(await root.getAttribute('data-collapsed'),'true');await root.locator('[data-guidance-expand]').click();await root.locator('#guidance-finding').waitFor();
if(live){await root.locator('.pd-guidance-tool[data-capability=timeline] form button').click();await p.waitForURL(/\/Timeline/);await root.locator('#guidance-finding').waitFor();assert.equal(c.pages().length,pages);assert.equal(await root.locator('.pd-guidance-tool[data-capability=timeline]').getAttribute('data-selected'),'true');await snap('Second-destination-Timeline');}
else{await p.goto(`${base}/Writer/Review?bookId=${w.book}&projectId=${w.project}`);await root.locator('#guidance-finding').waitFor();}
await expandRibbon();await p.getByRole('tab',{name:'Writer',exact:true}).click();await p.waitForURL(u=>/\/Writer(?:\/Index)?$/.test(u.pathname));await root.locator('#guidance-finding').waitFor();await expandRibbon();await p.locator('[data-app-back]').click();await p.waitForURL(live?/\/Timeline/:/\/Writer\/Review/);await root.locator('#guidance-finding').waitFor();assert(await first.locator('select').inputValue()==='Done');await snap('Ribbon-Back-retains-guidance');
await p.setViewportSize({width:800,height:1000});assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));assert((await root.locator('.pd-investigation-panel').boundingBox()).height<=551);await snap('Narrow-in-flow');await p.setViewportSize({width:1440,height:1000});
state=await c.storageState();await c.close();const reopened=await b.newContext({storageState:state,viewport:{width:1440,height:1000}});await reopened.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));const q=await reopened.newPage();await q.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`);await q.locator('#guidance-finding').waitFor();assert.equal(await q.locator('.pd-guidance-tool[data-capability=threads] select').inputValue(),'Done');
await q.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.otherBook}`);await q.waitForFunction(()=>document.querySelector('[data-guidance-content]')?.textContent.includes('No active investigation'));assert.equal(await q.locator('#guidance-finding').count(),0);assert.equal(await q.locator('[data-investigation-companion]').getAttribute('data-collapsed'),'true');await q.locator('[data-guidance-expand]').click();const resume=await q.getByRole('link',{name:'Open saved investigations',exact:true}).getAttribute('href');assert.equal(new URL(resume).searchParams.get('bookId'),String(w.otherBook));
// In-page book context changes use the same event as Calendar/At This Point and recheck server scope.
await q.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:book-context-changed',{detail:{bookId:0}})));await q.waitForFunction(()=>document.querySelector('[data-guidance-content]')?.textContent.includes('Choose a book'));await q.locator('[data-guidance-expand]').click();assert(!(new URL(await q.getByRole('link',{name:'Choose a book in Writer to resume an investigation'}).getAttribute('href'))).searchParams.has('bookId'));
await q.evaluate(book=>{const url=new URL(location.href);url.searchParams.set('bookId',String(book));history.replaceState(history.state,'',url);document.dispatchEvent(new CustomEvent('plotdirector:book-context-changed',{detail:{bookId:book}}));},w.book);await q.locator('#guidance-finding').waitFor();
// Server-side failure paths retain the active guidance; forged IDs never expose it.
const token=await q.locator('[data-guidance-token] [name=__RequestVerificationToken]').inputValue();const response=await q.request.post(base+'/InvestigationCompanion/Open',{form:{__RequestVerificationToken:token,bookId:w.book,id:w.investigation,finding:'disconnected',capability:'invented'}});assert.equal(response.status(),400);
const wrong=await q.request.get(base+`/InvestigationCompanion/Evidence?bookId=${w.otherBook}&id=${w.investigation}&finding=disconnected`);assert.equal(wrong.status(),404);
const invalid=await q.request.get(base+`/InvestigationCompanion/Evidence?bookId=${w.book}&id=00000000-0000-0000-0000-000000000000&finding=disconnected`);assert.equal(invalid.status(),404);
// Old/invalid presentation preferences recover without changing server progress.
await q.evaluate(u=>localStorage.setItem(`plotdirector.investigationPanel.v1.${u.user}.${u.book}`,JSON.stringify({width:-99,positions:'stale'})),{user:w.UserID,book:w.book});await q.reload();await q.locator('#guidance-finding').waitFor();assert.equal(await q.locator('.pd-guidance-tool[data-capability=threads] select').inputValue(),'Done');
await q.route('**/InvestigationCompanion/Summary?*',r=>r.fulfill({status:503,body:'unavailable'}));await q.reload();await q.locator('[data-guidance-expand]').click();await q.getByRole('button',{name:'Retry',exact:true}).waitFor();await q.unroute('**/InvestigationCompanion/Summary?*');await q.getByRole('button',{name:'Retry',exact:true}).click();await q.locator('#guidance-finding').waitFor();
// Pin has the same restore-on-navigation meaning as contextual Help.
await q.locator('[data-guidance-pin]').click();await q.reload();await q.waitForFunction(()=>document.querySelector('[data-guidance-content]')?.textContent.includes('Full investigation results'));assert.equal(await q.locator('[data-investigation-companion]').getAttribute('data-collapsed'),'true');await q.locator('[data-guidance-expand]').click();await q.locator('[data-guidance-pin]').click();await q.reload();await q.locator('#guidance-finding').waitFor();assert.equal(await q.locator('[data-investigation-companion]').getAttribute('data-collapsed'),'false');
const full=await q.getByRole('link',{name:'Full investigation results',exact:true}).getAttribute('href');await q.getByRole('button',{name:'Dismiss guidance',exact:true}).click();await q.waitForFunction(()=>document.querySelector('[data-guidance-content]')?.textContent.includes('No active investigation'));await q.goto(base+full);await q.getByRole('button',{name:'Keep this investigation alongside my work'}).click();await q.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`);await q.waitForFunction(()=>document.querySelector('#guidance-finding'));assert.equal(await q.locator('[data-investigation-companion]').getAttribute('data-collapsed'),'true');await q.locator('[data-guidance-expand]').click();await q.locator('#guidance-finding').waitFor();
assert.deepEqual(errors,[]);await reopened.close();
if(live&&process.env.PD_GUIDANCE_OTHER_IDENTITY){
const other=JSON.parse(fs.readFileSync(process.env.PD_GUIDANCE_OTHER_IDENTITY)),oc=await b.newContext(),op=await oc.newPage();await op.goto(base+'/Account/Login');await op.locator('[name=Email]').fill(other.Email);await op.locator('[name=Password]').fill(other.Password);await Promise.all([op.waitForURL('**/Projects'),op.locator('button[type=submit]').click()]);
const view=await op.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`);assert.equal(view.status(),200);await op.locator('[data-guidance-token]').waitFor({state:'attached'});const ot=await op.locator('[data-guidance-token] [name=__RequestVerificationToken]').inputValue();
const summary=await op.request.get(`${base}/InvestigationCompanion/Summary?projectId=${w.project}&bookId=${w.book}`);assert.equal(summary.status(),200);assert.equal((await summary.json()).active,false);
assert.equal((await op.request.get(`${base}/InvestigationCompanion/Evidence?bookId=${w.book}&id=${w.investigation}&finding=disconnected`)).status(),404);
assert.equal((await op.request.post(base+'/InvestigationCompanion/Update',{form:{__RequestVerificationToken:ot,bookId:w.book,id:w.investigation,version:0,operation:'activate'}})).status(),404);await oc.close();
}
console.log('PASS '+(live?'authenticated Development':'isolated Razor/HTTP')+' investigation companion: saved results, same-window destinations, two findings, private server progress, Help coexistence, collapse/expand, refresh and reopened PWA session, Back ribbon action, book isolation, invalid IDs and unavailable destination');
}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1});
// Compatibility entry point: Phase 1.5 placeholder-tab/unpinned-collapse expectations were superseded.
// Without Development credentials this runs lifecycle isolation only, not server persistence qualification.
if(process.env.PD_GUIDANCE_IDENTITY){process.env.PD_UX_IDENTITY=process.env.PD_GUIDANCE_IDENTITY;process.env.PD_UX_SCREENSHOTS=process.env.PD_GUIDANCE_SCREENSHOTS;require('./investigation-ux-correction.cjs');}
else{require('./context-panel-lifecycle.cjs');}

View File

@ -0,0 +1,20 @@
const{chromium}=require('playwright'),fs=require('fs'),assert=require('node:assert/strict');
(async()=>{const w=JSON.parse(fs.readFileSync(process.env.PD_UX_IDENTITY)),base='https://dev.plotdirector.com',out=process.env.PD_UX_SCREENSHOTS,b=await chromium.launch(),timings=[];try{const c=await b.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(u=>{Object.defineProperty(navigator,'standalone',{value:true});localStorage.setItem('plotdirector.desktop.v1.'+u,JSON.stringify({dismissedAt:Date.now()}));},w.UserID);const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.exposeFunction('navigationAck',ms=>timings.push({ackMs:ms}));await p.addInitScript(()=>{document.addEventListener('submit',e=>{if(!e.target.matches('[data-guidance-navigation]'))return;const start=performance.now(),observer=new MutationObserver(()=>{if(e.target.textContent.includes('Opening…')){window.navigationAck(performance.now()-start);observer.disconnect();}});observer.observe(e.target,{subtree:true,childList:true,characterData:true});},true);});const shot=async name=>{if(out){fs.mkdirSync(out,{recursive:true});await p.mouse.move(2,995);await p.screenshot({path:out+'/'+name+'.png'});}};
await p.goto(base+'/Account/Login');await p.locator('[name=Email]').fill(w.Email);await p.locator('[name=Password]').fill(w.Password);await Promise.all([p.waitForURL('**/Projects'),p.locator('button[type=submit]').click()]);const explore=`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`;await p.goto(explore);await p.locator('[data-my-investigations] article').first().waitFor();await shot('My-investigations');const root=p.locator('[data-investigation-companion]'),help=p.locator('[data-help-drawer]');
// Starting from saved results does not activate guidance. Continue is explicit.
assert(await root.isHidden());assert(await root.locator('[data-guidance-expand]').isHidden());
const older=p.locator('[data-my-investigations] article').filter({has:p.locator(`input[name=id][value="${w.oldInvestigation}"]`)});await older.getByRole('button',{name:'Continue',exact:true}).click();await p.waitForFunction(()=>document.querySelector('[data-guidance-content]')?.textContent.includes('older investigation'));assert.equal(await root.locator('.pd-guidance-tool').count(),0);await shot('Older-investigation');await p.goto(explore);await p.locator('[data-my-investigations] article').first().waitFor();const card=p.locator('[data-my-investigations] article').filter({has:p.locator(`input[name=id][value="${w.investigation}"]`)});await card.getByRole('button',{name:'Continue',exact:true}).click();await p.locator('[data-conclusion]').waitFor();await root.waitFor();const count=c.pages().length;
for(let n=0;n<3;n++){if(n)await p.goto(`${base}/Writer/Explore/Investigate?bookId=${w.book}&id=${w.investigation}`);const network=[];const capture=r=>{if(r.request().isNavigationRequest()||r.url().includes('/InvestigationCompanion/Summary'))network.push({url:new URL(r.url()).pathname,status:r.status(),timing:r.request().timing(),serverTiming:r.headers()['server-timing']});};p.on('response',capture);const start=Date.now();await p.locator('form[data-guidance-navigation]').first().getByRole('button').click();await p.waitForURL(/PlotLineWorkspace/);const documentMs=Date.now()-start;await root.locator('#guidance-finding').waitFor();timings.push({documentMs,restoredMs:Date.now()-start,network});p.removeListener('response',capture);}
assert.equal(c.pages().length,count);const panelContent=root.locator('.plotline-help-drawer-panel');assert.equal(await root.getAttribute('data-state'),'open');await p.evaluate(()=>PlotLineHelpDrawer.open('plotLines.workspace'));await help.locator('.help-drawer-article').waitFor();await shot('Both-open');
for(const left of['open','collapsed','closed'])for(const right of['open','collapsed','closed']){
if(await root.getAttribute('data-state')!=='open')await p.locator('[data-guidance-open]').click();if(left==='collapsed')await root.locator('[data-guidance-collapse]').click();if(left==='closed')await root.locator('[data-guidance-close]').click();
await p.evaluate(()=>PlotLineHelpDrawer.open('plotLines.workspace'));await help.locator('.help-drawer-article').waitFor();if(right==='collapsed')await help.locator('[data-help-collapse]').click();if(right==='closed')await help.locator('[data-help-close]').click();
assert.equal(await root.isVisible(),left!=='closed');assert.equal(await panelContent.isVisible(),left==='open');assert.equal(await help.isVisible(),right!=='closed');assert.equal(await help.locator('.plotline-help-drawer-panel').isVisible(),right==='open');}
await p.locator('[data-guidance-open]').click();await p.evaluate(()=>PlotLineHelpDrawer.open('plotLines.workspace'));await help.locator('.help-drawer-article').waitFor();await root.locator('[data-guidance-close]').click();await shot('Help-only');assert(await help.isVisible());await p.locator('[data-guidance-open]').click();await help.locator('[data-help-close]').click();await shot('Investigation-only');
// A close is presentation only, and a saved selector changes only authorised guidance.
const before=await (await p.request.get(base+`/InvestigationCompanion/Summary?projectId=${w.project}&bookId=${w.book}`)).json();await root.locator('[data-guidance-close]').click();const after=await (await p.request.get(base+`/InvestigationCompanion/Summary?projectId=${w.project}&bookId=${w.book}`)).json();assert.equal(after.summary.version,before.summary.version);await p.reload();assert(await root.isHidden());await p.locator('[data-guidance-open]').click();
const picker=root.getByLabel('Switch saved investigation');await picker.focus();await picker.locator(`option[value="${w.secondInvestigation}"]`).waitFor({state:'attached'});await picker.selectOption(w.secondInvestigation);await p.waitForFunction(()=>document.querySelector('[data-guidance-content] a')?.href.includes(window.location.origin)&&document.querySelector('[data-guidance-content] a')?.href.includes('id='));await p.waitForFunction(id=>document.querySelector('[data-guidance-content] a')?.href.includes(id),w.secondInvestigation);assert((await root.getByRole('link',{name:'Full investigation results'}).getAttribute('href')).includes(w.secondInvestigation));
await root.locator('[data-guidance-pin]').click(); // pin (Close unpinned it)
await root.locator('.pd-guidance-tool[data-capability=timeline] form button').click();await p.waitForURL(/Timeline/);await root.locator('#guidance-finding').waitFor();await shot('Timeline');await p.reload();await root.locator('#guidance-finding').waitFor();assert.equal(await root.getAttribute('data-state'),'open');
await root.locator('[data-guidance-pin]').click();await root.locator('.pd-guidance-tool select').first().selectOption('Done');await p.waitForFunction(()=>document.querySelector('[data-guidance-message]')?.textContent==='');assert.equal(await root.getAttribute('data-state'),'open');await p.reload();assert(await root.isHidden());await p.locator('[data-guidance-open]').click();await p.setViewportSize({width:800,height:1000});await p.evaluate(()=>PlotLineHelpDrawer.open('timeline.overview'));await help.locator('.help-drawer-article').waitFor();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await shot('Narrow-both');await root.locator('[data-guidance-close]').click();assert(await help.isVisible());
await p.setViewportSize({width:1440,height:1000});await p.goto(explore);await p.locator('[data-my-investigations] article').first().waitFor();assert(await root.isHidden());await p.locator('[data-guidance-open]').click();await root.getByRole('button',{name:'Finish this journey'}).click();await p.waitForFunction(()=>document.querySelector('[data-investigation-companion]')?.dataset.state==='closed');assert.equal((await (await p.request.get(base+`/InvestigationCompanion/Summary?bookId=${w.book}`)).json()).active,false);await p.goto(explore);await p.locator('[data-my-investigations] article').first().waitFor();const original=p.locator('[data-my-investigations] article').filter({has:p.locator(`input[name=id][value="${w.investigation}"]`)});await original.getByRole('link',{name:'Original results'}).click();assert.equal((await (await p.request.get(base+`/InvestigationCompanion/Summary?bookId=${w.book}`)).json()).active,false);await p.goto(explore);await p.locator('[data-my-investigations] article').filter({has:p.locator(`input[name=id][value="${w.investigation}"]`)}).getByRole('button',{name:'Continue',exact:true}).click();await root.locator('#guidance-finding').waitFor();if(await root.locator('[data-guidance-pin]').textContent()==='Pin')await root.locator('[data-guidance-pin]').click();await p.goto(`${base}/Writer/Review?projectId=${w.project}&bookId=${w.book}`);await root.locator('#guidance-finding').waitFor();await p.evaluate(()=>PlotLineHelpDrawer.open('writer3.reviewing'));const prior=[await root.getAttribute('data-state'),await help.getAttribute('data-state')];await p.locator('#reader-focus').click();assert(await root.evaluate(n=>n.inert));assert(await help.evaluate(n=>n.inert));await p.locator('#reader-focus').click();assert.deepEqual([await root.getAttribute('data-state'),await help.getAttribute('data-state')],prior);await shot('Writer-review');assert.deepEqual(errors,[]);fs.writeFileSync(process.env.PD_UX_TIMINGS||'/tmp/ux-timings.json',JSON.stringify(timings,null,2));console.log('PASS authenticated UX correction: saved discovery, nine independent lifecycle pairs, close preserves guidance, explicit reopen, switching, pin/unpin navigation/refresh, no duplicate windows, progress, narrow layout');await c.close();}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1});

View File

@ -0,0 +1,13 @@
IF DB_NAME()<>N'PlotDirector_Development' THROW 51000,'Wrong database',1;
DECLARE @u int=(SELECT UserID FROM dbo.AppUser WHERE Email=N'pwa-browser-writeraudit-20261116@example.invalid' AND DisplayName=N'Disposable Writer Audit 20261116');
DECLARE @b int=(SELECT TOP(1) BookID FROM dbo.WriterInvestigations WHERE UserID=@u ORDER BY UpdatedUtc DESC);
IF @b IS NULL THROW 51000,'Disposable saved investigations required',1;
DECLARE @r TABLE(ID uniqueidentifier,BookID int,CatalogueVersion varchar(80),Concern nvarchar(100),Status varchar(100),UpdatedUtc datetime2,GuidanceVersion int,IsActive bit,Finished bit);
INSERT @r EXEC dbo.WriterInvestigationSavedSummaries @UserID=@u,@BookID=@b;
IF (SELECT COUNT(*) FROM @r)<2 THROW 51000,'Missing saved investigations',1;
IF EXISTS(SELECT 1 FROM @r WHERE BookID<>@b OR GuidanceVersion<0) THROW 51000,'Bad summary metadata',1;
DELETE @r;INSERT @r EXEC dbo.WriterInvestigationSavedSummaries @UserID=-123456,@BookID=@b;
IF EXISTS(SELECT 1 FROM @r) THROW 51000,'Cross-user list leak',1;
INSERT @r EXEC dbo.WriterInvestigationSavedSummaries @UserID=@u,@BookID=-1;
IF EXISTS(SELECT 1 FROM @r) THROW 51000,'Cross-book list leak',1;
SELECT 'PASS private compact saved list, metadata and author/book isolation' Result;

View File

@ -8,7 +8,7 @@ namespace PlotLine.Controllers;
public sealed class InvestigationCompanionController(InvestigationAccess gate,IInvestigationGuidanceRepository repository,InvestigationGuidanceService service,IInvestigationRepository investigations):Controller
{
IActionResult Error(int status,string message){
if(ControllerContext.ActionDescriptor.ActionName==nameof(Open)){
if((ControllerContext.ActionDescriptor.ActionName==nameof(Open)||ControllerContext.ActionDescriptor.ActionName==nameof(Update)&&Request.Headers["X-Requested-With"]!="XMLHttpRequest")){
Response.StatusCode=status;ViewData["Failure"]=message;
if(int.TryParse(Request.Form["bookId"],out var book))ViewData["BookID"]=book;
if(Guid.TryParse(Request.Form["id"],out var id))ViewData["InvestigationID"]=id;
@ -27,6 +27,13 @@ public sealed class InvestigationCompanionController(InvestigationAccess gate,II
var(verified,c)=await Verify(r); // same ownership guard as explicit IDs
return Json(new{active=true,summary=service.Summary(verified,c),resultsUrl=Url.Action("Index","WriterInvestigations",new{bookId=r.BookID,id=r.ID})});
});
[HttpGet("/InvestigationCompanion/Saved")]
public Task<IActionResult> Saved(int bookId)=>Guard(async()=>{
var rows=await repository.List(Author,bookId);var result=new List<object>();
foreach(var row in rows){var c=await service.Catalogue(row.CatalogueVersion);if(c.Synthetic&&!(await HttpContext.RequestServices.GetRequiredService<IAuthorizationService>().AuthorizeAsync(User,null,"AdminOnly")).Succeeded)continue;
result.Add(new{row.ID,row.BookID,row.GuidanceVersion,updatedUtc=DateTime.SpecifyKind(row.UpdatedUtc,DateTimeKind.Utc),status=row.Finished?"Journey finished":row.IsActive?"Active guidance · "+row.Status:row.Status,concern=c.Concerns.SingleOrDefault(x=>x.Id==row.Concern)?.Text??"Saved investigation",resultsUrl=Url.Action("Index","WriterInvestigations",new{bookId,id=row.ID}),continueUrl=Url.Action("Update",new{bookId,id=row.ID})});}
return Json(result);
});
[HttpGet("/InvestigationCompanion/Evidence")]
public Task<IActionResult> Evidence(int bookId,Guid id,string finding)=>Guard(async()=>{
var(r,c)=await Load(null,bookId,id);var(i,_,s)=InvestigationGuidanceService.Decode(r);service.Select(r,c,s,finding,null);
@ -41,9 +48,9 @@ public sealed class InvestigationCompanionController(InvestigationAccess gate,II
if(operation=="progress"){if(capability==null||!InvestigationGuidanceService.ProgressStates.Contains(progress))throw new ArgumentException("Choose a progress state.");s.Progress[InvestigationGuidanceService.Key(finding!,capability)]=progress!;}
}else if(operation is not("activate" or "dismiss" or "finish"))throw new ArgumentException("Unknown guidance action.");
await service.Save(Author,r,s,operation is "select" or "progress"?"save":operation);
if(operation=="activate")return RedirectToAction("Index","WriterInvestigations",new{bookId,id});
if(operation=="activate"&&Request.Headers["X-Requested-With"]!="XMLHttpRequest")return RedirectToAction("Index","WriterInvestigations",new{bookId,id});
return Json(new{ok=true});
});
[HttpPost("/InvestigationCompanion/Open"),ValidateAntiForgeryToken]
public Task<IActionResult> Open(int bookId,Guid id,string finding,string capability)=>Guard(async()=>{var(r,c)=await Load(null,bookId,id);var target=await service.Open(Author,r,c,finding,capability);return RedirectToAction(target.Action,target.Controller,target.Values);});
public Task<IActionResult> Open(int bookId,Guid id,string finding,string capability)=>Guard(async()=>{var timer=System.Diagnostics.Stopwatch.StartNew();var(r,c)=await Load(null,bookId,id);Response.Headers.Append("Server-Timing",FormattableString.Invariant($"guidance-load;dur={timer.Elapsed.TotalMilliseconds:F2}"));var target=await service.Open(Author,r,c,finding,capability,(name,ms)=>Response.Headers.Append("Server-Timing",FormattableString.Invariant($"{name};dur={ms:F2}")));return RedirectToAction(target.Action,target.Controller,target.Values);});
}

View File

@ -43,10 +43,13 @@ public sealed class WriterInvestigationsController(InvestigationAccess gate,IInv
});
[HttpPost("/Writer/Explore/Investigate/Open"),ValidateAntiForgeryToken]
public Task<IActionResult> Open(int bookId,Guid id,int version,string capability)=>Guard(async()=>{
var(i,c)=await service.Read(Author,bookId,id);await EnsureCatalogue(c);if(version!=i.Version)throw new ArgumentException("Resume the latest version before opening a tool.");
var r=await guidance.Read(Author,i.ProjectID,bookId,id)??throw new KeyNotFoundException();
var timer=System.Diagnostics.Stopwatch.StartNew();
var r=await guidance.Read(Author,null,bookId,id)??throw new KeyNotFoundException();Response.Headers.Append("Server-Timing",FormattableString.Invariant($"guidance-read;dur={timer.Elapsed.TotalMilliseconds:F2}"));timer.Restart();
var i=InvestigationGuidanceService.Decode(r).Investigation;var c=await companion.Catalogue(i.CatalogueVersion);await EnsureCatalogue(c);
Response.Headers.Append("Server-Timing",FormattableString.Invariant($"catalogue-authorization;dur={timer.Elapsed.TotalMilliseconds:F2}"));
if(i.UserID!=Author||i.BookID!=bookId||i.ProjectID!=r.ProjectID)throw new UnauthorizedAccessException();if(version!=i.Version)throw new ArgumentException("Resume the latest version before opening a tool.");
var saved=InvestigationGuidanceService.Decode(r);var finding=InvestigationGuidanceService.Recommended(saved.Investigation,saved.Evaluation).FirstOrDefault(h=>c.Hypotheses.Single(x=>x.Id==h).Capabilities.Contains(capability))??throw new ArgumentException("This destination is not currently recommended.");
var target=await companion.Open(Author,r,c,Request.Form["finding"].FirstOrDefault()??finding,capability);
var target=await companion.Open(Author,r,c,Request.Form["finding"].FirstOrDefault()??finding,capability,(name,ms)=>Response.Headers.Append("Server-Timing",FormattableString.Invariant($"{name};dur={ms:F2}")));
return RedirectToAction(target.Action,target.Controller,target.Values);
});
[Authorize(Policy="AdminOnly"),HttpGet("/admin/writer-investigations")]

View File

@ -7,13 +7,16 @@ public sealed class GuidanceRecord
public string InvestigationJson {get;set;}="";public string? EvaluationJson {get;set;}public string? GuidanceJson {get;set;}
public int GuidanceVersion {get;set;}public bool IsActive {get;set;}public bool Finished {get;set;}
}
public sealed record SavedInvestigation(Guid ID,int BookID,string CatalogueVersion,string Concern,string Status,DateTime UpdatedUtc,int GuidanceVersion,bool IsActive,bool Finished);
public interface IInvestigationGuidanceRepository
{
Task<GuidanceRecord?> Read(int user,int? project,int? book,Guid? id=null);
Task<IReadOnlyList<SavedInvestigation>> List(int user,int book)=>Task.FromResult<IReadOnlyList<SavedInvestigation>>([]);
Task Save(int user,int book,Guid id,int version,string operation,string json);
}
public sealed class InvestigationGuidanceRepository(ISqlConnectionFactory factory):IInvestigationGuidanceRepository
{
public async Task<GuidanceRecord?> Read(int user,int? project,int? book,Guid? id=null){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<GuidanceRecord>("dbo.WriterInvestigationGuidanceState",new{Action="read",UserID=user,ProjectID=project,BookID=book,ID=id},commandType:CommandType.StoredProcedure);}
public async Task<IReadOnlyList<SavedInvestigation>> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync<SavedInvestigation>("dbo.WriterInvestigationSavedSummaries",new{UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();}
public async Task Save(int user,int book,Guid id,int version,string operation,string json){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterInvestigationGuidanceState",new{Action=operation,UserID=user,BookID=book,ID=id,ExpectedVersion=version,Json=json},commandType:CommandType.StoredProcedure);}
}

View File

@ -38,12 +38,14 @@ public sealed class InvestigationGuidanceService(IInvestigationGuidanceRepositor
state.Finding=finding;state.Capability=capability;
}
public Task Save(int user,GuidanceRecord r,GuidanceState state,string operation)=>guidance.Save(user,r.BookID,r.ID,r.GuidanceVersion,operation,JsonSerializer.Serialize(state,CatalogueValidator.Json));
public async Task<(string Controller,string Action,object Values)> Open(int user,GuidanceRecord r,Catalogue c,string finding,string capability)
public async Task<(string Controller,string Action,object Values)> Open(int user,GuidanceRecord r,Catalogue c,string finding,string capability,Action<string,double>? timed=null)
{
var timer=System.Diagnostics.Stopwatch.StartNew();
var(i,_,s)=Decode(r);Select(r,c,s,finding,capability);var d=c.Capabilities.SingleOrDefault(d=>d.Id==capability)??throw new ArgumentException("Tool unavailable.");
if(!Available(d,i))throw new ArgumentException("This tool is currently unavailable. Your investigation is retained.");
// Opening never completes a step, nor resets an explicit Done/Skipped decision.
var key=Key(finding,capability);if(s.Progress.GetValueOrDefault(key,"Not started")=="Not started")s.Progress[key]="Exploring";
await Save(user,r,s,"activate");return DestinationRegistry.Resolve(d,i.ProjectID,i.BookID,true,i.Answers.ToDictionary(a=>a.Question))!.Value;
timed?.Invoke("eligibility-registry",timer.Elapsed.TotalMilliseconds);timer.Restart();
await Save(user,r,s,"activate");timed?.Invoke("guidance-save",timer.Elapsed.TotalMilliseconds);return DestinationRegistry.Resolve(d,i.ProjectID,i.BookID,true,i.Answers.ToDictionary(a=>a.Question))!.Value;
}
}

View File

@ -0,0 +1,18 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.WriterInvestigationSavedSummaries @UserID int,@BookID int AS
BEGIN
SET NOCOUNT ON;
SELECT TOP(50) i.ID,i.BookID,i.CatalogueVersion,JSON_VALUE(i.Json,'$.Concern') Concern,
CASE WHEN JSON_VALUE(i.Json,'$.CurrentQuestion') IS NOT NULL THEN 'In progress' WHEN e.Event IS NULL THEN 'Older saved investigation' ELSE 'Results available' END Status,
i.UpdatedUtc,ISNULL(g.Version,0) GuidanceVersion,ISNULL(g.IsActive,0) IsActive,ISNULL(g.Finished,0) Finished
FROM dbo.WriterInvestigations i
JOIN dbo.Books b ON b.BookID=i.BookID AND b.ProjectID=i.ProjectID AND b.IsArchived=0
JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0
JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1
LEFT JOIN dbo.WriterInvestigationGuidance g ON g.InvestigationID=i.ID AND g.UserID=@UserID
LEFT JOIN dbo.WriterInvestigationEvents e ON e.InvestigationID=i.ID AND e.Version=i.Version
WHERE i.UserID=@UserID AND i.BookID=@BookID ORDER BY i.UpdatedUtc DESC,i.ID;
END;
GO

View File

@ -0,0 +1,19 @@
-- Include explicit follow-through in the saved investigation activity timestamp.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.WriterInvestigationSavedSummaries @UserID int,@BookID int AS
BEGIN
SET NOCOUNT ON;
SELECT TOP(50) i.ID,i.BookID,i.CatalogueVersion,JSON_VALUE(i.Json,'$.Concern') Concern,
CASE WHEN JSON_VALUE(i.Json,'$.CurrentQuestion') IS NOT NULL THEN 'In progress' WHEN e.Event IS NULL THEN 'Older saved investigation' ELSE 'Results available' END Status,
CASE WHEN g.UpdatedUtc>i.UpdatedUtc THEN g.UpdatedUtc ELSE i.UpdatedUtc END UpdatedUtc,ISNULL(g.Version,0) GuidanceVersion,ISNULL(g.IsActive,0) IsActive,ISNULL(g.Finished,0) Finished
FROM dbo.WriterInvestigations i
JOIN dbo.Books b ON b.BookID=i.BookID AND b.ProjectID=i.ProjectID AND b.IsArchived=0
JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0
JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1
LEFT JOIN dbo.WriterInvestigationGuidance g ON g.InvestigationID=i.ID AND g.UserID=@UserID
LEFT JOIN dbo.WriterInvestigationEvents e ON e.InvestigationID=i.ID AND e.Version=i.Version
WHERE i.UserID=@UserID AND i.BookID=@BookID ORDER BY UpdatedUtc DESC,i.ID;
END;
GO

View File

@ -127,7 +127,7 @@
<button type="button" class="pd-ribbon-collapse" data-ribbon-collapse aria-expanded="@(!appearance.RibbonCollapsed ? "true" : "false")" aria-controls="ribbon-surface" title="Collapse or expand ribbon">@(appearance.RibbonCollapsed ? "Expand ribbon" : "Collapse ribbon") <span aria-hidden="true">⌃</span></button>
</div>
<div id="ribbon-surface" class="pd-ribbon-surface" hidden="@appearance.RibbonCollapsed">
<div class="pd-ribbon-group pd-ribbon-history" role="group" aria-label="Navigation"><div class="pd-ribbon-commands"><button type="button" class="pd-ribbon-command pd-ribbon-back" data-app-back disabled aria-label="Back" title="Back to previous PlotDirector page"><svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon("back").IconPath" /></svg><span>Back</span></button></div><span class="pd-ribbon-group-label">Navigation</span></div>
<div class="pd-ribbon-group pd-ribbon-history" role="group" aria-label="Navigation"><div class="pd-ribbon-commands"><button type="button" class="pd-ribbon-command pd-ribbon-back" data-app-back disabled aria-label="Back" title="Back to previous PlotDirector page"><svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon("back").IconPath" /></svg><span>Back</span></button><button type="button" class="pd-ribbon-command" data-guidance-open hidden><svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon("point").IconPath" /></svg><span>Investigation</span></button></div><span class="pd-ribbon-group-label">Navigation</span></div>
@foreach (var category in ApplicationRibbon.Categories)
{
<div class="pd-ribbon-panel" id="ribbon-panel-@category.Key" role="tabpanel" aria-labelledby="ribbon-tab-@category.Key" hidden="@(category.Key != selectedCategory)">

View File

@ -1,14 +1,14 @@
@model ApplicationNavigationViewModel
<aside class="pd-investigation" data-investigation-companion data-collapsed="true" data-user="@User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value" data-project="@Model.Project?.ProjectID" data-book="@Model.Book?.BookID"
data-summary-url="@Url.Action("Summary","InvestigationCompanion")" data-update-url="@Url.Action("Update","InvestigationCompanion")" data-open-url="@Url.Action("Open","InvestigationCompanion")" data-evidence-url="@Url.Action("Evidence","InvestigationCompanion")" data-start-url="@Url.Action("Index","WriterInvestigations")" data-choose-url="@Url.Action("Index","Writer",new{projectId=Model.Project?.ProjectID})" aria-label="Investigation companion">
<button type="button" class="pd-investigation-tab" data-guidance-expand aria-label="Expand investigation companion" title="Expand investigation companion" aria-expanded="false" aria-controls="investigation-panel">Investigation</button>
<div class="plotline-help-drawer-panel pd-investigation-panel" id="investigation-panel">
<aside class="pd-investigation pd-context-panel" data-context-panel data-state="closed" data-side="left" data-investigation-companion data-collapsed="true" data-user="@User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value" data-project="@Model.Project?.ProjectID" data-book="@Model.Book?.BookID"
data-summary-url="@Url.Action("Summary","InvestigationCompanion")" data-update-url="@Url.Action("Update","InvestigationCompanion")" data-open-url="@Url.Action("Open","InvestigationCompanion")" data-evidence-url="@Url.Action("Evidence","InvestigationCompanion")" data-start-url="@Url.Action("Index","WriterInvestigations")" data-saved-url="@Url.Action("Saved","InvestigationCompanion")" data-choose-url="@Url.Action("Index","Writer",new{projectId=Model.Project?.ProjectID})" aria-label="Investigation companion">
<button type="button" class="plotline-help-collapsed-strip pd-investigation-tab" data-guidance-expand data-panel-expand aria-label="Expand investigation companion" title="Expand investigation companion" aria-expanded="false" aria-controls="investigation-panel">Investigation</button>
<div class="plotline-help-drawer-panel" id="investigation-panel">
<header class="plotline-help-drawer-header"><div><p class="eyebrow mb-0">Investigation</p><strong data-guidance-title>Your story concern</strong></div>
<div class="btn-group btn-group-sm" role="group" aria-label="Investigation panel controls"><button class="btn btn-outline-secondary" type="button" data-guidance-pin aria-pressed="true">Unpin</button><button class="btn btn-outline-secondary" type="button" data-guidance-collapse aria-label="Collapse investigation companion">Collapse</button></div>
<div class="btn-group btn-group-sm" role="group" aria-label="Investigation panel controls"><button class="btn btn-outline-secondary" type="button" data-guidance-pin data-panel-pin aria-pressed="true">Unpin</button><button class="btn btn-outline-secondary" type="button" data-guidance-collapse data-panel-collapse aria-label="Collapse investigation companion">Collapse</button><button class="btn btn-outline-secondary" type="button" data-guidance-close data-panel-close>Close</button></div>
</header>
<div class="plotline-help-drawer-content" data-guidance-content><p>Loading saved guidance…</p></div>
<p class="pd-guidance-message" role="status" data-guidance-message></p>
</div>
<form hidden data-guidance-token>@Html.AntiForgeryToken()</form>
</aside>
<div class="pd-investigation-splitter" data-guidance-resize role="separator" tabindex="0" aria-label="Resize investigation companion" aria-orientation="vertical" aria-valuemin="280" aria-valuemax="440" aria-valuenow="320" title="Drag to resize; use Left and Right arrow keys"></div>
<div class="pd-investigation-splitter" data-guidance-resize data-context-splitter="left" hidden role="separator" tabindex="0" aria-label="Resize investigation companion" aria-orientation="vertical" aria-valuemin="20" aria-valuemax="50" aria-valuenow="25" title="Drag to resize; use Left and Right arrow keys"></div>

View File

@ -116,6 +116,7 @@
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/plotline-theme.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/context-panels.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/onboarding.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/story-intelligence-global-progress.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/plot-line-workspace.css" asp-append-version="true" />
@ -290,9 +291,9 @@
}
</div>
</div>
<div class="plotline-help-splitter" data-help-splitter role="separator" aria-orientation="vertical" aria-label="Resize help drawer"></div>
<aside class="plotline-help-drawer" data-help-drawer aria-label="Help drawer">
<div class="plotline-help-collapsed-strip" data-help-expand role="button" tabindex="0" aria-label="Expand help drawer">Help</div>
<div class="plotline-help-splitter" data-help-splitter data-context-splitter="right" hidden tabindex="0" aria-valuemin="20" aria-valuemax="50" aria-valuenow="25" role="separator" aria-orientation="vertical" aria-label="Resize help drawer"></div>
<aside class="plotline-help-drawer pd-context-panel" data-context-panel data-state="closed" data-side="right" data-help-drawer aria-label="Help drawer">
<div class="plotline-help-collapsed-strip" data-help-expand data-panel-expand role="button" tabindex="0" aria-label="Expand help drawer">Help</div>
<div class="plotline-help-drawer-panel">
<header class="plotline-help-drawer-header">
<div>
@ -300,9 +301,9 @@
<strong data-help-drawer-heading>Help</strong>
</div>
<div class="btn-group btn-group-sm" role="group" aria-label="Help drawer controls">
<button class="btn btn-outline-secondary" type="button" data-help-pin aria-pressed="false">Pin</button>
<button class="btn btn-outline-secondary" type="button" data-help-collapse>Collapse</button>
<button class="btn btn-outline-secondary" type="button" data-help-close>Close</button>
<button class="btn btn-outline-secondary" type="button" data-help-pin data-panel-pin aria-pressed="false">Pin</button>
<button class="btn btn-outline-secondary" type="button" data-help-collapse data-panel-collapse>Collapse</button>
<button class="btn btn-outline-secondary" type="button" data-help-close data-panel-close>Close</button>
</div>
</header>
<div class="plotline-help-drawer-content" data-help-content>
@ -341,6 +342,7 @@
}
<script src="~/js/application-dialogs.js" asp-append-version="true"></script>
<script src="~/js/workspace-bridge.js" asp-append-version="true"></script>
<script src="~/js/context-panels.js" asp-append-version="true"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@if (User.Identity?.IsAuthenticated == true)
{

View File

@ -3,6 +3,7 @@
<div class="writer3-workspace" aria-label="Story exploration">
<section class="writer3-panel writer3-main" tabindex="0">
@if(InvestigationAccess.Enabled && Model.BookID.HasValue){<section class="writer3-inset"><h2>What's troubling you about your story?</h2><p>You don't need to know the answer yet. Work through a concern one question at a time.</p><a class="btn btn-primary" asp-controller="WriterInvestigations" asp-action="Index" asp-route-bookId="@Model.BookID">Explore a concern</a><p class="writer3-caption">Explore your concern through questions and practical writing actions. Suggestions use your answers, not manuscript analysis.</p></section>}
@if(InvestigationAccess.Enabled&&Model.BookID.HasValue){<section class="writer3-inset" data-my-investigations data-book="@Model.BookID" data-url="@Url.Action("Saved","InvestigationCompanion")"><h2>My Investigations</h2><p>Continue a saved concern or revisit its original results.</p><div class="pd-investigation-list" data-saved-investigations><p>Loading your saved investigations…</p></div></section>}
<p class="eyebrow">Start with your question</p><h2>What would you like to explore?</h2><p>You do not need a finished outline or a linked manuscript. Choose a starting point.</p>
<div class="writer3-explore-paths">
<a asp-controller="Writer" asp-action="Write" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID"><span class="writer3-path-mark" aria-hidden="true">01</span><div><h3>Develop a chapter or scene</h3><p>Work with your saved chapter intentions, scene ideas and reminders.</p></div><span aria-hidden="true">→</span></a>

View File

@ -44,7 +44,7 @@
}</ul>
@if(state!.Recommendations.Contains(finding.Hypothesis)){
@foreach(var cap in Model.Catalogue.Capabilities.Where(d=>Model.Catalogue.Hypotheses.Single(h=>h.Id==finding.Hypothesis).Capabilities.Contains(d.Id)&&state.AvailableCapabilities.Contains(d.Id))){
<p>@cap.Description</p><form asp-action="Open" method="post"><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/><input type="hidden" name="finding" value="@finding.Hypothesis"/><button class="btn btn-primary" name="capability" value="@cap.Id">@cap.ActionText</button></form>
<p>@cap.Description</p><form asp-action="Open" method="post" data-guidance-navigation><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/><input type="hidden" name="finding" value="@finding.Hypothesis"/><button class="btn btn-primary" name="capability" value="@cap.Id">@cap.ActionText</button></form>
}
}
</section>
@ -59,7 +59,7 @@
@if(row.Answers.Count>=Model.Catalogue.MaxAnswers&&state.Recommendations.Count==0){<p>We've reached the question limit for this test. You can still change earlier answers or save and return later.</p>}
@foreach(var id in state.Recommendations){var h=Model.Catalogue.Hypotheses.Single(h=>h.Id==id);<section class="writer3-inset"><h3>@h.Summary</h3><p>@h.Reason</p><p class="muted">@h.Uncertainty</p>
<p>Answers that informed this suggestion:</p><ul>@foreach(var evidence in state.Evidence.Where(e=>e.Hypothesis==id&&e.Raw>0&&!e.Uncertain).DistinctBy(e=>e.Question).Take(3)){var q=Model.Catalogue.Questions.Single(q=>q.Id==evidence.Question);<li>@q.Text — @q.Options.Single(o=>o.Id==evidence.Option).Text</li>}</ul>
@foreach(var cap in Model.Catalogue.Capabilities.Where(d=>h.Capabilities.Contains(d.Id)&&state.AvailableCapabilities.Contains(d.Id))){<p>@cap.Description</p><form asp-action="Open" method="post"><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/><input type="hidden" name="finding" value="@id"/><button class="btn btn-primary" name="capability" value="@cap.Id">@cap.ActionText</button></form>}
@foreach(var cap in Model.Catalogue.Capabilities.Where(d=>h.Capabilities.Contains(d.Id)&&state.AvailableCapabilities.Contains(d.Id))){<p>@cap.Description</p><form asp-action="Open" method="post" data-guidance-navigation><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/><input type="hidden" name="finding" value="@id"/><button class="btn btn-primary" name="capability" value="@cap.Id">@cap.ActionText</button></form>}
</section>}
}
@if(row.Accepted){<p role="status">Your response is saved. Return to this investigation whenever you need it.</p>}
@ -69,7 +69,7 @@
@if(row.Answers.Count<Model.Catalogue.MaxAnswers&&state.Candidates.Count>0){<button class="btn btn-outline-secondary" name="operation" value="further">I'd like to investigate further</button>}
<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"><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>}
@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>
</section>
<aside class="writer3-panel" aria-label="Your investigations">

View File

@ -0,0 +1,27 @@
/* Both drawers are instances of the same root-scoped panel system. */
.plotline-help-layout{--context-sticky-top:8px;--context-panel-surface:rgba(255,253,248,.96);--context-panel-border:rgba(107,114,128,.22)}
.pd-context-panel{display:block;flex:0 0 clamp(20%,var(--context-panel-width,25%),50%);min-width:0;background:var(--context-panel-surface);color:var(--plotline-ink);border-inline:1px solid var(--context-panel-border)}
.pd-context-panel[data-state=closed]{display:none}
.pd-context-panel[data-state=collapsed]{flex:0 0 2.35rem;min-width:2.35rem;max-width:2.35rem}
.pd-context-panel>.plotline-help-drawer-panel{position:sticky;top:var(--context-sticky-top);max-height:calc(100dvh - var(--context-sticky-top) - 8px)}
.pd-context-panel[data-state=collapsed]>.plotline-help-drawer-panel{display:none}
.pd-context-panel>.plotline-help-collapsed-strip{display:none}
.pd-context-panel[data-state=collapsed]>.plotline-help-collapsed-strip{display:flex;position:sticky;top:var(--context-sticky-top);writing-mode:vertical-rl;align-items:center;justify-content:center;width:2.35rem;min-height:140px;padding:1rem .5rem;border:0;color:var(--plotline-muted);background:transparent;font:inherit;font-size:.78rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase;cursor:pointer}
.pd-context-panel .plotline-help-drawer-header{flex-wrap:wrap;overflow-wrap:anywhere}
.pd-context-panel .plotline-help-drawer-content{min-height:0;overscroll-behavior:contain}
[data-context-splitter]{flex:0 0 8px;cursor:col-resize;touch-action:none;background:linear-gradient(90deg,transparent,var(--context-panel-border),transparent)}
[data-context-splitter][hidden]{display:none}
[data-panel-expand]:focus-visible,[data-context-splitter]:focus-visible{outline:2px solid var(--pd-focus);outline-offset:-2px}
@media(min-width:1100px){.plotline-help-layout[data-open-panels="2"]>.pd-context-panel[data-state=open]{flex-basis:clamp(240px,var(--context-panel-width,25%),calc((100% - 576px)/2))}}
@media(max-width:1099px){
.plotline-help-layout{flex-wrap:wrap}
.plotline-help-layout>.pd-context-panel[data-state=open]{flex:0 0 100%;min-width:0;max-width:100%;width:100%}
.pd-context-panel>.plotline-help-drawer-panel{position:relative;top:0;max-height:50dvh}
[data-context-splitter]{display:none}
.plotline-help-layout>.pd-context-panel[data-side=right][data-state=open]{order:-1}
.plotline-help-layout[data-open-panels="2"]{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr)}
.plotline-help-layout[data-open-panels="2"]>[data-side=left]{grid-row:1;grid-column:1}
.plotline-help-layout[data-open-panels="2"]>[data-side=right]{grid-row:1;grid-column:2}
.plotline-help-layout[data-open-panels="2"]>.plotline-help-main{grid-row:2;grid-column:1/-1}
}
body.reader-focused .pd-context-panel,body.reader-focused [data-context-splitter]{visibility:hidden}

View File

@ -1,50 +1,7 @@
/* Independent left guidance and existing right Help, sharing the application's drawer shell. */
.plotline-help-layout:has([data-investigation-companion]){--context-sticky-top:8px;--investigation-width:320px}
.pd-investigation{flex:0 0 var(--investigation-width);width:var(--investigation-width);min-width:0;border-right:1px solid var(--pd-border-subtle);background:var(--pd-surface);color:var(--pd-text)}
.pd-investigation .pd-investigation-panel{top:var(--context-sticky-top);max-height:calc(100dvh - var(--context-sticky-top) - 8px)}
.pd-investigation .plotline-help-drawer-header{flex-wrap:wrap;padding:.85rem}
.pd-investigation .plotline-help-drawer-content{padding:.85rem;min-height:0;overscroll-behavior:contain}
.pd-investigation-tab{display:none}
.pd-investigation[data-collapsed=true]{flex-basis:36px;width:36px}
.pd-investigation[data-collapsed=true]>.pd-investigation-panel{display:none}
.pd-investigation[data-collapsed=true]>.pd-investigation-tab{display:block;position:sticky;top:var(--context-sticky-top);writing-mode:vertical-rl;min-height:140px;width:36px;border:0;background:var(--pd-surface-2);color:var(--pd-text);padding:1rem .5rem;font:inherit;cursor:pointer}
.pd-investigation-tab:focus-visible,.pd-investigation-splitter:focus-visible{outline:2px solid var(--pd-focus);outline-offset:-2px}
.pd-investigation-splitter{flex:0 0 8px;cursor:col-resize;touch-action:none;background:linear-gradient(90deg,transparent,var(--pd-border-subtle),transparent)}
.pd-investigation[data-collapsed=true]+.pd-investigation-splitter{display:none}
.pd-guidance-message{margin:0;padding:0 .85rem .5rem;font-size:.85rem}
.pd-investigation h2{font-size:1.1rem}.pd-investigation h3{font-size:1rem}.pd-investigation p,.pd-investigation label{font-size:.9rem}
.pd-guidance-message{margin:0;padding:0 1rem .5rem;font-size:.85rem}
.pd-guidance-tool{border:1px solid var(--pd-border-subtle);border-radius:6px;margin:1rem 0;padding:.65rem}
.pd-guidance-tool[data-selected=true]{border-color:var(--pd-accent);box-shadow:inset 3px 0 var(--pd-accent)}
.pd-guidance-tool button,.pd-guidance-tool select{max-width:100%;white-space:normal}
.pd-investigation select{width:100%;min-width:0}.pd-investigation .btn{white-space:normal}
/* Correct existing Help sticky containment without coupling its business state to Investigation. */
.plotline-help-layout:has([data-investigation-companion])>.plotline-help-drawer>.plotline-help-drawer-panel{top:var(--context-sticky-top);max-height:calc(100dvh - var(--context-sticky-top) - 8px)}
.plotline-help-layout:has([data-investigation-companion])>.plotline-help-drawer .plotline-help-drawer-content{min-height:0}
.plotline-help-layout:has([data-investigation-companion]) .plotline-help-collapsed-strip{position:sticky;top:var(--context-sticky-top);min-height:140px}
/* Bound all three columns: reserve at least 560px for the central surface at desktop widths. */
@media(min-width:1100px){.plotline-help-layout:has(.pd-investigation[data-collapsed=false]).help-open:not(.help-collapsed)>.plotline-help-drawer{min-width:240px;max-width:max(240px,calc(100% - var(--investigation-width) - 576px));flex-basis:clamp(240px,var(--help-drawer-width),360px)}}
@media(max-width:1099px){
.pd-investigation[data-collapsed=false]{flex-basis:min(var(--investigation-width),calc(100% - 480px));width:min(var(--investigation-width),calc(100% - 480px))}
/* Small windows use an in-flow, full-width guidance row. No overlay and no lost main controls. */
.plotline-help-layout:has(.pd-investigation[data-collapsed=false]){flex-wrap:wrap}
.plotline-help-layout>.pd-investigation[data-collapsed=false]{flex:0 0 100%;width:100%;border-bottom:1px solid var(--pd-border)}
.pd-investigation[data-collapsed=false]+.pd-investigation-splitter{display:none}
.pd-investigation .pd-investigation-panel{position:relative;top:0;max-height:55dvh}
.plotline-help-layout:has([data-investigation-companion]).help-open>.plotline-help-drawer{flex-basis:36px;min-width:36px;max-width:36px}
.plotline-help-layout:has([data-investigation-companion]).help-open>.plotline-help-drawer .plotline-help-drawer-panel{display:none}
.plotline-help-layout:has([data-investigation-companion]).help-open>.plotline-help-drawer .plotline-help-collapsed-strip{display:flex;width:36px;writing-mode:vertical-rl;cursor:pointer}
.plotline-help-layout:has([data-investigation-companion]).help-open>.plotline-help-splitter{display:none}
.plotline-help-layout:has([data-investigation-companion]).help-open[data-narrow-help=true]>.plotline-help-drawer{flex:0 0 100%;width:100%;max-width:100%;order:4}
.plotline-help-layout:has([data-investigation-companion]).help-open[data-narrow-help=true]{flex-wrap:wrap}
.plotline-help-layout[data-narrow-help=true]>.plotline-help-drawer .plotline-help-drawer-panel{display:flex;position:relative;top:0;max-height:55dvh}
.plotline-help-layout[data-narrow-help=true]>.plotline-help-drawer .plotline-help-collapsed-strip{display:none}
}
body.reader-focused .pd-investigation,body.reader-focused .pd-investigation-splitter{visibility:hidden}
@media(min-width:1100px){
.plotline-help-layout.help-open:not(.help-collapsed)>.pd-investigation[data-collapsed=false]{flex-basis:clamp(280px,var(--investigation-width),calc(100% - 816px));width:clamp(280px,var(--investigation-width),calc(100% - 816px))}
}
.plotline-help-layout:has([data-investigation-companion])>.plotline-help-drawer .plotline-help-drawer-header{flex-wrap:wrap;overflow-wrap:anywhere}
/* Existing Plot Lines filters must respond to the remaining working width, not only window width. */
.plotline-help-layout:has([data-investigation-companion]) .plot-control-row{grid-template-columns:repeat(auto-fit,minmax(min(100%,180px),1fr))}
.plotline-help-layout:has([data-investigation-companion]) .plot-control-row>label{min-width:0}
.plot-control-row{grid-template-columns:repeat(auto-fit,minmax(min(100%,180px),1fr))}.plot-control-row>label{min-width:0}
.pd-investigation-list{display:grid;gap:.75rem;margin:1rem 0}.pd-investigation-list article{border:1px solid var(--pd-border-subtle);border-radius:6px;padding:.85rem}.pd-investigation-list p{margin:.4rem 0}
[data-guidance-navigation][aria-busy=true] button{opacity:.65;cursor:progress}

View File

@ -3216,61 +3216,6 @@ a:focus-visible {
transition: flex-basis 0.18s ease;
}
.plotline-help-splitter,
.plotline-help-drawer {
display: none;
}
.plotline-help-layout.help-open .plotline-help-splitter {
display: block;
flex: 0 0 8px;
cursor: col-resize;
background: linear-gradient(90deg, transparent, rgba(107, 114, 128, 0.22), transparent);
}
.plotline-help-layout.help-open .plotline-help-drawer {
display: block;
flex: 0 0 clamp(20%, var(--help-drawer-width), 50%);
min-width: 20%;
max-width: 50%;
border-left: 1px solid rgba(107, 114, 128, 0.22);
background: rgba(255, 253, 248, 0.96);
transition: flex-basis 0.18s ease;
}
.plotline-help-layout.help-collapsed .plotline-help-splitter {
display: none;
}
.plotline-help-layout.help-collapsed .plotline-help-drawer {
flex-basis: 2.35rem;
min-width: 2.35rem;
max-width: 2.35rem;
}
.plotline-help-layout.help-collapsed .plotline-help-drawer-panel {
display: none;
}
.plotline-help-collapsed-strip {
display: none;
}
.plotline-help-layout.help-collapsed .plotline-help-collapsed-strip {
display: flex;
align-items: center;
justify-content: center;
width: 2.35rem;
min-height: calc(100vh - 5rem);
color: #5f6875;
font-size: 0.78rem;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
writing-mode: vertical-rl;
cursor: pointer;
}
.plotline-help-drawer-panel {
position: sticky;
top: 0;
@ -3408,7 +3353,7 @@ a:focus-visible {
border-color: #f1c38f;
}
[data-theme="dark"] .plotline-help-layout.help-open .plotline-help-drawer {
[data-theme="dark"] .pd-context-panel {
border-left-color: rgba(255, 255, 255, 0.12);
background: rgba(22, 22, 27, 0.97);
}

View File

@ -0,0 +1,16 @@
// One lifecycle/resize implementation; each drawer owns its state and storage independently.
(() => {
const instances=new Map();
window.PlotDirectorContextPanels={create(root,{read=()=>null,write=()=>{},changed=()=>{}}={}){
if(instances.has(root))return instances.get(root);
const layout=root.closest('[data-help-layout]'),side=root.dataset.side,splitter=layout.querySelector(`[data-context-splitter="${side}"]`);
let state='closed',pinned=read('pinned')==='true',width=Number.parseFloat(read('width'))||25,drag=null;
const clamp=n=>Math.max(20,Math.min(50,n));
function paint(){root.dataset.state=state;root.style.setProperty('--context-panel-width',clamp(width)+'%');const pin=root.querySelector('[data-panel-pin]');if(pin){pin.textContent=pinned?'Unpin':'Pin';pin.setAttribute('aria-pressed',String(pinned));}const collapse=root.querySelector('[data-panel-collapse]');if(collapse)collapse.textContent=state==='collapsed'?'Expand':'Collapse';root.querySelector('[data-panel-expand]')?.setAttribute('aria-expanded',String(state==='open'));if(splitter){splitter.hidden=state!=='open';splitter.setAttribute('aria-valuenow',String(Math.round(clamp(width))));splitter.setAttribute('aria-valuetext',Math.round(clamp(width))+'% preferred width, constrained to keep the workspace usable');}layout.dataset.openPanels=String(layout.querySelectorAll(':scope > [data-context-panel][data-state="open"]').length);changed({state,pinned});document.dispatchEvent(new CustomEvent('plotdirector:panel-layout-changed'));}
const api={get state(){return state},get pinned(){return pinned},open({restore=false}={}){state=restore&&read('collapsed')==='true'?'collapsed':'open';if(!restore){write('collapsed','false');write('closed','false');}paint();},collapse(){state=state==='collapsed'?'open':'collapsed';write('collapsed',String(state==='collapsed'));paint();},close(){state='closed';pinned=false;write('pinned','false');write('closed','true');paint();},hide(){state='closed';paint();},pin(){pinned=!pinned;write('pinned',String(pinned));paint();},restore(){pinned=read('pinned')==='true';width=Number.parseFloat(read('width'))||25;if(pinned&&read('closed')!=='true')api.open({restore:true});else api.hide();}};
root.querySelector('[data-panel-pin]')?.addEventListener('click',api.pin);root.querySelector('[data-panel-close]')?.addEventListener('click',api.close);root.querySelector('[data-panel-collapse]')?.addEventListener('click',()=>{api.collapse();if(state==='collapsed')root.querySelector('[data-panel-expand]')?.focus();});const expand=root.querySelector('[data-panel-expand]');expand?.addEventListener('click',()=>{state='open';write('collapsed','false');paint();});expand?.addEventListener('keydown',e=>{if(expand.tagName!=='BUTTON'&&(e.key==='Enter'||e.key===' ')){e.preventDefault();expand.click();}});
const resize=n=>{width=clamp(n);write('width',width+'%');paint();};splitter?.addEventListener('keydown',e=>{if(!['ArrowLeft','ArrowRight'].includes(e.key))return;e.preventDefault();resize(width+(e.key==='ArrowRight'?(side==='left'?1:-1):(side==='left'?-1:1)));});splitter?.addEventListener('pointerdown',e=>{if(e.button!==0)return;drag=e.pointerId;splitter.setPointerCapture(drag);e.preventDefault();});splitter?.addEventListener('pointermove',e=>{if(drag!==e.pointerId)return;const r=layout.getBoundingClientRect();resize((side==='left'?e.clientX-r.left:r.right-e.clientX)/r.width*100);});for(const type of['pointerup','pointercancel','lostpointercapture'])splitter?.addEventListener(type,()=>drag=null);
paint();instances.set(root,api);return api;
}};
const layout=document.querySelector('[data-help-layout]'),header=document.querySelector('.pd-application-header');if(layout&&header){const measure=()=>layout.style.setProperty('--context-sticky-top',(getComputedStyle(header).position==='sticky'?Math.ceil(header.getBoundingClientRect().height):0)+8+'px');new ResizeObserver(measure).observe(header);measure();}
})();

View File

@ -3,22 +3,29 @@
const root=document.querySelector('[data-investigation-companion]');if(!root)return;
const layout=root.closest('[data-help-layout]'),content=root.querySelector('[data-guidance-content]'),message=root.querySelector('[data-guidance-message]'),tab=root.querySelector('[data-guidance-expand]'),splitter=layout.querySelector('[data-guidance-resize]');
const token=root.querySelector('[name=__RequestVerificationToken]').value;
let current=null,resultsUrl=null,epoch=0,request,busy=false,preference={},drag=null;
let current=null,resultsUrl=null,epoch=0,request,busy=false,preference={},hydrated=false;
const storageKey=()=>`plotdirector.investigationPanel.v1.${root.dataset.user}.${current?.bookID||root.dataset.book||root.dataset.project||'none'}`;
const read=()=>{try{const value=JSON.parse(localStorage.getItem(storageKey()));if(!value||typeof value!=='object'||Array.isArray(value))return {};if(!value.positions||typeof value.positions!=='object'||Array.isArray(value.positions))value.positions={};return value;}catch{return {};}};
const pendingKey=`plotdirector.guidance.open.${root.dataset.user}`;
const readPanel=name=>{const v=read();if(name==='pinned')return String(v.pinned!==false);if(name==='width')return String(v.panelWidth||(typeof v.width==='number'?v.width/Math.max(1,layout.clientWidth)*100:25));if(name==='closed')return String(v.closed===true);return String(v[name]??false);};
const panel=PlotDirectorContextPanels.create(root,{read:readPanel,write:(name,value)=>{const v=read();v[name==='width'?'panelWidth':name]=name==='width'?parseFloat(value):value==='true';try{localStorage.setItem(storageKey(),JSON.stringify(v));}catch{}preference=v;},changed:({state,pinned})=>{root.dataset.collapsed=String(state==='collapsed');document.querySelector('[data-guidance-open]')?.setAttribute('aria-expanded',String(state==='open'));}});
document.querySelector('[data-guidance-open]')?.addEventListener('click',()=>{if(current)panel.open();});
const save=()=>{try{localStorage.setItem(storageKey(),JSON.stringify(preference));}catch{}};
const element=(tag,text,cls)=>{const n=document.createElement(tag);if(text!=null)n.textContent=text;if(cls)n.className=cls;return n;};
const btn=(text,fn)=>{const n=element('button',text,'btn btn-outline-secondary btn-sm');n.type='button';n.addEventListener('click',fn);return n;};
function collapse(value,persist=true){root.dataset.collapsed=String(value);tab.setAttribute('aria-expanded',String(!value));if(persist){preference.collapsed=value;save();}measure();}
function paintPreference(){root.querySelector('[data-guidance-pin]').textContent=preference.pinned===false?'Pin':'Unpin';root.querySelector('[data-guidance-pin]').setAttribute('aria-pressed',String(preference.pinned!==false));setWidth(preference.width||320,false);collapse(preference.collapsed===true||preference.pinned===false||!current,false);}
function setWidth(value,persist=true){const width=Math.max(280,Math.min(440,Number(value)||320));layout.style.setProperty('--investigation-width',width+'px');splitter.setAttribute('aria-valuenow',String(width));if(persist){preference.width=width;save();}}
function measure(){const h=document.querySelector('.pd-application-header'),top=h&&getComputedStyle(h).position==='sticky'?h.getBoundingClientRect().height:0;layout.style.setProperty('--context-sticky-top',Math.ceil(top)+8+'px');}
function restorePanel(restore=true){
const opener=document.querySelector('[data-guidance-open]');if(opener)opener.hidden=!current;
if(!current){panel.hide();return;}
let pending;try{pending=sessionStorage.getItem(pendingKey);}catch{}
if(pending===current.id){try{sessionStorage.removeItem(pendingKey);}catch{}panel.restore();panel.open();}else if(restore)panel.restore();
}
function failure(text){message.textContent=text;}
function startLink(){const book=Number(root.dataset.book),a=element('a',book>0?'Open saved investigations':'Choose a book in Writer to resume an investigation');const url=new URL(book>0?root.dataset.startUrl:root.dataset.chooseUrl,location.origin);if(book>0)url.searchParams.set('bookId',String(book));a.href=url.href;return a;}
function render(){
content.replaceChildren();message.textContent='';root.querySelector('[data-guidance-title]').textContent=current?.bookTitle||'Your story concern';
if(!current){content.append(element('p','No active investigation for this context.'),startLink());return;}
const summary=element('a','Full investigation results');summary.href=resultsUrl;content.append(summary,element('h2',current.concern),element('p',current.message));
const picker=element('select',null,'form-select');picker.setAttribute('aria-label','Switch saved investigation');const initial=element('option','Switch investigation…');initial.value='';picker.append(initial);picker.addEventListener('focus',async()=>{if(picker.dataset.loaded)return;try{for(const item of await saved(current.bookID)){const option=element('option',item.concern+' · '+item.id.slice(0,8));option.value=item.id;option.dataset.version=item.guidanceVersion;picker.append(option);}picker.dataset.loaded='true';}catch{failure('Saved investigations could not be loaded. Use My Investigations in Explore.');}});picker.addEventListener('change',()=>{const option=picker.selectedOptions[0];if(option.value)activate(option.value,Number(option.dataset.version),current.bookID);});content.append(picker);
const summary=element('a','Full investigation results');summary.href=resultsUrl;content.append(summary,element('h3','Your concern'),element('p',current.concern),element('p',current.message));
if(current.findings.length){
const label=element('label','Finding');label.htmlFor='guidance-finding';const select=element('select',null,'form-select');select.id='guidance-finding';
for(const f of current.findings){const o=element('option',f.title);o.value=f.id;select.append(o);}select.value=current.findings.some(f=>f.id===current.finding)?current.finding:current.findings[0].id;
@ -30,7 +37,7 @@
for(const tool of f.tools){
const card=element('section',null,'pd-guidance-tool');card.dataset.selected=String(current.finding===f.id&&current.capability===tool.id);card.dataset.capability=tool.id;
card.append(element('h3',tool.name),element('p',tool.why));
if(tool.available){const form=element('form');form.method='post';form.action=root.dataset.openUrl;for(const [name,value]of Object.entries({__RequestVerificationToken:token,bookId:current.bookID,id:current.id,finding:f.id,capability:tool.id})){const input=element('input');input.type='hidden';input.name=name;input.value=value;form.append(input);}const open=element('button',tool.action||'Open tool','btn btn-primary btn-sm');open.type='submit';form.append(open);card.append(form);}
if(tool.available){const form=element('form');form.method='post';form.action=root.dataset.openUrl;form.dataset.guidanceNavigation='';for(const [name,value]of Object.entries({__RequestVerificationToken:token,bookId:current.bookID,id:current.id,finding:f.id,capability:tool.id})){const input=element('input');input.type='hidden';input.name=name;input.value=value;form.append(input);}const open=element('button',tool.action||'Open tool','btn btn-primary btn-sm');open.type='submit';form.append(open);card.append(form);}
else card.append(element('p','This destination is currently unavailable. Your investigation and progress are retained.'));
const label=element('label','Your progress'),select=element('select',null,'form-select form-select-sm');label.append(select);for(const state of['Not started','Exploring','Done','Skipped']){const o=element('option',state);o.value=state;select.append(o);}select.value=tool.progress;select.setAttribute('aria-label',tool.name+' progress');select.addEventListener('change',()=>mutate('progress',{finding:f.id,capability:tool.id,progress:select.value}));card.append(label);content.append(card);
}
@ -39,26 +46,23 @@
const position=preference.positions?.[current.id]||0;requestAnimationFrame(()=>content.scrollTop=position);
}
async function load(){
const stamp=++epoch;request?.abort();request=new AbortController();
const priorId=current?.id;const stamp=++epoch;request?.abort();request=new AbortController();
try{const url=new URL(root.dataset.summaryUrl,location.origin);if(root.dataset.project)url.searchParams.set('projectId',root.dataset.project);if(root.dataset.book)url.searchParams.set('bookId',root.dataset.book);
const response=await fetch(url,{cache:'no-store',signal:request.signal});if(response.redirected||response.status===401){throw Error('Sign in again to resume your saved investigation.');}if(!response.ok)throw Error('Saved guidance could not be loaded. Retry when your connection returns.');const data=await response.json();if(stamp!==epoch)return;
current=data.active?data.summary:null;resultsUrl=data.resultsUrl;preference=read();render();paintPreference();
}catch(e){if(e.name==='AbortError'||stamp!==epoch)return;current=null;content.replaceChildren(element('p',e.message),btn('Retry',load),startLink());collapse(true,false);}
current=data.active?data.summary:null;resultsUrl=data.resultsUrl;preference=read();render();restorePanel(!hydrated||priorId!==current?.id);hydrated=true;
}catch(e){if(e.name==='AbortError'||stamp!==epoch)return;current=null;content.replaceChildren(element('p',e.message),btn('Retry',load),startLink());panel.hide();}
}
async function mutate(operation,extra={}){
if(busy||!current)return;busy=true;const selected=current.id;failure('Saving…');content.querySelectorAll('button,select').forEach(n=>n.disabled=true);
try{const data=new URLSearchParams({__RequestVerificationToken:token,bookId:current.bookID,id:current.id,version:current.version,operation,...extra});const response=await fetch(root.dataset.updateUrl,{method:'POST',body:data,cache:'no-store'});if(!response.ok){let body;try{body=await response.json();}catch{}throw Error(body?.message||'Your change was not confirmed. Retry or refresh your saved guidance.');}if(current?.id===selected){if(operation==='dismiss'||operation==='finish')collapse(true);await load();}}
try{const data=new URLSearchParams({__RequestVerificationToken:token,bookId:current.bookID,id:current.id,version:current.version,operation,...extra});const response=await fetch(root.dataset.updateUrl,{method:'POST',body:data,cache:'no-store'});if(!response.ok){let body;try{body=await response.json();}catch{}throw Error(body?.message||'Your change was not confirmed. Retry or refresh your saved guidance.');}if(current?.id===selected){if(operation==='dismiss'||operation==='finish')panel.hide();await load();await discover();}}
catch(e){render();failure(e.message);}finally{busy=false;}
}
tab.addEventListener('click',()=>collapse(false));root.querySelector('[data-guidance-collapse]').addEventListener('click',()=>{collapse(true);tab.focus();});
root.querySelector('[data-guidance-pin]').addEventListener('click',()=>{preference.pinned=preference.pinned===false;save();const wasCollapsed=root.dataset.collapsed;paintPreference();root.dataset.collapsed=wasCollapsed;});
let scrollFrame=0;content.addEventListener('scroll',()=>{if(scrollFrame||!current)return;scrollFrame=requestAnimationFrame(()=>{scrollFrame=0;if(!current||root.dataset.collapsed==='true')return;preference.positions||={};preference.positions[current.id]=content.scrollTop;const keys=Object.keys(preference.positions);if(keys.length>20)delete preference.positions[keys[0]];save();});});
splitter.addEventListener('keydown',e=>{if(e.key!=='ArrowLeft'&&e.key!=='ArrowRight')return;e.preventDefault();setWidth((preference.width||320)+(e.key==='ArrowRight'?10:-10));});
splitter.addEventListener('pointerdown',e=>{if(e.button!==0)return;drag=e.pointerId;splitter.setPointerCapture(e.pointerId);e.preventDefault();});splitter.addEventListener('pointermove',e=>{if(drag===e.pointerId)setWidth(e.clientX-layout.getBoundingClientRect().left);});for(const event of['pointerup','pointercancel','lostpointercapture'])splitter.addEventListener(event,()=>drag=null);
const observer=new ResizeObserver(measure);const header=document.querySelector('.pd-application-header');if(header)observer.observe(header);window.addEventListener('resize',measure);window.addEventListener('plotdirector:ribbon-layout-changed',measure);
// A narrow Help drawer becomes an in-flow row when explicitly opened; its stored pin/collapse remains independent.
const help=layout.querySelector('[data-help-expand]');help?.addEventListener('click',()=>layout.dataset.narrowHelp='true');help?.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' ')layout.dataset.narrowHelp='true';});
layout.querySelector('[data-help-collapse]')?.addEventListener('click',()=>delete layout.dataset.narrowHelp);document.addEventListener('plotline:help-more',()=>layout.dataset.narrowHelp='true');document.addEventListener('click',e=>{if(e.target.closest?.('[data-help-open]'))layout.dataset.narrowHelp='true';});
document.addEventListener('plotdirector:book-context-changed',e=>{root.dataset.book=String(e.detail.bookId);current=null;content.replaceChildren(element('p','Loading guidance for the selected book…'));collapse(true,false);load();});
window.addEventListener('pageshow',e=>{if(e.persisted)load();});measure();load();
let scrollFrame=0;content.addEventListener('scroll',()=>{if(scrollFrame||!current)return;scrollFrame=requestAnimationFrame(()=>{scrollFrame=0;if(!current||panel.state!=='open')return;preference.positions||={};preference.positions[current.id]=content.scrollTop;const keys=Object.keys(preference.positions);if(keys.length>20)delete preference.positions[keys[0]];save();});});
document.addEventListener('plotdirector:book-context-changed',e=>{root.dataset.book=String(e.detail.bookId);current=null;content.replaceChildren(element('p','Loading guidance for the selected book…'));panel.hide();load();});
async function saved(book){const url=new URL(root.dataset.savedUrl,location.origin);url.searchParams.set('bookId',book);const r=await fetch(url,{cache:'no-store'});if(!r.ok)throw Error('Saved investigations unavailable');return r.json();}
async function activate(id,version,book){if(busy)return;busy=true;try{const r=await fetch(root.dataset.updateUrl,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:new URLSearchParams({__RequestVerificationToken:token,id,bookId:book,version,operation:'activate'})});if(!r.ok)throw Error('This investigation could not be activated. Refresh and try again.');try{sessionStorage.setItem(pendingKey,id);}catch{}await load();await discover();}catch(e){failure(e.message);}finally{busy=false;}}
async function discover(){const area=document.querySelector('[data-my-investigations]');if(!area)return;const list=area.querySelector('[data-saved-investigations]');try{const rows=await saved(area.dataset.book);list.replaceChildren();if(!rows.length)list.append(element('p','No saved investigations for this book yet. Begin a concern above.'));for(const item of rows){const card=element('article');card.append(element('h3',item.concern),element('p',item.status+' · Last activity: '+new Date(item.updatedUtc).toLocaleString()+' · '+item.id.slice(0,8)));const form=element('form');form.method='post';form.action=item.continueUrl;form.dataset.guidanceActivate='';for(const[name,value]of Object.entries({__RequestVerificationToken:token,bookId:item.bookID,id:item.id,version:item.guidanceVersion,operation:'activate'})){const input=element('input');input.type='hidden';input.name=name;input.value=value;form.append(input);}form.append(element('button','Continue','btn btn-primary'));const results=element('a','Original results');results.href=item.resultsUrl;card.append(form,results);list.append(card);}}catch{list.replaceChildren(element('p','Your saved investigations could not be loaded.'),btn('Retry',discover));}}
document.addEventListener('submit',e=>{const form=e.target;if(!form.matches('[data-guidance-navigation],[data-guidance-activate]'))return;if(form.dataset.pending==='true'){e.preventDefault();return;}form.dataset.pending='true';form.setAttribute('aria-busy','true');const submit=e.submitter;if(submit?.name){const hidden=element('input');hidden.type='hidden';hidden.name=submit.name;hidden.value=submit.value;form.append(hidden);}const id=form.querySelector('[name=id]')?.value||new URL(form.action).searchParams.get('id');if(id)try{sessionStorage.setItem(pendingKey,id);}catch{}requestAnimationFrame(()=>{form.querySelectorAll('button').forEach(b=>{b.dataset.originalText=b.textContent;b.textContent='Opening…';b.disabled=true;});});});
window.addEventListener('pageshow',()=>document.querySelectorAll('[data-pending=true]').forEach(f=>{delete f.dataset.pending;f.removeAttribute('aria-busy');f.querySelectorAll('button').forEach(b=>{b.disabled=false;b.textContent=b.dataset.originalText||b.textContent;});}));discover();
window.addEventListener('pageshow',e=>{if(e.persisted)load();});load();
})();

View File

@ -412,52 +412,13 @@
collapsed: "plotline.helpDrawer.collapsed"
};
const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
const readBool = (key) => {
try {
return localStorage.getItem(key) === "true";
} catch {
return false;
}
};
const writeValue = (key, value) => {
try {
localStorage.setItem(key, value);
} catch {
// Help drawer preferences are conveniences; blocked storage should not break help.
}
};
const setWidth = (value) => {
const width = `${clamp(Number.parseFloat(value) || 25, 20, 50)}%`;
layout.style.setProperty("--help-drawer-width", width);
writeValue(storage.width, width);
};
const setPinned = (isPinned) => {
writeValue(storage.pinned, String(isPinned));
pinButton?.setAttribute("aria-pressed", String(isPinned));
if (pinButton) {
pinButton.textContent = isPinned ? "Unpin" : "Pin";
}
};
const setCollapsed = (isCollapsed) => {
layout.classList.toggle("help-collapsed", isCollapsed);
writeValue(storage.collapsed, String(isCollapsed));
if (collapseButton) {
collapseButton.textContent = isCollapsed ? "Expand" : "Collapse";
}
};
const readValue=key=>{try{return localStorage.getItem(key);}catch{return null;}};
const readBool=key=>readValue(key)==="true";
const writeValue=(key,value)=>{try{localStorage.setItem(key,value);}catch{}};
const panel=PlotDirectorContextPanels.create(drawer,{read:name=>readValue(storage[name]||"plotline.helpDrawer."+name),write:(name,value)=>writeValue(storage[name]||"plotline.helpDrawer."+name,value),changed:({state})=>{layout.classList.toggle("help-open",state!=="closed");layout.classList.toggle("help-collapsed",state==="collapsed");}});
const openDrawer = async (key, options = {}) => {
const contextKey = key || "";
layout.classList.add("help-open");
if (!options.keepCollapsed) {
setCollapsed(false);
}
panel.open({restore:!!options.keepCollapsed});
writeValue(storage.key, contextKey);
if (heading) {
heading.textContent = contextKey || "Help";
@ -480,10 +441,7 @@
}
};
const closeDrawer = () => {
layout.classList.remove("help-open", "help-collapsed");
setPinned(false);
};
const closeDrawer = () => panel.close();
window.PlotLineHelpDrawer = {
isActive() {
@ -494,9 +452,7 @@
}
};
setWidth(localStorage.getItem(storage.width) || "25%");
setPinned(readBool(storage.pinned));
setCollapsed(readBool(storage.collapsed));
document.addEventListener("plotline:help-more", (event) => {
const key = event.detail?.key || event.target?.dataset?.helpKey || "";
@ -515,42 +471,6 @@
openDrawer(opener.dataset.helpOpen || "");
});
closeButton?.addEventListener("click", closeDrawer);
collapseButton?.addEventListener("click", () => setCollapsed(!layout.classList.contains("help-collapsed")));
expandStrip?.addEventListener("click", () => setCollapsed(false));
expandStrip?.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
setCollapsed(false);
}
});
pinButton?.addEventListener("click", () => setPinned(!readBool(storage.pinned)));
splitter?.addEventListener("pointerdown", (event) => {
if (!layout.classList.contains("help-open") || layout.classList.contains("help-collapsed")) {
return;
}
event.preventDefault();
document.body.classList.add("help-resizing");
splitter.setPointerCapture?.(event.pointerId);
const onMove = (moveEvent) => {
const rect = layout.getBoundingClientRect();
const widthPercent = ((rect.right - moveEvent.clientX) / rect.width) * 100;
setWidth(widthPercent);
};
const onUp = () => {
document.body.classList.remove("help-resizing");
document.removeEventListener("pointermove", onMove);
document.removeEventListener("pointerup", onUp);
};
document.addEventListener("pointermove", onMove);
document.addEventListener("pointerup", onUp);
});
const pinnedKey = (() => {
try {
return localStorage.getItem(storage.key) || "";