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

43 lines
14 KiB
JavaScript

// Consumes the existing native presence/status stream. No second background poller or global selection.
(()=>{'use strict';let root=document.querySelector('[data-writer-word]');if(root?.dataset.bound)return;if(!root){const template=document.querySelector('[data-word-fallback]');if(!template)return;const holder=document.createElement('details');holder.className='writer3-inset';holder.dataset.wordFallbackProvider='true';holder.hidden=!Number(template.content.querySelector('[data-writer-word]')?.dataset.chapterId);const summary=document.createElement('summary');summary.textContent='Word connection and manuscript';holder.append(summary,template.content.cloneNode(true));document.querySelector('main')?.append(holder);root=holder.querySelector('[data-writer-word]');}if(!root)return;root.dataset.bound='true';
document.querySelector('[data-review-diagnostics-open]')?.addEventListener('click',()=>{document.querySelector('[data-review-diagnostics]').open=true;});
const book=Number(root.dataset.bookId);let chapter=Number(root.dataset.chapterId),scene=Number(root.dataset.sceneId);const state=root.querySelector('[data-word-state]'),position=root.querySelector('[data-word-position]'),freshness=root.querySelector('[data-word-freshness]'),message=root.querySelector('[data-word-command]'),choose=root.querySelector('[data-word-choose]'),select=root.querySelector('[data-word-document]'),nav=root.querySelector('[data-word-navigate]'),sceneNav=root.querySelector('[data-word-scene]'),adopt=root.querySelector('[data-word-adopt]');
const reviewing=root.dataset.wordContext==='review',paragraphButton=root.querySelector('[data-word-paragraph]');
let availabilityKey='',availability={},availabilityEpoch=0,availabilityChecked=0;let packet=null,current=null,busy=false,abort=null,checkBusy=false,syncPending=null;const sync=root.querySelector('[data-word-sync]');
const key=l=>l.instanceId+'/'+l.sessionId;new MutationObserver(()=>{for(const status of document.querySelectorAll('[data-word-ribbon-status]'))status.textContent=message.textContent;}).observe(message,{childList:true,subtree:true,characterData:true});
const verified=l=>(packet?.verifiedPositions||[]).find(p=>key(p)===key(l));
const requestStatus=()=>window.dispatchEvent(new Event('plotdirector:refresh-word-status'));
function render(data){chapter=Number(root.dataset.chapterId);scene=Number(root.dataset.sceneId);packet=data;const old=current;const leases=(data.leases||[]).filter(l=>l.wordAvailable&&l.bookId===book&&Date.parse(l.expires)>Date.now());const originParams=new URLSearchParams(location.search);const originKey=originParams.get('wordInstanceId')+'/'+originParams.get('wordSessionId');const selected=select.value||originKey;select.replaceChildren(new Option('Choose a document',''),...leases.map(l=>new Option(l.documentTitle,key(l))));if(leases.some(l=>key(l)===selected))select.value=selected;else if(leases.length===1)select.value=key(leases[0]);current=leases.find(l=>key(l)===select.value)||null;choose.hidden=leases.length<2;
if(old&&(!current||key(old)!==key(current)||old.revision!==current.revision||old.manuscriptId!==current.manuscriptId)&&busy){abort?.abort();message.textContent='Word document changed or disconnected. Navigation was not confirmed.';}
if(syncPending&&(!current||syncPending.key!==key(current)||Date.now()-syncPending.started>120000||(syncPending.requestId&&current.paragraphTransfer?.requestId===syncPending.requestId&&['accepted','needs-review','failed','cancelled'].includes(current.paragraphTransfer.state))))syncPending=null;
const identity=current&&data.canonical?.manuscriptID===current.manuscriptId;const observed=current&&verified(current);
state.textContent=data.unavailable?'Word Companion status unavailable. Your saved work is retained.':!current?(leases.length>1?'Choose the correct Word manuscript.':(data.leases||[]).some(l=>l.wordAvailable)?'The open Word manuscript is for another book.':'Word Companion is not connected to this manuscript.'):!identity?'Word is connected, but this manuscript has not been verified.':`Manuscript: ${current.documentTitle}`;
position.textContent=observed?`Word is showing ${observed.chapterTitle||'the verified chapter'}${observed.sceneId&&observed.sceneTitle?' · '+observed.sceneTitle:''}. ${observed.chapterId!==chapter?(reviewing?'Your review selection is separate.':'Your working focus is separate.'):''}`:current?.wordSaved===false?'Word has unsaved changes. Current positions await verification; no save will be forced.':'Word position has not been verified.';
let status=!identity?'Your latest changes have not yet been confirmed in PlotDirector.':current.chapterProgress?.state==='Needs review'||current.chapterIssue==='needs_review'?'Manuscript checking needs attention in Companion. Accepted content is retained.':current.paragraphTransfer?.state==='failed'?'Manuscript update failed. Accepted content is retained.':current.chapterProgress?.state==='Synchronised'&&current.wordSaved===true?'The last manuscript check completed. Later edits may still be pending.':current.chapterProgress?.state?`${current.chapterProgress.state}: ${current.chapterProgress.message||'Latest changes are not yet confirmed.'}`:'Latest changes are not yet confirmed. Check synchronisation in Companion.';
if(data.canonical?.chapterAcceptedUtc)status+=' This chapter last accepted: '+new Date(data.canonical.chapterAcceptedUtc).toLocaleString()+'.';else if(data.canonical?.snapshotUtc)status+=' Accepted snapshot recorded: '+new Date(data.canonical.snapshotUtc).toLocaleString()+'.';freshness.textContent=status;const warning=document.querySelector('[data-review-word-warning]');if(warning)warning.textContent='Showing accepted text. '+(!current?state.textContent:current.wordSaved===false?'Word has unsaved changes; they are not shown here.':status);
sync.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!(current.canChapterSync||current.canParagraphSync);
for(const button of [nav,sceneNav,paragraphButton])if(button)button.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!current.canAcknowledgeNavigation;
if(identity&&!current.canAcknowledgeNavigation)position.textContent+=' Update the Word add-in and Companion together to enable confirmed navigation.';
const targetKey=identity&&current.wordSaved===true&&chapter?[chapter,scene,root.dataset.paragraphId,root.dataset.acceptedRevision,key(current),current.manuscriptId,current.revision,current.canAcknowledgeNavigation,current.canChapterSync,current.canParagraphSync,data.canonical?.revision,data.canonical?.chapterAcceptedUtc,data.canonical?.snapshotUtc].join(':'):'';
if(targetKey!==availabilityKey||(targetKey&&(availability.chapter===false||scene&&availability.scene===false||root.dataset.paragraphId&&availability.paragraph===false)&&Date.now()-availabilityChecked>=5000)){availabilityKey=targetKey;availability={};availabilityChecked=Date.now();const epoch=++availabilityEpoch;
if(targetKey){const query=new URLSearchParams({bookId:book,chapterId:chapter,instanceId:current.instanceId,sessionId:current.sessionId,manuscriptId:current.manuscriptId,revision:current.revision});if(scene)query.set('sceneId',scene);if(root.dataset.paragraphId){query.set('paragraphId',root.dataset.paragraphId);query.set('acceptedRevision',root.dataset.acceptedRevision);}
fetch('/WriterWord/Availability?'+query,{cache:'no-store',signal:AbortSignal.timeout(10000)}).then(async response=>{if(!response.ok)throw Error();return response.json();}).then(value=>{if(epoch!==availabilityEpoch)return;availability=value;if(packet)render(packet);}).catch(()=>{if(epoch!==availabilityEpoch)return;message.textContent='Verified Word target mapping is unavailable. Check synchronisation or retry the connection.';availabilityKey='';});}
}
if(nav)nav.disabled ||= availability.chapter!==true;if(sceneNav)sceneNav.disabled ||= availability.scene!==true;if(paragraphButton)paragraphButton.disabled ||= availability.paragraph!==true;
if(nav)nav.disabled ||= !chapter;if(sceneNav)sceneNav.disabled ||= !scene;if(paragraphButton)paragraphButton.disabled ||= !root.dataset.paragraphId;
for(const button of document.querySelectorAll('[data-ribbon-word]')){const original=button.dataset.ribbonWord==='chapter'?nav:button.dataset.ribbonWord==='scene'?sceneNav:paragraphButton;button.disabled=!original||original.disabled;button.title=button.disabled?'Select a verified target, connect and synchronise its Word manuscript':button.textContent.trim();}
const params=new URLSearchParams(location.search),origin=current&&params.get('wordInstanceId')===current.instanceId&&params.get('wordSessionId')===current.sessionId;
adopt.hidden=reviewing||!(origin&&observed&&observed.chapterId!==chapter);if(!adopt.hidden){adopt.querySelector('[name=ChapterID]').value=observed.chapterId;adopt.querySelector('[name=SceneID]').value=observed.sceneId||'';adopt.querySelector('[data-word-origin]').textContent='Opened from verified Word chapter '+(observed.chapterTitle||'in this manuscript')+'. Your saved working focus is unchanged.';}
}
select.addEventListener('change',()=>render(packet));
window.addEventListener('plotdirector:focus-saved',event=>{abort?.abort();message.textContent='Working target changed. Word has not moved.';chapter=Number(event.detail.chapterID)||0;scene=Number(event.detail.sceneID)||0;root.dataset.chapterId=chapter||'';root.dataset.sceneId=scene||'';root.dataset.paragraphId='';root.dataset.statusUrl='/native-companion/status?writerBookId='+book+'&writerChapterId='+chapter;if(packet)render(packet);requestStatus();});
for(const button of document.querySelectorAll('[data-ribbon-word]'))button.addEventListener('click',()=>{if(button.disabled)return;(button.dataset.ribbonWord==='chapter'?nav:button.dataset.ribbonWord==='scene'?sceneNav:paragraphButton)?.click();});
async function navigate(toScene,toParagraph=false){if(busy||!current||!chapter)return;if(Date.parse(current.expires)<=Date.now()){message.textContent='Word connection expired. Check the connection before navigating.';render({...packet,leases:[]});requestStatus();return;}busy=true;abort=new AbortController();const selected={...current},id=crypto.randomUUID(),dispatch=performance.now();render(packet);message.textContent='Requesting navigation in Word…';const form=new URLSearchParams({bookId:String(book),chapterId:String(chapter),instanceId:selected.instanceId,sessionId:selected.sessionId,manuscriptId:selected.manuscriptId,revision:String(selected.revision),navigationId:id,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});if(toScene)form.set('sceneId',String(scene));if(toParagraph){form.set('paragraphId',root.dataset.paragraphId);form.set('acceptedRevision',root.dataset.acceptedRevision);}try{const response=await fetch('/WriterWord/Navigate',{method:'POST',body:form,signal:abort.signal});const data=await response.json().catch(()=>null);if(!response.ok)throw Error(data?.message||'Navigation could not be requested. Check your connection and sign-in.');message.textContent='Requested in Word; waiting for confirmation.';console.debug('Word navigation',id,'server request ms',Math.round(performance.now()-dispatch));const start=Date.now();let done=false;while(Date.now()-start<30000){await new Promise((resolve,reject)=>{const signal=abort.signal;const cancel=()=>{clearTimeout(timer);reject(new Error('Navigation was not confirmed. Word changed or disconnected.'));};const timer=setTimeout(()=>{signal.removeEventListener('abort',cancel);resolve();},1000);signal.addEventListener('abort',cancel,{once:true});});const receipt=await fetch(`/WriterWord/Navigation?bookId=${book}&instanceId=${selected.instanceId}&sessionId=${selected.sessionId}&navigationId=${id}`,{signal:abort.signal,cache:'no-store'});if(!receipt.ok)throw Error('Navigation confirmation unavailable.');const result=await receipt.json();if(result.state!=='requested'){console.debug('Word navigation',id,'confirmation ms',Math.round(performance.now()-dispatch),result.state);message.textContent=result.state==='completed'?(toParagraph?'Word confirmed navigation to the paragraph start.':'Word confirmed navigation.'):result.state==='failed'?'Word could not navigate. Your work was retained.':'Navigation expired or the document changed. No completion was confirmed.';done=true;break;}}if(!done)message.textContent='Word did not confirm navigation in time. Check the manuscript before retrying.';}catch(error){availabilityKey='';availability={};message.textContent=error.name==='AbortError'?'Navigation was not confirmed. Check Word before retrying.':error.message;}finally{busy=false;abort=null;if(packet)render(packet);requestStatus();}}
sync.addEventListener('click',async()=>{if(sync.disabled||!current)return;const selected={...current};syncPending={key:key(selected),started:Date.now()};sync.disabled=true;const body=new URLSearchParams({bookId:String(book),instanceId:selected.instanceId,sessionId:selected.sessionId,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});try{const response=await fetch('/manuscript/paragraphs/snapshot',{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)});const result=await response.json();if(!response.ok||response.redirected)throw Error(result.message||'Manuscript check unavailable.');if(syncPending)syncPending.requestId=result.requestId;message.textContent='Saved manuscript check requested; acceptance has not yet been confirmed. '+(result.message||'');}catch(error){syncPending=null;message.textContent=error.message||'Could not request manuscript check.';}finally{requestStatus();}});
paragraphButton?.addEventListener('click',()=>void navigate(false,true));window.addEventListener('review-reference-changed',()=>{if(packet)render(packet);});
nav?.addEventListener('click',()=>void navigate(false));sceneNav?.addEventListener('click',()=>void navigate(true));
root.querySelector('[data-word-check]').addEventListener('click',()=>{if(checkBusy)return;checkBusy=true;availabilityKey='';availability={};message.textContent='Checking reported connection and accepted updates. Use Synchronise in Companion to request a bounded manuscript check.';requestStatus();setTimeout(()=>checkBusy=false,2000);});
window.addEventListener('writer-word-state',event=>render(event.detail));window.addEventListener('native-companion-presence',event=>{if(!event.detail.length&&packet&&!packet.leases?.length&&event.detail.connectionState==='Connected')state.textContent='Companion is connected; open and verify this manuscript in Word.';});window.addEventListener('pagehide',()=>abort?.abort());const initial=document.querySelector('#native-companion-status')?.writerWordState;if(initial)render(initial);
})();