PlotDirector/PlotLine/wwwroot/js/writer-explore.js

14 lines
5.4 KiB
JavaScript

// Uses the established versioned investigation engine; only the presentation is replaced.
(()=>{const root=document.querySelector('[data-explore-investigation]');if(!root)return;
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');}}
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);
})();