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

59 lines
10 KiB
JavaScript

// Canonical authoring support only. Never changes Word position, session target or a reference selection.
(() => {
const root=document.querySelector('[data-writer-authoring]');if(!root)return;
const main=root.closest('.writer3-main');
main.addEventListener('plotdirector:work-state',e=>{const block=e.target.closest('.writer3-session-block');if(!block)return;if(e.detail.session){if(block.nextElementSibling!==root)root.before(block);}else if(block.previousElementSibling!==root)root.after(block);});
let allowLeave=false;const dirty=()=>[...root.querySelectorAll('[data-authoring-form]')].some(f=>f.dataset.dirty==='true'||f.dataset.busy==='true');
const cardOf=n=>n.closest('[data-authoring-card]');
const focusEditor=card=>card.querySelector('textarea,select,input:not([type=hidden])')?.focus();
function bind(container){
window.PlotLineHelpIcons?.init(container);
for(const form of container.querySelectorAll('[data-authoring-form]')){
if(form.dataset.bound)continue;form.dataset.bound='true';
const markDirty=()=>{form.dataset.dirty='true';cardOf(form).querySelector('[data-authoring-status]').textContent='';};form.addEventListener('input',markDirty);form.addEventListener('change',markDirty);
const card=cardOf(form),edit=card.querySelector('[data-authoring-edit]'),display=card.querySelector('[data-authoring-display]'),error=form.querySelector('[data-authoring-error]');
edit.addEventListener('click',()=>{card.querySelector('[data-authoring-status]').textContent='';form.hidden=false;display.hidden=true;edit.hidden=true;edit.setAttribute('aria-expanded','true');focusEditor(card);});
form.querySelector('[data-authoring-cancel]').addEventListener('click',()=>{if(form.dataset.busy==='true')return;form.reset();card.querySelector('[data-authoring-status]').textContent='';form.dataset.dirty='false';form.hidden=true;display.hidden=false;edit.hidden=false;edit.setAttribute('aria-expanded','false');error.hidden=true;edit.focus();});
form.querySelector('[data-authoring-reload]').addEventListener('click',async()=>{if(!confirm('Reload the recorded version? Copy any text you want to keep first.'))return;try{const doc=await read();replaceCard(card,doc);}catch{error.textContent='Could not reload. Your text is still here.';}});
card.querySelector('[data-checklist-toggle]')?.addEventListener('change',async event=>{
const box=event.target;if(form.dataset.busy==='true'){box.checked=!box.checked;return;}const prior=!box.checked;box.disabled=true;edit.disabled=true;form.dataset.busy='true';
const data=new FormData(form);for(const input of form.querySelectorAll('input[type=checkbox]'))data.set(input.name,String(input.name==='IsCompleted'?box.checked:input.checked));
try{const response=await fetch(form.action,{method:'POST',body:data});if(!response.ok)throw Error();const doc=await read();replaceCard(card,doc);}
catch{box.checked=prior;card.querySelector('[data-authoring-status]').textContent='Completion could not be refreshed. Reload the recorded version before retrying.';box.disabled=true;form.querySelector('[data-authoring-reload]').hidden=false;}
finally{form.dataset.busy='false';edit.disabled=false;}
});
form.addEventListener('submit',async e=>{
e.preventDefault();if(form.dataset.busy==='true')return;form.dataset.busy='true';const save=form.querySelector('[data-authoring-save]'),cancel=form.querySelector('[data-authoring-cancel]'),reload=form.querySelector('[data-authoring-reload]');let committed=false;save.disabled=true;cancel.disabled=true;reload.disabled=true;error.hidden=true;
const data=new FormData(form);for(const input of form.querySelectorAll('input[type=checkbox]'))data.set(input.name,String(input.checked));
try{const response=await fetch(form.action,{method:'POST',body:data,headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok){const body=await response.json().catch(()=>null);error.textContent=body?.message||'Could not save. Your text is still here.';error.hidden=false;if(response.status===409)form.querySelector('[data-authoring-reload]').hidden=false;return;}
// A committed save is not retried if the following read fails (especially for newly created rows).
const result=await response.json().catch(()=>null);if(result?.success!==true)throw Error('Save was not confirmed');
committed=true;form.dataset.dirty='false';const doc=await read();const isAdd=card.dataset.kind.startsWith('Add');replaceCard(card,doc);
const preview=root.querySelector('.writer3-reminder-preview'),freshPreview=doc.querySelector('.writer3-reminder-preview');if(preview&&freshPreview)preview.replaceWith(freshPreview.cloneNode(true));
const next=root.querySelector('[data-authoring-next-area]'),freshNext=doc.querySelector('[data-authoring-next-area]');if(next&&freshNext){const clone=freshNext.cloneNode(true);next.replaceWith(clone);bind(clone);}
const refs=document.querySelector('[data-authoring-references]'),template=doc.querySelector('[data-authoring-companion]');if(refs&&template)refs.replaceChildren(template.content.cloneNode(true));
if(isAdd){for(const fresh of doc.querySelectorAll('[data-authoring-card]'))if(!root.querySelector(`[data-key="${CSS.escape(fresh.dataset.key)}"]`)){const clone=fresh.cloneNode(true);root.querySelector('[data-authoring-new-records]')?.append(clone);bind(clone.parentElement);}}
}catch{error.textContent=committed?'Saved, but the refreshed record could not load. Your text is retained. Reload the recorded version.':'Save was not confirmed. Your text is retained. Reload the recorded version to check before trying again.';error.hidden=false;form.querySelector('[data-authoring-reload]').hidden=false;}
finally{form.dataset.busy='false';save.disabled=committed&&form.isConnected;cancel.disabled=committed&&form.isConnected;reload.disabled=false;}
});
}
for(const details of container.querySelectorAll('details'))if(!details.dataset.authoringBound){details.dataset.authoringBound='true';details.addEventListener('toggle',()=>{if(!details.open&&[...details.querySelectorAll('[data-authoring-form]')].some(f=>f.dataset.dirty==='true')){details.open=true;const pending=details.querySelector('[data-authoring-form][data-dirty="true"]');if(pending)cardOf(pending).querySelector('[data-authoring-status]').textContent='Save or Cancel this editor before closing the section.';}});}
for(const button of container.querySelectorAll('[data-authoring-next]'))button.addEventListener('click',()=>root.querySelector(`[data-key="${CSS.escape(button.dataset.authoringNext)}"] [data-authoring-edit]`)?.click());
}
function replaceCard(card,doc){if(!card.isConnected)return;const fresh=doc.querySelector(`[data-key="${CSS.escape(card.dataset.key)}"]`);if(!fresh)throw Error('Saved record is not available');const clone=fresh.cloneNode(true),parent=card.parentElement;card.replaceWith(clone);bind(parent);clone.querySelector('[data-authoring-status]').textContent='Saved.';clone.querySelector('[data-authoring-edit]')?.focus();}
async function read(){const response=await fetch(root.dataset.inspectUrl,{cache:'no-store'});if(!response.ok)throw Error('Recorded information is unavailable');const doc=new DOMParser().parseFromString(await response.text(),'text/html');if(!doc.querySelector('[data-authoring-content]'))throw Error('Authorisation or recorded information is unavailable');return doc;}
let loadEpoch=0;
async function load(){const mine=++loadEpoch;if(!root.dataset.inspectUrl){root.hidden=true;root.replaceChildren();return;}root.hidden=false;const pending=document.createElement('p');pending.textContent='Loading the selected chapter and scene notes…';root.replaceChildren(pending);try{const doc=await read();if(mine!==loadEpoch)return;root.replaceChildren(...doc.body.childNodes);bind(root);const references=document.querySelector('[data-authoring-references]'),template=root.querySelector('[data-authoring-companion]');if(references&&template)references.replaceChildren(template.content.cloneNode(true));}
catch{if(mine!==loadEpoch)return;root.replaceChildren();const p=document.createElement('p');p.textContent='Recorded information could not load. Your current work and existing editors remain available.';const retry=document.createElement('button');retry.type='button';retry.className='btn btn-outline-secondary';retry.textContent='Try again';retry.addEventListener('click',load);root.append(p,retry);}}
window.addEventListener('beforeunload',e=>{if(dirty()&&!allowLeave){e.preventDefault();e.returnValue='';}});
function guard(e){if(!dirty())return;const target=e.target.closest('a,form,[data-plan-focus]');if(!target||target.matches('[data-authoring-form],[data-work-start]')||target.target==='_blank'||target.hasAttribute('download'))return;if(target.tagName==='A'&&new URL(target.href,location.href).pathname===location.pathname&&new URL(target.href,location.href).search===location.search&&target.hash)return;if(!confirm(root.querySelector('[data-busy="true"]')?'A save is in progress and may finish after you leave. Leave this page?':'Leave without saving your inline edits?')){e.preventDefault();e.stopImmediatePropagation();}else allowLeave=true;}
document.addEventListener('click',e=>{if(e.target.closest('a,[data-plan-focus]'))guard(e);},true);document.addEventListener('submit',guard,true);window.addEventListener('pageshow',()=>allowLeave=false);
const navigationNotice=document.createElement('p');navigationNotice.className='writer3-caption';navigationNotice.hidden=true;root.before(navigationNotice);
let pendingFocus=null;
function applyFocus(focus){root.dataset.inspectUrl=focus.chapterID?`/WriterAuthoring/Inspect?bookId=${focus.bookID}&chapterId=${focus.chapterID}${focus.sceneID?'&sceneId='+focus.sceneID:''}`:'';pendingFocus=null;navigationNotice.hidden=true;void load();}
window.addEventListener('plotdirector:narrative-focus-changed',e=>{const focus=e.detail;if(focus.bookID!==Number(document.querySelector('[data-writer-focus]')?.dataset.bookId))return;
if(dirty()||root.querySelector('[data-authoring-form]:not([hidden])')){pendingFocus=focus;navigationNotice.hidden=false;navigationNotice.replaceChildren(document.createTextNode('Current focus changed. These editors retain their original target. '));const button=document.createElement('button');button.type='button';button.className='btn btn-sm btn-link';button.textContent='Show current focus';button.addEventListener('click',()=>{if(dirty()||root.querySelector('[data-authoring-form]:not([hidden])')){button.textContent='Save or cancel the open editor first';return;}applyFocus(pendingFocus);});navigationNotice.append(button);}else applyFocus(focus);
});
load();
})();