PlotDirector/PlotLine/wwwroot/js/shared-manuscript-focus.js

17 lines
14 KiB
JavaScript

// One user/book/canonical-manuscript focus stream over the window's existing presence connection.
(()=>{'use strict';function start(){const context=document.querySelector('[data-context-workspace]'),header=document.querySelector('[data-narrative-focus]'),reader=document.querySelector('.manuscript-reader');if(!context&&!header)return;const initial=window.PlotDirectorNarrativeFocus?.state||(header?JSON.parse(header.querySelector('[data-narrative-initial]').textContent):{});let project=Number(context?.dataset.scopeProjectId||initial.projectID),book=Number(context?.dataset.scopeBookId||initial.bookID),connection,connected=false,authoritative=false,readFlight=null,readAbort=null,readyKey=null,generation=0,disconnected=false,latest=null,local=null,epoch=0,sequence=0,held=false,publishing=false,selectionPublishing=false,queuedTarget=null;const user=document.body.dataset.pdUserId||context?.dataset.user||'',page=crypto.randomUUID(),buttons=[...document.querySelectorAll('[data-shared-focus-hold]')],outputs=[...document.querySelectorAll('[data-shared-focus-status]')];let id=context?.contextController?.windowId||sessionStorage.getItem('pd.shared-focus.window');if(!/^[\da-f-]{36}$/i.test(id||''))id=crypto.randomUUID();sessionStorage.setItem('pd.shared-focus.window',id);const normal=p=>({projectID:Number(p.projectID||p.projectId||project),bookID:Number(p.bookID||p.bookId||book),chapterID:Number(p.chapterID||p.chapterId)||null,sceneID:Number(p.sceneID||p.sceneId)||null,paragraphID:p.paragraphID||p.paragraphId||null,manuscriptID:p.manuscriptID||p.manuscriptId||null,originWindowID:p.originWindowID||p.originWindowId||null,version:Number(p.version||0),isValid:p.isValid!==false});const key=()=>`pd.shared-focus.${user}.${id}`;const positionKey=p=>p&&[p.projectID,p.bookID,p.manuscriptID,p.chapterID,p.sceneID,p.paragraphID].join('/');function save(){try{sessionStorage.setItem(key(),JSON.stringify({held,local,sequence}));}catch{}}function restore(){try{const data=JSON.parse(sessionStorage.getItem(key())||'null');held=data?.held??context?.dataset.followMode==='snapshot';local=data?.local||normal(context?.contextController?.position||{...initial,chapterID:Number(reader?.dataset.chapterId)||initial.chapterID});sequence=data?.sequence||0;}catch{held=false;}}
const traceEnabled=new URLSearchParams(location.search).get('focusDiagnostics')==='1',traceRows=[];function trace(stage,outcome,p=latest){if(!traceEnabled)return;traceRows.push({stage,outcome,source:context?'Context':'Review',windowID:id,bookID:book,chapterID:p?.chapterID,sceneID:p?.sceneID,paragraphID:p?.paragraphID,version:p?.version,held});if(traceRows.length>128)traceRows.shift();let panel=document.querySelector('[data-focus-diagnostics]');if(!panel){panel=document.createElement('pre');panel.dataset.focusDiagnostics='';document.body.append(panel);}panel.textContent=JSON.stringify(traceRows,null,2);}
let lastNotice='';function status(message=''){const available=!!book&&connected&&authoritative&&!disconnected;buttons.forEach(b=>{(b.querySelector('span')||b).textContent=held?'Release Hold':'Hold';b.setAttribute('aria-pressed',String(held));b.disabled=!available;b.classList.toggle('active',held);b.title=!available?(book?'Shared focus is connecting. Your local position is retained.':'Select a book first.'):(held?'Catch up to the latest shared manuscript position.':'Hold this window at its local manuscript position.');});outputs.forEach(n=>{n.textContent=message;n.hidden=!message;});document.documentElement.dataset.manuscriptFocusMode=held?'held':'follow';if(message&&message!==lastNotice){lastNotice=message;window.PlotDirector?.toast?.warning?.(message);}if(!message)lastNotice='';}function apply(position,reason){local=normal(position);save();trace('reconcile',reason,local);window.dispatchEvent(new CustomEvent('plotdirector:shared-focus',{detail:{position:local,reason}}));status();}function accept(packet,force=false,metadata=false){const next=normal(packet);if(next.bookID!==book||next.projectID!==project)return false;if(latest&&next.version<latest.version){trace('reconcile','stale-revision',next);return false;}if(latest&&!force&&next.version===latest.version){if(metadata&&latest.isValid!==next.isValid){latest={...latest,isValid:next.isValid};if(!held)status(next.isValid?'':'Shared focus is unavailable. Select a valid chapter or scene; your local position is retained.');}return false;}latest=next;if(publishing&&queuedTarget)return true;if(!held&&next.isValid&&next.chapterID&&(force||positionKey(local)!==positionKey(next)))apply(next,next.originWindowID===id&&selectionPublishing?'selection':'shared');else if(!held&&next.isValid&&next.chapterID)status();else if(!next.isValid&&!held)status('Shared focus is unavailable. Select a valid chapter or scene; your local position is retained.');return true;}
async function request(action,target={}){trace('request',action,normal(target));const token=document.querySelector('[name=__RequestVerificationToken]')?.value;if(!token)throw Error('Refresh this authenticated window before changing focus.');const body=new URLSearchParams({projectID:project,bookID:book,windowID:id,sequence:++sequence,__RequestVerificationToken:token});for(const[k,v]of Object.entries(target))if(v!=null&&['chapterID','sceneID','paragraphID','manuscriptID','direction'].includes(k))body.set(k,v);save();const response=await fetch('/NarrativeFocus/Shared/'+action,{method:'POST',body,cache:'no-store'});const packet=await response.json().catch(()=>null);if(!response.ok||response.redirected)throw Error(packet?.message||'Focus could not be changed. Your local reference is retained.');return normal(packet);}
function invalidateRead(){epoch++;generation++;readAbort?.abort();readAbort=null;readFlight=null;authoritative=false;}
function refresh(force=false){if(!book||!connected)return Promise.resolve(false);if(readFlight)return readFlight;const mine=++epoch,scope=book,transport=generation;readAbort=new AbortController();const signal=readAbort.signal;trace('read','started');const task=(async()=>{try{const response=await fetch(`/NarrativeFocus/Shared?projectID=${project}&bookID=${book}`,{cache:'no-store',signal});if(!response.ok||response.redirected)throw Error();const packet=await response.json();if(mine!==epoch||scope!==book||transport!==generation)return false;const recovering=disconnected;disconnected=false;authoritative=true;accept(packet,force,true);status(!held&&latest?.isValid===false?'Shared focus is unavailable. Select another position; your local reference is retained.':'');trace('read','reconciled');if(recovering)void validateLocal();return true;}catch(error){if(signal.aborted)return false;if(mine===epoch){disconnected=true;status('Shared focus disconnected. Your local position is retained.');trace('read','failed');}return false;}finally{if(readFlight===task){readFlight=null;readAbort=null;}}})();readFlight=task;return task;}
async function navigate(target,forcePublication=false){const priorLocal=local;if(target.localSelection&&Number(target.bookID||book)===book){local=normal({...local,projectID:project,bookID:book,chapterID:target.chapterID,sceneID:target.sceneID||null,paragraphID:target.paragraphID});save();}if(publishing){queuedTarget=target;return true;}const effective=held?priorLocal:latest?.isValid?latest:null;if(!forcePublication&&Number(target.sceneID||target.sceneId)>0&&Number(target.sceneID||target.sceneId)===effective?.sceneID&&!effective.paragraphID&&!target.paragraphID&&!target.paragraphId)return true;if(!forcePublication&&!target.direction&&!target.sceneID&&!target.sceneId&&!target.paragraphID&&!target.paragraphId&&Number(target.chapterID||target.chapterId)>0&&Number(target.chapterID||target.chapterId)===effective?.chapterID&&!effective.sceneID&&!effective.paragraphID)return true;const paragraph=target.paragraphID||target.paragraphId;if(!forcePublication&&paragraph&&paragraph===effective?.paragraphID&&Number(target.chapterID||target.chapterId)===effective.chapterID)return true;if(publishing)return false;if(target.bookID&&Number(target.bookID)!==book)return false;publishing=true;const localRequest=held;selectionPublishing=target.localSelection===true;try{const normalized={chapterID:target.chapterID||target.chapterId||null,sceneID:target.sceneID||target.sceneId||null,paragraphID:target.paragraphID||target.paragraphId||null,...(target.direction?{direction:target.direction}:{}),...(target.manuscriptID?{manuscriptID:target.manuscriptID}:{})};if(held&&target.direction)Object.assign(normalized,{chapterID:local.chapterID,sceneID:local.sceneID,paragraphID:local.paragraphID});const result=await request(localRequest?'Resolve':'Publish',normalized);if(result.bookID!==book||result.projectID!==project)return false;if(localRequest){if(held)apply(result,selectionPublishing?'selection':'local');else await refresh(true);}else accept(result,true);return true;}catch(error){status(error.message);return false;}finally{publishing=false;selectionPublishing=false;if(queuedTarget){const next=queuedTarget;queuedTarget=null;void navigate(next,true);}}}
async function toggle(){if(!connected||!authoritative||disconnected)return;queuedTarget=null;if(held){if(!await refresh()){status('Hold retained: reconnect before catching up to authoritative shared focus.');return;}held=false;save();if(latest?.isValid&&latest.chapterID)apply(latest,'release');else status('Following · no valid shared focus; local position retained.');}else{held=true;save();status();}window.dispatchEvent(new CustomEvent('plotdirector:focus-mode',{detail:{held}}));}
async function validateLocal(){if(!held||!local?.chapterID)return;try{const result=await request('Validate',local);if(!result.isValid)status('Held reference is no longer valid. Select another local position or Release Hold.');}catch{status('Held reference cannot be resolved. Select another position; data updates remain connected.');}}
function ready(c,reconnected=false){if(!c||c!==connection||c.state!=='Connected')return;connected=true;const key=c.connectionId||'connected';if(readyKey===key){if(!authoritative)void refresh();return;}readyKey=key;invalidateRead();status();trace('connection',reconnected?'reconnected':'ready');void refresh();}
function wire(c){if(!c||connection===c)return;if(connection)return;connection=c;c.on('ManuscriptFocusChanged',packet=>{trace('notification','received',normal(packet));accept(packet);});c.on('ManuscriptFocusDelivery',packet=>{if(Number(packet.bookID||packet.bookId)===book&&Number(packet.version)===latest?.version)status('Word cannot follow this reference in the background. Save and synchronise Word; other windows remain independent.');});c.on('ContextInvalidated',hint=>{if(hint.bookId&&Number(hint.bookId)!==book||hint.projectId&&Number(hint.projectId)!==project)return;window.dispatchEvent(new CustomEvent('plotdirector:reference-invalidated',{detail:hint}));void validateLocal();});function offline(){connected=false;disconnected=true;readyKey=null;invalidateRead();status('Shared focus disconnected. Your local position is retained.');trace('connection','disconnected');}c.onreconnecting(offline);c.onclose(offline);c.onreconnected(()=>ready(c,true));ready(c);}
const channel=!context&&window.BroadcastChannel?new BroadcastChannel('pd.shared-focus.identity.'+user):null;channel?.addEventListener('message',event=>{const m=event.data;if(m.id!==id||m.page===page)return;if(m.kind==='claim')channel.postMessage({kind:'occupied',id,page,target:m.page});if(m.kind==='occupied'&&m.target===page){id=crypto.randomUUID();sessionStorage.setItem('pd.shared-focus.window',id);held=false;sequence=0;save();status();void refresh(true);}});channel?.postMessage({kind:'claim',id,page});
context?.addEventListener('context-capabilities-changed',()=>{const next=context.contextController?.windowId;if(next&&next!==id){id=next;held=false;sequence=0;save();status();void refresh(true);}});
restore();status();buttons.forEach(b=>b.addEventListener('click',()=>void toggle()));document.addEventListener('pd-presence-connection',e=>wire(e.detail));document.addEventListener('pd-presence-ready',()=>{const c=window.PlotDirectorPresenceConnection;wire(c);ready(c);});context?.addEventListener('context-connection-ready',()=>{const c=context.contextController?.connection;wire(c);ready(c);});wire(context?.contextController?.connection||window.PlotDirectorPresenceConnection);window.addEventListener('focus',()=>void refresh());window.addEventListener('pagehide',()=>{save();channel?.close();});window.PlotDirectorSharedFocus={navigate,refresh,toggle,validateLocal,get held(){return held;},get local(){return local;},get shared(){return latest;},get windowID(){return id;},async go(){if(await refresh(true)&&held&&latest?.isValid)apply(latest,'local');},ownsScope:p=>Number(p.bookID)===book&&Number(p.projectID)===project,async scope(p){invalidateRead();project=Number(p.projectID);book=Number(p.bookID);queuedTarget=null;latest=null;const wasHeld=held;restore();held=wasHeld;local=normal(p);save();status();if(held)apply(local,'local');await refresh(true);}};document.addEventListener('click',async event=>{if(!event.isTrusted||event.defaultPrevented||event.button!==0||event.ctrlKey||event.metaKey||event.shiftKey||event.altKey)return;const link=event.target.closest('a[href]');if(!link||link.target&&link.target!=='_self'||link.closest('.reader-chapter-navigation'))return;const url=new URL(link.href,location.href);if(url.origin!==location.origin||url.searchParams.get('retainNarrativeFocus')==='true')return;const match=url.pathname.match(/^\/(Scenes\/Edit|Chapters\/(?:Details|Edit)|Writer\/Chapter)\/(\d+)$/i),timeline=/^\/Timeline(?:\/Index)?$/i.test(url.pathname)&&url.searchParams.get('navigateFocus')==='true';if(!match&&!timeline)return;const selectedScene=Number([...url.searchParams].find(([key])=>key.toLowerCase()==='selectedsceneid')?.[1]);const target=timeline?{sceneID:selectedScene}:match[1].toLowerCase()==='scenes/edit'?{sceneID:Number(match[2])}:{chapterID:Number(match[2])};if(timeline&&!selectedScene)return;event.preventDefault();const adapter=window.PlotDirectorFocusWorkspace?.adapter;try{if(adapter?.beforeChange&&await adapter.beforeChange(target)===false)return;await navigate(target);url.searchParams.delete('navigateFocus');url.searchParams.set('retainNarrativeFocus','true');location.assign(url);}finally{adapter?.changeFinished?.();}});window.dispatchEvent(new Event('plotdirector:shared-focus-ready'));void refresh();if(held&&local?.chapterID){apply(local,'restore');void validateLocal();}}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})();