32 lines
10 KiB
JavaScript
32 lines
10 KiB
JavaScript
// Consumes the existing native presence/status stream. No second background poller or global selection.
|
|
(()=>{'use strict';const root=document.querySelector('[data-writer-word]');if(!root)return;
|
|
const book=Number(root.dataset.bookId),chapter=Number(root.dataset.chapterId),scene=Number(root.dataset.sceneId),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 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;
|
|
const verified=l=>(packet?.verifiedPositions||[]).find(p=>key(p)===key(l));
|
|
const requestStatus=()=>window.dispatchEvent(new Event('plotdirector:refresh-word-status'));
|
|
function render(data){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&¤t.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'&¤t.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;
|
|
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.';
|
|
if(paragraphButton)paragraphButton.disabled ||= !root.dataset.paragraphId;
|
|
const params=new URLSearchParams(location.search),origin=current&¶ms.get('wordInstanceId')===current.instanceId&¶ms.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));
|
|
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();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.';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'){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){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;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);
|
|
})();
|