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

89 lines
18 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 selectionKey='plotdirector.writer.word-selection.'+(document.body.dataset.pdUserId||'')+'.'+book;
let explicitSelection=null;try{const saved=JSON.parse(sessionStorage.getItem(selectionKey)||'null');if(typeof saved?.key==='string'&&/^[0-9a-f-]{36}\/[0-9a-f-]{36}$/i.test(saved.key)&&typeof saved.title==='string'&&saved.title.length<=260)explicitSelection=saved;}catch{}
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){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=explicitSelection?.key||select.value||originKey;select.replaceChildren(new Option('Choose a document',''),...leases.map(l=>new Option(l.documentTitle,key(l))));const missingSelection=!!explicitSelection&&!leases.some(l=>key(l)===explicitSelection.key);if(missingSelection){const missing=new Option(explicitSelection.title+' · disconnected',explicitSelection.key);missing.disabled=true;select.add(missing);select.value=explicitSelection.key;}else 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&&!missingSelection;
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&&Date.now()-syncPending.started>120000){message.textContent='Saved manuscript check was not confirmed. Check Companion Troubleshooting before retrying; accepted content is retained.';window.PlotDirector?.toast?.error(message.textContent);window.PlotDirector?.wordNotifications?.forget(syncPending.key);}
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?(missingSelection?'Selected Word document is disconnected. Choose another document explicitly.':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.':current?.wordSaved===null?'Word position awaits a fresh observation. Check the intended document in Word; accepted text is retained.':'Word position has not been verified.';
const chapterStatus=window.PlotDirector.wordChapterStatus(data,current,book,chapter);
freshness.textContent=chapterStatus.text+(current&&current.canSharedFocus!==true?' Update Word Companion to use shared manuscript focus.':'');for(const ribbon of document.querySelectorAll('[data-word-ribbon-status]')){ribbon.textContent=chapterStatus.label;ribbon.title=chapterStatus.text;}
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.':chapterStatus.text);
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.dataset.navigationTitle+(button.disabled?' Select a verified target and connect its saved Word manuscript; inspect Companion Troubleshooting if chapter reading failed.':'');}
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 objective is unchanged.';}
}
select.addEventListener('change',()=>{const lease=packet?.leases?.find(l=>key(l)===select.value);explicitSelection=lease?{key:key(lease),title:lease.documentTitle}:null;try{if(explicitSelection)sessionStorage.setItem(selectionKey,JSON.stringify(explicitSelection));else sessionStorage.removeItem(selectionKey);}catch{}render(packet);});
adopt.addEventListener('submit',async event=>{event.preventDefault();if(adopt.hidden||!window.PlotDirectorNarrativeFocus)return;await window.PlotDirectorNarrativeFocus.set({bookID:book,chapterID:Number(adopt.querySelector('[name=ChapterID]').value),sceneID:Number(adopt.querySelector('[name=SceneID]').value)||null});});
window.addEventListener('plotdirector:narrative-focus-changed',event=>{if(event.detail.bookID!==book||reviewing)return;applyNarrative(event);});
window.addEventListener('review:narrative-applied',event=>{if(reviewing&&event.detail.bookID===book)applyNarrative(event);});
function applyNarrative(event){const targetChapter=Number(event.detail.chapterID)||0,targetScene=Number(event.detail.sceneID)||0;if(chapter===targetChapter&&scene===targetScene)return;abort?.abort();message.textContent=busy?'Navigation was not confirmed because the intended target changed. Check Word before retrying.':'';chapter=targetChapter;scene=targetScene;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 signal=abort.signal,selected={...current},id=crypto.randomUUID(),dispatch=performance.now();
let notified=false,notificationAt=null,resume=null;
const hint=event=>{const target=Number(event.detail?.bookId);if(target!==0&&target!==book)return;notified=true;notificationAt??=performance.now();resume?.();};
// Register before POST; an acknowledgement can race the accepted response.
window.addEventListener('plotdirector:native-presence-changed',hint);
const wait=()=>new Promise((resolve,reject)=>{
const finish=()=>{clearTimeout(timer);signal.removeEventListener('abort',cancel);resume=null;resolve();};
const cancel=()=>{clearTimeout(timer);signal.removeEventListener('abort',cancel);resume=null;reject(new DOMException('Navigation was not confirmed.','AbortError'));};
const timer=setTimeout(finish,1000);resume=finish;signal.addEventListener('abort',cancel,{once:true});if(signal.aborted)cancel();else if(notified)finish();
});
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});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.');
if(data?.navigationId&&data.navigationId!==id)throw Error('Navigation response did not match this request.');
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,first=true;
while(Date.now()-start<30000){
if(!first&&!notified)await wait();first=false;notified=false;const notificationStarted=notificationAt;notificationAt=null;
const query=new URLSearchParams({bookId:String(book),instanceId:selected.instanceId,sessionId:selected.sessionId,manuscriptId:selected.manuscriptId,revision:String(selected.revision),navigationId:id});
const receipt=await fetch('/WriterWord/Navigation?'+query,{signal,cache:'no-store'});if(!receipt.ok)throw Error('Navigation confirmation unavailable.');const result=await receipt.json();
if(notificationStarted!==null)console.debug('Word navigation',id,'notification-to-receipt ms',Math.round(performance.now()-notificationStarted));
if(result.state!=='requested'){
if(result.state==='completed'&&(result.navigationId!==id||result.instanceId!==selected.instanceId||result.sessionId!==selected.sessionId||result.manuscriptId!==selected.manuscriptId||Number(result.revision)!==Number(selected.revision)))throw Error('Navigation confirmation did not match this document and request.');
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.';window.PlotDirector?.toast?.[result.state==='completed'?'success':'error'](message.textContent);done=true;break;
}
}
if(!done){message.textContent='Word did not confirm navigation in time. Check the manuscript before retrying.';window.PlotDirector?.toast?.error(message.textContent);}
}catch(error){availabilityKey='';availability={};message.textContent=error.name==='AbortError'?'Navigation was not confirmed. Check Word before retrying.':error.message;window.PlotDirector?.toast?.error(message.textContent);}
finally{window.removeEventListener('plotdirector:native-presence-changed',hint);resume?.();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;window.PlotDirector?.wordNotifications?.requested(selected,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.';window.PlotDirector?.toast?.error(message.textContent);}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 the reported connection and current chapter evidence. For a reading failure, inspect Companion Troubleshooting; synchronisation acknowledgement alone does not confirm verification.';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);
})();