diff --git a/PlotLine.Tests/Browser/explore-divider.cjs b/PlotLine.Tests/Browser/explore-divider.cjs new file mode 100644 index 00000000..f98ab20c --- /dev/null +++ b/PlotLine.Tests/Browser/explore-divider.cjs @@ -0,0 +1,130 @@ +// Real compiled Explore/Journey Razor and investigation engine; isolated memory repositories. +// Run with --installed under xvfb-run for a real installed Chromium PWA. +const {chromium} = require('playwright'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const base='http://127.0.0.1:5238', url=base+'/Writer/Explore?projectId=7&bookId=12'; +(async()=>{ + const installed=process.argv.includes('--installed'), mode=installed?'installed-pwa':'browser'; + const profile=installed?fs.mkdtempSync('/tmp/pd-explore-pwa-'):null; + const context=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1666,height:1050}}):await(await chromium.launch()).newContext({viewport:{width:1666,height:1050}}); + const browser=context.browser(), evidence='/tmp/pd-explore-divider-evidence/'+mode; + fs.mkdirSync(evidence,{recursive:true}); + await context.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()}))); + await context.route('**/native-companion/status*',r=>r.fulfill({json:{leases:[]}})); + await context.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'))})); + try{ + let page; + if(installed){ + const tab=context.pages()[0];await tab.goto(base+'/fixture'); + const cdp=await browser.newBrowserCDPSession(),manifestId=base+'/Projects'; + await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture'}); + await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'}); + const opened=context.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:base+'/fixture'}); + page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches)); + }else page=await context.newPage(); + page.setDefaultTimeout(15000); + const errors=[];page.on('pageerror',e=>errors.push(e.message)); + let navigations=0;page.on('request',r=>{if(r.isNavigationRequest()&&r.frame()===page.mainFrame())navigations++;}); + const layout=page.locator('[data-explore-layout]'), divider=page.locator('[data-explore-divider]'), journey=page.locator('[data-explore-journey]'); + const ratio=()=>layout.evaluate(n=>Number(n.style.getPropertyValue('--explore-ratio'))); + const close=(a,b)=>assert(Math.abs(a-b)<.005,`${a} != ${b}`); + const idle=()=>page.waitForFunction(()=>!document.querySelector('[data-explore-layout]').hasAttribute('data-resize-animating')); + const ready=()=>journey.getByRole('button',{name:'Begin',exact:true}).waitFor(); + const begin=async()=>{await journey.locator('[name=concern]').first().check();await journey.getByRole('button',{name:'Begin',exact:true}).click();await journey.locator('[data-inline-investigation]').waitFor();}; + await page.goto(url);await ready();close(await ratio(),.5); + const nodes=await layout.evaluateHandle(n=>[n,n.querySelector('#explore-discovery'),n.querySelector('#explore-concern')]); + await page.screenshot({path:evidence+'/initial.png'}); + await journey.locator('[name=concern]').first().check(); + await journey.getByRole('button',{name:'Begin',exact:true}).scrollIntoViewIfNeeded(); + await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))); + await page.evaluate(()=>{ + const w=document.querySelector('[data-explore-layout]');window.exploreFrames=[];window.exploreTransitions=0;window.exploreWrites=0; + const set=Storage.prototype.setItem;Storage.prototype.setItem=function(k,v){if(k.startsWith('plotdirector.writerExploreLayout.'))window.exploreWrites++;return set.call(this,k,v);}; + new MutationObserver(records=>{for(const r of records)if(r.attributeName==='data-resize-animating'&&w.hasAttribute('data-resize-animating'))window.exploreTransitions++;}).observe(w,{attributes:true,attributeFilter:['data-resize-animating']}); + window.exploreSampling=true; + function frame(t){ + const r=document.querySelector('[data-ribbon-shell]').getBoundingClientRect(); + const tabs=[...document.querySelectorAll('[data-guidance-expand],[data-help-expand]')].map(n=>{const b=n.getBoundingClientRect();return[b.x,b.y];}); + window.exploreFrames.push({t,animating:w.hasAttribute('data-resize-animating'),ratio:Number(w.style.getPropertyValue('--explore-ratio')),ribbon:[r.x,r.y,r.width,r.height],tabs}); + if(window.exploreSampling)requestAnimationFrame(frame); + }requestAnimationFrame(frame); + }); + const beforeNavigation=navigations; + await begin(); + await page.waitForFunction(()=>document.querySelector('[data-explore-layout]').hasAttribute('data-resize-animating')); + const screenshotSession=await context.newCDPSession(page); + const capture=screenshotSession.send('Page.captureScreenshot',{format:'png',captureBeyondViewport:false}).then(result=>fs.writeFileSync(evidence+'/intermediate.png',Buffer.from(result.data,'base64'))); + // A real next-question response during the glide must neither restart it nor replace the outer panels. + const form=journey.locator('[data-investigation-answer]'); + assert.equal(await form.count(),1); + await form.locator('[name=option]').first().evaluate(n=>{n.checked=true;n.dispatchEvent(new Event('input',{bubbles:true}));}); + await form.locator('button[value=answer]').evaluate(n=>n.form.requestSubmit(n)); + await page.waitForFunction(()=>!document.querySelector('[data-explore-investigation]').hasAttribute('aria-busy')); + await idle();await capture;close(await ratio(),.25); + await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))); + await page.evaluate(()=>window.exploreSampling=false); + const frames=await page.evaluate(()=>window.exploreFrames); + fs.writeFileSync(evidence+'/animation-frames.json',JSON.stringify(frames,null,2)); + assert(frames.filter(f=>f.ratio>.26&&f.ratio<.49).length>=4,'Continuous intermediate positions'); + const moving=frames.filter(f=>f.animating),firstSettled=frames.find(f=>f.t>moving.at(-1).t&&!f.animating); + assert(moving.length>=4&&firstSettled,'Animation start and finish captured'); + const duration=firstSettled.t-moving[0].t;assert(duration>=375&&duration<=650,`Observed ease-out duration ${duration} ms`); + for(const f of frames){assert.deepEqual(f.ribbon,frames[0].ribbon,'Ribbon stationary');assert.deepEqual(f.tabs,frames[0].tabs,'Side tabs stationary');} + assert.equal(await page.evaluate(()=>window.exploreTransitions),1,'Only discovery-to-active starts animation'); + assert.equal(await page.evaluate(()=>window.exploreWrites),0,'Automatic defaults are not persisted as manual choices'); + assert.equal(navigations,beforeNavigation,'AJAX investigation does not reload the document'); + assert(await nodes.evaluate(ns=>ns.every(n=>n.isConnected)),'Workspace and outer panels stay mounted'); + await page.screenshot({path:evidence+'/active.png'}); + const id=new URL(page.url()).searchParams.get('investigation');assert(id); + const answerLinks=journey.locator('aside a');assert(await answerLinks.count()>0,'Your answers is retained'); + await answerLinks.first().click();await form.waitFor();await idle();close(await ratio(),.25); + const explanation=journey.locator('textarea'); + if(await explanation.count())await explanation.fill('Draft explanation retained while resizing'); + const dragTo=async target=>{ + const b=await divider.boundingBox(),w=await layout.boundingBox(); + await page.mouse.move(b.x+b.width/2,b.y+100);await page.mouse.down(); + await page.mouse.move(w.x+(w.width-b.width)*target+b.width/2,b.y+100,{steps:12}); + await page.mouse.up(); + }; + await dragTo(.42);close(await ratio(),.42); + assert.equal(await page.evaluate(()=>window.exploreWrites),1,'Drag persists once at completion'); + assert.equal(await layout.evaluate(n=>n.classList.contains('writer3-dragging')),false); + if(await explanation.count())assert.equal(await explanation.inputValue(),'Draft explanation retained while resizing'); + await divider.focus();const old=await ratio();await divider.press('ArrowRight');assert(await ratio()>old); + await divider.press('Home');assert((await page.locator('#explore-discovery').boundingBox()).width>=259);assert(await page.locator('#explore-discovery').evaluate(n=>n.scrollWidth<=n.clientWidth+2)); + await divider.press('End');assert((await page.locator('#explore-concern').boundingBox()).width>=359);assert(await page.locator('#explore-concern').evaluate(n=>n.scrollWidth<=n.clientWidth+2)); + await dragTo(.4);const preferred=await ratio(); + await journey.locator('button[value=save]').first().click(); + await page.waitForFunction(()=>!document.querySelector('[data-explore-investigation]').hasAttribute('aria-busy')); + close(await ratio(),preferred); + await page.getByRole('tab',{name:'Saved investigations',exact:true}).click(); + await page.locator(`[data-explore-saved] a[href*="${id}"]`).click();await journey.locator('[data-inline-investigation]').waitFor();await page.waitForFunction(()=>!document.querySelector('[data-explore-investigation]').hasAttribute('aria-busy')); + close(await ratio(),preferred); + await page.reload();await journey.locator('[data-inline-investigation]').waitFor();close(await ratio(),preferred); + 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); + // Pointer cancellation and lost capture leave no stuck drag or selection suppression. + let b=await divider.boundingBox();await page.mouse.move(b.x+b.width/2,b.y+60);await page.mouse.down(); + await divider.evaluate(n=>n.dispatchEvent(new PointerEvent('pointercancel',{pointerId:1})));await page.mouse.up(); + assert.equal(await layout.evaluate(n=>n.classList.contains('writer3-dragging')),false); + for(const theme of ['modern-light','modern-dark'])for(const width of [1666,1280,1024,800,600,390]){ + await page.setViewportSize({width,height:1050});await page.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme); + await page.waitForFunction(()=>document.querySelector('[data-explore-layout]').dataset.narrow===String(document.querySelector('[data-explore-layout]').clientWidth<=800||innerWidth<=800)); + if(width<=800)assert.equal(await divider.isVisible(),false); + assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),`${theme}/${width} page overflow`); + for(const selector of ['#explore-discovery','#explore-concern'])assert(await page.locator(selector).evaluate(n=>n.scrollWidth<=n.clientWidth+2),`${theme}/${width} panel overflow`); + if(width===1280||width===600)await page.screenshot({path:`${evidence}/${theme}-${width}.png`}); + if(width===600){await page.locator('#explore-concern').scrollIntoViewIfNeeded();await page.screenshot({path:`${evidence}/${theme}-questionnaire-600.png`});} + } + await page.setViewportSize({width:1666,height:1050}); + await page.emulateMedia({reducedMotion:'reduce'}); + await 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.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.`); + }finally{await context.close();await browser.close();if(profile)fs.rmSync(profile,{recursive:true,force:true});} +})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/InvestigationGuidanceTests.cs b/PlotLine.Tests/InvestigationGuidanceTests.cs index 25188549..215fa6ec 100644 --- a/PlotLine.Tests/InvestigationGuidanceTests.cs +++ b/PlotLine.Tests/InvestigationGuidanceTests.cs @@ -43,6 +43,15 @@ internal sealed class GuidanceMemoryRepository(IInvestigationRepository investig rows.TryGetValue(id.Value,out var state);var events=await investigations.Replay(user,i.BookID,id.Value);using var ev=JsonDocument.Parse(events.Last()); return new(){ID=i.ID,ProjectID=i.ProjectID,BookID=i.BookID,BookTitle="Fixture book",InvestigationJson=JsonSerializer.Serialize(i,CatalogueValidator.Json),EvaluationJson=ev.RootElement.GetProperty("evaluation").GetRawText(),GuidanceJson=state.Json,GuidanceVersion=state.Version,IsActive=state.Active,Finished=state.Finished}; } + // Saved-summary projection for browser save/resume qualification; mirrors the existing repository contract. + public async Task> List(int user,int book) + { + var list=await investigations.List(user,book); + return list.Select(i=>{ + rows.TryGetValue(i.ID,out var state); + return new SavedInvestigation(i.ID,i.BookID,i.CatalogueVersion,i.Concern,i.CurrentQuestion==null?"Results available":"In progress",i.UpdatedUtc,state.Version,state.Active,state.Finished); + }).ToArray(); + } public async Task Save(int user,int book,Guid id,int version,string operation,string json) { var i=await investigations.Read(user,book,id)??throw new UnauthorizedAccessException();rows.TryGetValue(id,out var old);if(old.Version!=version)throw new ArgumentException("Stale guidance"); diff --git a/PlotLine/Views/Writer/Destination.cshtml b/PlotLine/Views/Writer/Destination.cshtml index 7c31cf02..181432af 100644 --- a/PlotLine/Views/Writer/Destination.cshtml +++ b/PlotLine/Views/Writer/Destination.cshtml @@ -28,7 +28,7 @@ @if(Model.Destination=="Plan"){} - @if(Model.Destination=="Explore"){} + @if(Model.Destination=="Explore"){} @if(Model.Destination=="Review"){} @if(Model.Destination is "Write" or "Plan"){ diff --git a/PlotLine/Views/Writer/_WriterExplore.cshtml b/PlotLine/Views/Writer/_WriterExplore.cshtml index 5959e948..4fe87b09 100644 --- a/PlotLine/Views/Writer/_WriterExplore.cshtml +++ b/PlotLine/Views/Writer/_WriterExplore.cshtml @@ -1,7 +1,7 @@ @inject PlotLine.Services.Investigations.InvestigationAccess InvestigationAccess @model WriterDashboardViewModel -
-
+
+

Discover what could help your story

Find a practical next step, or try a different way of looking at your work.

@if(Model.ProjectID.HasValue){
@@ -14,7 +14,8 @@

}else{

Choose a project to discover tools for its characters, settings and story.

Choose or create a project}
-

Explore a concern

You do not need to know the answer yet. Start with what is troubling you.

+ +

Explore a concern

You do not need to know the answer yet. Start with what is troubling you.

@if(InvestigationAccess.Enabled&&Model.BookID.HasValue){
diff --git a/PlotLine/wwwroot/css/writer21.css b/PlotLine/wwwroot/css/writer21.css index a6478627..baaa32e0 100644 --- a/PlotLine/wwwroot/css/writer21.css +++ b/PlotLine/wwwroot/css/writer21.css @@ -5,8 +5,20 @@ .writer21-tabs button[aria-selected=true]{border-bottom-color:var(--bs-primary);font-weight:700} .writer21-bounded{max-height:32rem;overflow-y:auto;overscroll-behavior:contain;padding:.3rem} .writer21-bounded article{padding:.75rem 0;border-bottom:1px solid var(--bs-border-color)} -.writer3-workspace:has([data-explore-investigation]){grid-template-columns:minmax(0,1fr) minmax(0,1fr)} -.writer3-workspace.writer21-investigating{grid-template-columns:minmax(0,1fr) minmax(0,3fr)} +[data-explore-layout]{--explore-divider-size:18px;grid-template-columns:minmax(0,calc((100% - var(--explore-divider-size)) * var(--explore-ratio,.5))) var(--explore-divider-size) minmax(0,1fr);gap:0;overflow-anchor:none} +[data-explore-layout]>.writer3-panel{overflow-wrap:anywhere} +#explore-concern{container-type:inline-size} +[data-explore-layout] fieldset{min-width:0} +[data-explore-layout] .investigation-choice input{flex-shrink:0} +@container(max-width:700px){[data-explore-layout] .investigation-journey{grid-template-columns:minmax(0,1fr)}} +[data-explore-layout] :is(input,select,textarea){max-width:100%;min-width:0} +.writer3-destination .writer-explore-divider{position:relative;top:auto;height:auto;align-self:stretch} +.writer-explore-divider::before{content:"";position:absolute;inset:8px auto 8px calc(50% - .5px);width:1px;background:var(--pd-border-subtle)} +.writer-explore-divider::after{left:calc(50% - 2px);top:clamp(32px,20vh,240px)} +[data-explore-layout][data-narrow=true]{grid-template-columns:minmax(0,1fr);gap:1rem} +[data-explore-layout][data-narrow=true]>.writer-explore-divider{display:none} +@media(pointer:coarse){[data-explore-layout]{--explore-divider-size:44px}} + .investigation-journey{display:grid;grid-template-columns:minmax(0,2fr) minmax(12rem,1fr);gap:1rem} .investigation-journey>.writer3-panel{padding:.7rem;min-width:0} .writer21-board{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:1rem} @@ -15,4 +27,4 @@ .writer21-task form{display:inline-block;margin:.2rem} .writer21-task p{white-space:pre-wrap} @media(max-width:1150px){.investigation-journey{grid-template-columns:1fr}.writer21-board{grid-template-columns:repeat(2,minmax(0,1fr))}} -@media(max-width:800px){.writer3-workspace:has([data-explore-investigation]),.writer3-workspace.writer21-investigating{grid-template-columns:minmax(0,1fr)}.writer21-board{grid-template-columns:1fr}} +@media(max-width:800px){[data-explore-layout]{grid-template-columns:minmax(0,1fr);gap:1rem}[data-explore-divider]{display:none}.writer21-board{grid-template-columns:1fr}} diff --git a/PlotLine/wwwroot/js/writer-explore-layout.js b/PlotLine/wwwroot/js/writer-explore-layout.js new file mode 100644 index 00000000..fb59cb22 --- /dev/null +++ b/PlotLine/wwwroot/js/writer-explore-layout.js @@ -0,0 +1,116 @@ +// Explore-only device presentation preference; never stores investigation content or working focus. +(() => { + const workspace = document.querySelector('[data-explore-layout]'); + const divider = workspace?.querySelector('[data-explore-divider]'); + if (!divider) return; + 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; + 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; + } catch { /* Storage may be blocked or contain an old preference. */ } + function bounds() { + const size = parseFloat(getComputedStyle(workspace).getPropertyValue('--explore-divider-size')); + const width = Math.max(1, workspace.clientWidth - size); + return { width, min: Math.max(.15, Math.min(.5, 260 / width)), max: Math.min(.8, Math.max(.5, 1 - 360 / width)) }; + } + function paint(value) { + const b = bounds(); + ratio = Math.max(b.min, Math.min(b.max, value)); + workspace.style.setProperty('--explore-ratio', ratio); + divider.setAttribute('aria-valuemin', String(Math.round(b.min * 100))); + divider.setAttribute('aria-valuemax', String(Math.round(b.max * 100))); + divider.setAttribute('aria-valuenow', String(Math.round(ratio * 100))); + divider.setAttribute('aria-valuetext', `${Math.round(ratio * 100)} percent discovery, ${Math.round((1 - ratio) * 100)} percent investigation`); + } + function stop() { + cancelAnimationFrame(animation); animation = 0; + workspace.removeAttribute('data-resize-animating'); + } + function move(value, animate = false) { + stop(); target = value; + if (!animate || motion.matches || workspace.dataset.narrow === 'true') { paint(value); return; } + const from = ratio, started = performance.now(); + workspace.dataset.resizeAnimating = 'true'; + function tick(now) { + const elapsed = Math.min(1, (now - started) / 450); + paint(from + (value - from) * (1 - Math.pow(1 - elapsed, 3))); + if (elapsed < 1) animation = requestAnimationFrame(tick); + else { animation = 0; workspace.removeAttribute('data-resize-animating'); } + } + animation = requestAnimationFrame(tick); + } + function save() { + manual = ratio; target = ratio; + try { localStorage.setItem(key, JSON.stringify({ version: 1, leftRatio: manual })); } catch { } + } + function applyPointer() { + pointerFrame = 0; + if (!drag || pointerX === null) return; + const b = bounds(); + // Center the handle on the pointer, so picking it up never jumps a column. + paint((pointerX - workspace.getBoundingClientRect().left - drag.offset) / b.width); + pointerX = null; drag.moved = true; + } + function endDrag(event) { + if (!drag || (event?.pointerId != null && event.pointerId !== drag.id)) return; + cancelAnimationFrame(pointerFrame); applyPointer(); + const finished = drag; drag = null; pointerX = null; + workspace.classList.remove('writer3-dragging'); + if (divider.hasPointerCapture(finished.id)) divider.releasePointerCapture(finished.id); + if (finished.moved) save(); + } + divider.addEventListener('pointerdown', event => { + if (!event.isPrimary || event.button !== 0 || workspace.dataset.narrow === 'true') return; + event.preventDefault(); stop(); divider.focus(); + drag = { id: event.pointerId, offset: event.clientX - workspace.getBoundingClientRect().left - ratio * bounds().width, moved: false }; + divider.setPointerCapture(event.pointerId); workspace.classList.add('writer3-dragging'); + }); + divider.addEventListener('pointermove', event => { + if (event.pointerId !== drag?.id) return; + pointerX = event.clientX; + if (!pointerFrame) pointerFrame = requestAnimationFrame(applyPointer); + }); + for (const type of ['pointerup', 'pointercancel', 'lostpointercapture']) divider.addEventListener(type, endDrag); + window.addEventListener('blur', () => endDrag()); + window.addEventListener('pagehide', () => { endDrag(); stop(); }); + divider.addEventListener('keydown', event => { + if (event.altKey || event.ctrlKey || event.metaKey) return; + const b = bounds(), step = (event.shiftKey ? 50 : 10) / b.width; + let value; + if (event.key === 'ArrowLeft') value = ratio - step; + else if (event.key === 'ArrowRight') value = ratio + step; + else if (event.key === 'Home') value = b.min; + else if (event.key === 'End') value = b.max; + else return; + event.preventDefault(); stop(); paint(value); save(); + }); + workspace.addEventListener('writer-explore:state', event => { + const next = event.detail.active; + if (next === active && !event.detail.initial) return; + active = next; + if (manual === null && !drag) move(active ? .25 : .5, !event.detail.initial); + }); + function measure() { + const narrow = workspace.clientWidth <= 800 || innerWidth <= 800; + if (workspace.dataset.narrow !== String(narrow)) { + endDrag(); + if (narrow && document.activeElement === divider) workspace.querySelector('#explore-concern')?.focus({preventScroll:true}); + 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); + } + let measuredWidth = 0; + new ResizeObserver(() => { + if (workspace.clientWidth === measuredWidth) return; + measuredWidth = workspace.clientWidth; + endDrag(); stop(); measure(); + }).observe(workspace); + window.addEventListener('resize', () => { endDrag(); stop(); measure(); }); + window.addEventListener('pageshow', () => { if (!animation) measure(); }); + motion.addEventListener('change', () => { if (motion.matches && animation) { stop(); paint(target); } }); + target = manual ?? .5; measure(); +})(); diff --git a/PlotLine/wwwroot/js/writer-explore.js b/PlotLine/wwwroot/js/writer-explore.js index bb26c0ea..9b73333e 100644 --- a/PlotLine/wwwroot/js/writer-explore.js +++ b/PlotLine/wwwroot/js/writer-explore.js @@ -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);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');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);}); 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{}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;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); })();