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

8 lines
2.6 KiB
JavaScript

(()=>{const root=document.querySelector('[data-activity-planner]');if(!root)return;let view=new URLSearchParams(location.search).get('view')||'list',busy=false,dirty=false,allow=false;
async function load(){const url=new URL(root.dataset.url,location.href);url.searchParams.set('view',view);const r=await fetch(url,{cache:'no-store'});if(!r.ok)throw Error('The planner could not load. Reload when connected.');const doc=new DOMParser().parseFromString(await r.text(),'text/html'),panel=doc.querySelector('[data-planner-view]');if(!panel)throw Error('Sign in to resume your planner.');root.replaceChildren(panel);const schedule=document.querySelector('[data-planner-schedule-existing]');if(schedule)schedule.hidden=view!=='schedule';dirty=false;}
root.addEventListener('input',()=>dirty=true);
root.addEventListener('click',async event=>{const tab=event.target.closest('[data-planner-tab]');if(!tab||busy)return;if(dirty&&!confirm('Leave unsaved activity edits?'))return;view=tab.dataset.plannerTab;try{await load();}catch(e){root.querySelector('[data-planner-message]').textContent=e.message;}});
root.addEventListener('submit',async event=>{const form=event.target;if(form.matches('[data-activity-start]')){if(form.dataset.pending==='true'||dirty&&!confirm('Leave unsaved activity edits and start this work?')){event.preventDefault();return;}form.dataset.pending='true';allow=true;return;}if(!form.matches('[data-activity-change],[data-activity-save]'))return;event.preventDefault();if(busy)return;const payload=new FormData(form);busy=true;root.setAttribute('aria-busy','true');const button=event.submitter,locked=[...root.querySelectorAll('button,input,select,textarea')].map(node=>[node,node.disabled]);for(const [node] of locked)node.disabled=true;let committed=false;const message=form.querySelector('[data-activity-error]')||root.querySelector('[data-planner-message]');message.textContent='Saving…';try{const r=await fetch(form.action,{method:'POST',body:payload});if(!r.ok){const data=await r.json().catch(()=>null);throw Error(data?.message||'Save not confirmed. Your text is retained. Reload before retrying.');}committed=true;dirty=false;await load();}catch(e){message.textContent=committed?'Saved, but the refreshed planner could not load. Reload the page before making another change.':e.message;}finally{busy=false;root.removeAttribute('aria-busy');for(const [node,disabled] of locked)if(node.isConnected)node.disabled=disabled;button.disabled=committed&&form.isConnected;}});
window.addEventListener('beforeunload',e=>{if((dirty||busy)&&!allow){e.preventDefault();e.returnValue='';}});load().catch(e=>{root.textContent=e.message;});
})();