PlotDirector/PlotLine/wwwroot/js/native-companion-status.js

67 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(() => {
'use strict';const root=document.querySelector('#native-companion-status');if(!root)return;
const text=root.querySelector('#native-companion-status-text');let pending=false,seen=false,refreshAgain=false,reconnectPending=false;
const details=document.querySelector('#writing-connection-details'), documents=details?.querySelector('#writing-word-document');
const syncForm=details?.querySelector('[data-word-sync-form]'),syncButton=syncForm?.querySelector('[data-word-sync-button]'),syncFeedback=syncForm?.querySelector('[data-word-sync-feedback]');
let syncCurrent=null,syncPending=null;
syncForm?.addEventListener('submit',async event=>{
event.preventDefault();if(!event.isTrusted||!syncCurrent||syncButton.disabled)return;
const selected=syncCurrent;syncPending={key:selected.instanceId+'/'+selected.sessionId,revision:selected.snapshotRevision||0,started:Date.now()};syncButton.disabled=true;
syncFeedback.textContent='Requesting a saved paragraph snapshot from Word…';
const body=new URLSearchParams(new FormData(syncForm));body.set('instanceId',selected.instanceId);body.set('sessionId',selected.sessionId);
try{const response=await fetch((event.submitter?.hasAttribute('formaction')?event.submitter.formAction:syncForm.action),{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)});
if(response.redirected||!response.headers.get('content-type')?.includes('application/json'))throw Error('Sign in to PlotDirector again before requesting synchronisation.');
const result=await response.json();if(!response.ok)throw Error(result.message||'Synchronisation could not be requested.');syncFeedback.textContent=result.message;if(syncPending)syncPending.requestId=result.requestId&&result.requestId!=='00000000-0000-0000-0000-000000000000'?result.requestId:null;if(!syncPending?.requestId){syncPending=null;syncButton.disabled=false;}void update();
}catch(error){syncPending=null;syncButton.disabled=false;syncFeedback.textContent=error.message||'Could not contact PlotDirector. Your saved manuscript is unchanged.';}
});
root.addEventListener('click',()=>details?.showModal());
details?.querySelector('[data-close-word-details]')?.addEventListener('click',()=>details.close());
details?.querySelector('[data-word-return-to-current]')?.addEventListener('click',()=>{window.dispatchEvent(new Event('plotdirector:word-return-to-current'));details.close();});
documents?.addEventListener('change',()=>{documents.dataset.userSelected='true';window.dispatchEvent(new CustomEvent('plotdirector:word-document-selected',{detail:documents.value}));const button=details.querySelector('[data-word-return-to-current]');if(button)button.disabled=true;void update();});
function renderDetails(leases) {
if(!details)return;
const workspace=document.querySelector('[data-writing-context],[data-writing-intent]'),scopeBook=Number(workspace?.dataset.scopeBookId);
const selectable=leases.filter(l=>l.wordAvailable&&(!scopeBook||Number(l.bookId)===scopeBook));
details.querySelector('[data-word-connection-description]').textContent=workspace&&scopeBook&&!selectable.length?'No live Word document is linked to this book. Saved scenes remain available; use Companion to change a manuscript’s book association.':root.title;
const previousLabel=documents.selectedOptions[0]?.textContent||'Selected manuscript';
const selected=documents.dataset.userSelected==='true'?documents.value:documents.value || (document.querySelector('[data-word-instance]')?.dataset.wordInstance && document.querySelector('[data-word-session]')?.dataset.wordSession ? document.querySelector('[data-word-instance]').dataset.wordInstance+'/'+document.querySelector('[data-word-session]').dataset.wordSession : '');
const signature=selectable.map(l=>l.instanceId+'/'+l.sessionId+':'+l.documentTitle).join('|');
if(documents.dataset.signature!==signature){documents.dataset.signature=signature;documents.replaceChildren(new Option('Follow the active Word manuscript',''));for(const lease of selectable)documents.add(new Option(lease.documentTitle+(lease.active?' · active in Word':''),lease.instanceId+'/'+lease.sessionId));if(selected&&![...documents.options].some(o=>o.value===selected)){const stale=new Option(previousLabel.replace(/ · disconnected$/,'')+' · disconnected',selected);stale.disabled=true;documents.add(stale);}documents.value=selected;}
details.querySelector('[data-word-document-picker]')?.toggleAttribute('hidden',!workspace);
const activeInScope=selectable.filter(l=>l.active),selection=documents.value?selectable.find(l=>l.instanceId+'/'+l.sessionId===documents.value):activeInScope.length===1?activeInScope[0]:selectable.length===1?selectable[0]:null;
const returnButton=details.querySelector('[data-word-return-to-current]');if(returnButton)returnButton.disabled=!selection?.sceneId||selection.wordSaved===false;
const repairButton=details.querySelector('[data-word-repair-button]');if(repairButton)repairButton.disabled=!!syncPending||!selection?.bookId||selection.wordSaved!==true||selection.canChapterSync!==true;
syncCurrent=selection;
if(syncForm){syncForm.querySelector('[data-word-sync-book]').value=selection?.bookId||'';syncButton.disabled=!!syncPending||!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;
if(syncPending){const observed=selectable.find(l=>l.instanceId+'/'+l.sessionId===syncPending.key);
if(observed?.paragraphTransfer?.requestId===syncPending.requestId&&observed.paragraphTransfer.state==='accepted'&&(observed.paragraphTransfer.kind==='chapter'||observed.mappingCurrent&&Number(observed.snapshotRevision)>syncPending.revision)){syncPending=null;syncButton.disabled=!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;syncFeedback.textContent=observed.paragraphTransfer.message||'Word snapshot accepted. This session’s paragraph positions are verified; current scene following can resume.';}
else if(observed?.paragraphTransfer?.requestId===syncPending.requestId&&observed.paragraphTransfer.kind==='chapter'){syncFeedback.textContent=observed.paragraphTransfer.message;if(observed.paragraphTransfer.state==='needs-review'){syncPending=null;syncButton.disabled=false;}}
else if(syncPending.requestId&&(!observed||observed.paragraphTransfer?.requestId!==syncPending.requestId||observed.paragraphTransfer.state==='failed')){syncPending=null;syncButton.disabled=!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;syncFeedback.textContent='Word transfer ended without an accepted snapshot. Saved paragraphs are unchanged. Check Companion Troubleshooting, then retry.';}
else if(observed?.captureRequestId)syncFeedback.textContent='Reading Word: '+Math.max(0,Math.min(100,Number(observed.captureProgress)||0))+'%. Keep Word open until PlotDirector acknowledges the snapshot.';
else if(Date.now()-syncPending.started>120000){syncPending=null;syncButton.disabled=false;syncFeedback.textContent='No accepted snapshot has been confirmed. Open Manuscript structure and evidence below or Companion Troubleshooting before retrying.';}
}else if(selection?.chapterProgress){const progress=selection.chapterProgress;syncFeedback.textContent=progress.state+' · '+progress.matching+'/'+progress.total+' chapter mappings accepted. '+progress.message;}else if(!selection)syncFeedback.textContent='Open the intended manuscript in Word and select its current connection. Saved scene browsing remains available.';
else if(selection.wordSaved!==true)syncFeedback.textContent='Save the manuscript in Word before requesting synchronisation.';
else if(selection.canParagraphSync!==true)syncFeedback.textContent='The connected add-in has not advertised paragraph synchronisation. Check the installed Companion and Word connection.';
}
const active=leases.filter(l=>l.active&&l.wordAvailable),available=leases.filter(l=>l.wordAvailable);
const current=leases.find(l=>l.instanceId+'/'+l.sessionId===documents.value)||(active.length===1?active[0]:available.length===1?available[0]:null);
const book=Number(workspace?.dataset.scopeBookId||current?.bookId),links=details.querySelector('[data-word-book-links]');
if(links){links.hidden=!Number.isSafeInteger(book)||book<=0;if(!links.hidden){links.querySelector('[data-word-book-link]').href='/Books/Details/'+book;links.querySelector('[data-word-structure-link]').href='/manuscript/paragraphs?bookId='+book;}}
details.querySelector('[data-word-connection-diagnostics]').textContent=leases.length?'Current authenticated sessions: '+leases.length+'. Heartbeats expire after 45 seconds. Last checked '+new Date().toLocaleTimeString()+'. No manuscript text is transferred by these checks.':'No current Word session. Open Companion, check sign-in and book association, then reopen the manuscript.';
}
function offline(message){root.dataset.nativeAuthority=root.dataset.officeConnected==='true'?'false':'true';root.dataset.connected='false';root.classList.remove('is-connected');root.classList.add('is-offline');text.textContent=message;root.title=message+' · saved PlotDirector information remains available.';}
async function update(reconnected=false){reconnectPending ||= reconnected;if(document.hidden)return;if(pending){refreshAgain=true;return;}pending=true;const reconnect=reconnectPending;reconnectPending=false;try{
const response=await fetch('/native-companion/status',{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw new Error();const leases=(await response.json()).filter(l=>Date.parse(l.expires)>Date.now());const active=leases.filter(l=>l.active&&l.wordAvailable),words=leases.filter(l=>l.wordAvailable);const lease=active.length===1?active[0]:words.length===1?words[0]:words.length===0?leases[0]:null;if(words.length>1&&active.length!==1){seen=true;offline('Choose an active Word document');}
if(lease){leases.connectionState="Connected";leases.known=true;seen=true;root.dataset.nativeAuthority='true';root.dataset.connectionState='Connected';root.dataset.connected='true';root.classList.add('is-connected');root.classList.remove('is-offline');text.textContent=lease.wordAvailable?'Word connected':'Companion connected';root.title=lease.wordAvailable?lease.documentTitle+' · verified document heartbeat · last update '+new Date(lease.updated).toLocaleTimeString():'Companion connected; open a linked manuscript in Word.';}
else {
const stateResponse=await fetch('/native-companion/connection-state',{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});
const device=stateResponse.ok?await stateResponse.json():null;leases.connectionState=device?.state||"Disconnected";leases.known=!!device?.known;
if(device?.known){seen=true;const label=device.state==='Connected'?'Companion connected · Word not connected':device.state;offline(label);root.dataset.connectionState=device.state;if(device.state==='Connected'){root.dataset.nativeAuthority='true';root.dataset.connected='true';root.classList.add('is-connected');root.classList.remove('is-offline');root.title='Approved Companion is connected. No live Word document is registered.';}}
else if(seen)offline('Word disconnected or stale');else if(text.textContent==='Checking Word…')offline('Word disconnected');
}leases.reconnected=reconnect;root.nativePresence=leases;renderDetails(leases);window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases}));
}catch{offline('Companion status unavailable');const unavailable=[];unavailable.connectionState='Disconnected';unavailable.reconnected=reconnect;root.nativePresence=unavailable;renderDetails(unavailable);window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:unavailable}));}finally{pending=false;if(refreshAgain){refreshAgain=false;void update();}}}
let reconnectHub=()=>{};void update();const timer=setInterval(()=>{reconnectHub();void update();},15000);document.addEventListener('visibilitychange',()=>{if(!document.hidden)void update();});window.addEventListener('pagehide',()=>clearInterval(timer));
if(window.signalR){let refresh;const connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();connection.on('NativePresenceChanged',()=>{clearTimeout(refresh);refresh=setTimeout(()=>void update(),250);});connection.onreconnected(()=>void update(true));let starting=false;reconnectHub=()=>{if(starting||connection.state&&connection.state!=='Disconnected')return;starting=true;void connection.start().then(()=>void update(true)).catch(()=>{}).finally(()=>starting=false);};reconnectHub();window.addEventListener('pagehide',()=>{clearTimeout(refresh);void connection.stop();});}
})();