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

72 lines
15 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';let root=document.querySelector('#native-companion-status');
// The title-bar presence preference must not disable Writer's shared status stream.
if(!root&&document.querySelector('[data-writer-word]')){root=document.createElement('span');root.id='native-companion-status';root.hidden=true;const label=document.createElement('span');label.id='native-companion-status-text';root.append(label);document.querySelector('[data-writer-word]').append(root);}
if(!root||root.nativeStatusStarted)return;root.nativeStatusStarted=true;
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;window.PlotDirector?.wordNotifications?.requested(selected,result.requestId);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.';window.PlotDirector?.toast?.error(syncFeedback.textContent);}
});
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-context-workspace]'),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;
if(selectable.some(lease=>lease.canSharedFocus!==true))details.querySelector('[data-word-connection-description]').textContent+=' Shared manuscript focus requires an updated Word Companion. Existing editing and content synchronisation remain available.';
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){window.PlotDirector?.wordNotifications?.forget(syncPending.key);syncPending=null;syncButton.disabled=false;syncFeedback.textContent='No accepted snapshot has been confirmed. Open Manuscript structure and evidence below or Companion Troubleshooting before retrying.';window.PlotDirector?.toast?.error(syncFeedback.textContent);}
}else if(selection?.chapterIssue==='needs_review'){syncFeedback.textContent='Companion reports a chapter-reading failure. Open Companion Settings → Advanced mode → Troubleshooting to inspect the reading diagnostics and recovery options. Synchronise alone does not confirm chapter reading or acceptance.';}else if(['failed','needs-review','cancelled'].includes(selection?.paragraphTransfer?.state)){syncFeedback.textContent=selection.paragraphTransfer.message||'The last Word transfer needs attention. Accepted content is retained; inspect Companion details.';}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.';
else syncFeedback.textContent='No chapter-reading failure is currently reported. Current chapter verification is shown in the ribbon; accepted content is retained.';
}
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(document.querySelector('[data-writer-word]')?.dataset.statusUrl||'/native-companion/status',{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw new Error();const packet=await response.json();const leases=(Array.isArray(packet)?packet:packet.leases).filter(l=>Date.parse(l.expires)>Date.now());if(!Array.isArray(packet)){root.writerWordState=packet;window.dispatchEvent(new CustomEvent('writer-word-state',{detail:packet}));}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{window.dispatchEvent(new CustomEvent('writer-word-state',{detail:{unavailable:true}}));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();let timer;const startTimer=()=>{clearInterval(timer);timer=setInterval(()=>{reconnectHub();void update();},15000);};startTimer();window.addEventListener('pageshow',event=>{if(event.persisted){startTimer();reconnectHub();void update(true);}});document.addEventListener('visibilitychange',()=>{if(!document.hidden)void update();});window.addEventListener('pagehide',()=>clearInterval(timer));window.addEventListener('plotdirector:refresh-word-status',event=>void update(!!event.detail?.reconnected));
if(window.signalR&&!document.querySelector('[data-context-workspace]')){let refresh;const connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();window.PlotDirectorPresenceConnection=connection;document.dispatchEvent(new CustomEvent('pd-presence-connection',{detail:connection}));connection.on('NativePresenceChanged',hint=>{window.dispatchEvent(new CustomEvent('plotdirector:native-presence-changed',{detail:hint}));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);document.dispatchEvent(new Event('pd-presence-ready'));}).catch(()=>{}).finally(()=>starting=false);};reconnectHub();window.addEventListener('pagehide',()=>{clearTimeout(refresh);void connection.stop();});}
})();