38 lines
10 KiB
JavaScript
38 lines
10 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,pendingDeleted=false,deleteDialogOpen=false;
|
|
function release(){busy=false;if(pendingDeleted){pendingDeleted=false;void load(journey.dataset.openingUrl);}}
|
|
const deletedIds=new Set();
|
|
function tab(name){const deletionKey='plotdirector.investigation.deleted.'+workspace.closest('[data-layout-owner]').dataset.layoutOwner;
|
|
async function removed(id){
|
|
deletedIds.add(id);
|
|
window.dispatchEvent(new CustomEvent("plotdirector:investigation-deleted",{detail:{id,book:root.dataset.book}}));
|
|
try{const key='writer.explore.active.'+root.dataset.book;if(sessionStorage.getItem(key)===id)sessionStorage.removeItem(key);const pending='plotdirector.guidance.open.'+workspace.closest('[data-layout-owner]').dataset.layoutOwner;if(sessionStorage.getItem(pending)===id)sessionStorage.removeItem(pending);}catch{}
|
|
if(window.PlotDirectorGuidanceSummary?.summary?.id===id){window.PlotDirectorGuidanceSummary={active:false};window.dispatchEvent(new CustomEvent('plotdirector:guidance-summary',{detail:{active:false}}));}
|
|
window.dispatchEvent(new Event('investigation-guidance-updated'));
|
|
if(current===id){dirty=false;if(busy){pendingDeleted=true;return;}await load(journey.dataset.openingUrl);}else await history();
|
|
}
|
|
root.addEventListener('click',async event=>{
|
|
const button=event.target.closest('[data-investigation-delete]');if(!button)return;event.preventDefault();if(busy||deleteDialogOpen)return;deleteDialogOpen=true;
|
|
const listOpen=root.querySelector('[data-explore-tab="saved"]').getAttribute('aria-selected')==='true',listScroll=saved.scrollTop;
|
|
const id=button.dataset.investigationDelete,title=button.dataset.investigationTitle||'Current investigation';
|
|
const result=await window.PlotDirectorDialogs.choose({title:'Delete this investigation?',message:title+'\n\nThis will permanently delete the investigation, its answers and its investigation history. This cannot be undone. Changes you have already made to your story will not be affected.',actions:[{value:'cancel',label:'Cancel'},{value:'delete',label:'Delete investigation',className:'btn-danger',run:async()=>{
|
|
if(busy)throw Error('Wait for the current investigation request to finish, then retry.');busy=true;
|
|
try{const body=new URLSearchParams({id,bookId:root.dataset.book,projectId:root.dataset.project,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});const response=await fetch(root.dataset.deleteUrl,{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(30000)}).catch(()=>{throw Error('Deletion was not confirmed. Check your connection, then refresh or retry.');});if(response.redirected||response.status===401)throw Error('Sign in again before deleting this investigation. No deletion was confirmed.');if(!response.ok)throw Error('Deletion could not be confirmed. The investigation remains listed. Retry or refresh before continuing.');const data=await response.json().catch(()=>null);if(data?.deleted!==true||data.id!==id)throw Error('Deletion was not confirmed. Refresh before retrying.');return true;}finally{release();}
|
|
}}]}).finally(()=>deleteDialogOpen=false);
|
|
if(result?.value!=='delete')return;
|
|
try{localStorage.setItem(deletionKey,JSON.stringify({id,book:root.dataset.book,at:Date.now()}));}catch{}
|
|
await removed(id);if(listOpen){tab('saved');saved.scrollTop=listScroll;root.querySelector('[data-explore-tab="saved"]')?.focus({preventScroll:true});}else journey.querySelector('[name=concern]')?.focus({preventScroll:true});
|
|
});
|
|
window.addEventListener('storage',event=>{if(event.key!==deletionKey||!event.newValue)return;try{const data=JSON.parse(event.newValue);if(String(data.book)===root.dataset.book)void removed(data.id);}catch{}});
|
|
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;const menu=document.createElement('details'),toggle=document.createElement('summary'),remove=document.createElement('button');menu.className='writer-investigation-actions';toggle.textContent='⋯';toggle.setAttribute('aria-label','Actions for '+row.concern);remove.type='button';remove.className='btn btn-link btn-sm text-danger';remove.dataset.investigationDelete=row.id;remove.dataset.investigationTitle=row.concern+' · '+new Date(row.updatedUtc).toLocaleString();const trash=document.querySelector('[data-pwa-icon-catalog]').content.querySelector('[data-icon-key=remove]').cloneNode(true);trash.removeAttribute('data-icon-key');remove.append(trash,document.createTextNode(' Delete investigation'));menu.append(toggle,remove);card.append(h,p,a,menu);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.status===404&¤t&&(options.body?.get?.('id')||new URL(url,location.origin).searchParams.get('id'))===current){journey.replaceChildren();await removed(current);}if(!response.ok)throw Error(response.status===404?'This investigation was deleted or is no longer available. Return to Explore or choose another saved investigation.':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.');if(inline?.dataset.inlineInvestigation&&deletedIds.has(inline.dataset.inlineInvestigation)){pendingDeleted=true;journey.replaceChildren();dirty=false;return;}journey.replaceChildren(...(inline?[inline]:doc.body.childNodes));current=inline?.dataset.inlineInvestigation||null;workspace.classList.toggle('writer21-investigating',!!current);workspace.dispatchEvent(new CustomEvent('writer-explore:state',{detail:{active:!!current}}));dirty=false;tab('new');message.textContent='';const address=new URL(location.href);if(current)address.searchParams.set('investigation',current);else address.searchParams.delete('investigation');if(address.hash==='#new-investigation')address.hash='';window.history.replaceState(window.history.state,'',address);try{if(current)sessionStorage.setItem('writer.explore.active.'+root.dataset.book,current);else sessionStorage.removeItem('writer.explore.active.'+root.dataset.book);}catch{}await history();}catch(error){message.textContent=error.message;}finally{root.removeAttribute('aria-busy');release();}}
|
|
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;const activation=new FormData(form);if(event.submitter?.name)activation.set(event.submitter.name,event.submitter.value);fetch(form.action,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:activation}).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(release);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);const landing=a.matches('[data-explore-landing]');if(url.origin!==location.origin||!landing&&!url.pathname.startsWith('/Writer/Explore/Investigate'))return;event.preventDefault();if(dirty&&!confirm('Leave your unsaved answer and load this investigation?'))return;void load(landing?journey.dataset.openingUrl:url);});
|
|
window.addEventListener('beforeunload',event=>{if(dirty||busy){event.preventDefault();event.returnValue='';}});
|
|
window.addEventListener('hashchange',()=>{if(location.hash==='#new-investigation'&&(!dirty||confirm('Leave your unsaved answer and start another investigation?')))void load(journey.dataset.openingUrl);});let id=new URLSearchParams(location.search).get('investigation');if(location.hash==='#new-investigation')id=null;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);
|
|
})();
|