(() => { 'use strict'; const root = document.querySelector('[data-context-workspace]'); if (!root || root.contextController) return; const registry = new Map(JSON.parse(root.querySelector('[data-context-tabs]').textContent).map(tab => [tab.id, tab])); const scopes = ['None', 'Book', 'Chapter', 'Scene', 'Paragraph']; const fields = ['projectId', 'bookId', 'chapterId', 'sceneId', 'paragraphId']; const number = value => Number.isSafeInteger(Number(value)) && Number(value) > 0 ? Number(value) : null; const uuid = () => crypto.randomUUID(); const status = root.querySelector('[data-context-status]'); const grid = root.querySelector('[data-context-panes]'); const divider = root.querySelector('[data-context-divider]'); const layoutSelect = root.querySelector('[data-context-layout]'); const sceneSelect = root.querySelector('[data-context-scene]'); const pinned = root.dataset.followMode === 'snapshot'; const scope = { projectId:number(root.dataset.scopeProjectId), bookId:number(root.dataset.scopeBookId) }; let position = { ...scope, chapterId:number(root.dataset.chapterId), sceneId:number(root.dataset.sceneId), paragraphId:null }; let nativeLeases = [], generation = 0, stopped = false, connection, connectionStarting = false, recoveryGeneration = 0; let navigationRequest, manualGeneration = 0, recoveryPending = false, recoveryAgain = false; const requests = new Map(); const lifecycles = { reference: { mount() {}, dispose() {} }, ...(window.PlotDirectorContextLifecycles || {}) }; const read = (storage,key) => { try { return storage.getItem(key); } catch { return null; } }; const write = (storage,key,value) => { try { storage.setItem(key,value); } catch { /* UI storage is optional. */ } }; let windowId = new URL(location.href).searchParams.get('contextWindow') || read(sessionStorage,'plotdirector.context.window.v1'); if (!/^[a-f0-9-]{36}$/i.test(windowId || '')) windowId = uuid(); try { if (window.opener?.document.querySelector('[data-context-workspace]')?.contextController?.windowId === windowId) windowId = uuid(); } catch { } const defaults = () => ({ version:1, layout:'single', ratio:.5, selectedDocument:'', panes:[{tab:'overview',views:{}},{tab:'characters',views:{}}] }); const stateKey = () => `plotdirector.context.v1.${root.dataset.user}.${windowId}`; let state; try { state=JSON.parse(read(localStorage,stateKey())); } catch { } if (state?.version !== 1 || !Array.isArray(state.panes) || state.panes.length !== 2) state=defaults(); if (!['single','columns','rows'].includes(state.layout)) state.layout='single'; state.ratio = Number.isFinite(state.ratio) ? Math.max(.2,Math.min(.8,state.ratio)) : .5; state.panes=state.panes.map((pane,i)=>({tab:registry.has(pane?.tab)?pane.tab:defaults().panes[i].tab,views:pane?.views && typeof pane.views==='object'?pane.views:{}})); let selectedDocument = root.dataset.wordInstance && root.dataset.wordSession ? `${root.dataset.wordInstance}/${root.dataset.wordSession}` : state.selectedDocument || ''; let nativeKey = '', unavailable = false; const save = () => { state.selectedDocument=selectedDocument; write(sessionStorage,'plotdirector.context.window.v1',windowId); write(localStorage,stateKey(),JSON.stringify(state)); }; const panes = [...root.querySelectorAll('[data-context-pane]')].map((element,index)=>({ element,index,select:element.querySelector('[data-context-tab]'),host:element.querySelector('[data-context-pane-content]'),status:element.querySelector('[data-context-pane-status]'),records:new Map(),revision:0 })); const current = pane => pane.records.get(state.panes[pane.index].tab); const visible = pane => pane.index===0 || state.layout!=='single'; const guarded = record => record && (record.dirty || record.busy || lifecycles[record.tab.lifecycle]?.canRefresh?.(record.node,record)===false); function remember(pane) { const record=pane.host.contextRecord; if(!record)return; record.scroll={top:pane.host.scrollTop,left:pane.host.scrollLeft}; state.panes[pane.index].views[record.tab.id]=record.scroll; } function dispose(record) { if(record?.mounted){lifecycles[record.tab.lifecycle]?.dispose?.(record.node);record.mounted=false;} } function mount(pane,record) { if(record.node.parentNode!==pane.host){dispose(pane.host.contextRecord);pane.host.replaceChildren(record.node);pane.host.contextRecord=record;} if(!record.mounted){lifecycles[record.tab.lifecycle]?.mount?.(record.node,{paneId:pane.index,windowId,position:{...position}});record.mounted=true;} const scroll=record.scroll||state.panes[pane.index].views[record.tab.id]; if(scroll){pane.host.scrollTop=Number(scroll.top)||0;pane.host.scrollLeft=Number(scroll.left)||0;} } function cancelRequests() { for(const item of requests.values())item.controller.abort();requests.clear(); } function fragment(html) { const doc=new DOMParser().parseFromString(html,'text/html'); if(/]|]|]/i.test(html)||doc.body.children.length!==1||!doc.body.firstElementChild.matches('[data-context-tab-fragment]')) throw Error('Invalid reference response. Sign in again if your session expired.'); return doc.body.firstElementChild; } async function fetchTab(tab) { const url=new URL(tab.endpoint,location.origin); for(const field of fields)if(position[field]!=null)url.searchParams.set(field,position[field]); if(position.instanceId&&position.sessionId&&!pinned){url.searchParams.set('instanceId',position.instanceId);url.searchParams.set('sessionId',position.sessionId);} const key=`${generation}:${url.href}`; if(!requests.has(key)){ const controller=new AbortController(); const timer=setTimeout(()=>controller.abort(),20000); const promise=fetch(url,{signal:controller.signal,cache:'no-store',credentials:'same-origin',headers:{'X-Requested-With':'XMLHttpRequest'}}).then(async response=>{ if(response.redirected||response.status===401||response.status===403)throw Error('Sign in again with access to this book.'); if(response.status===409)throw Error('Word mapping changed or is awaiting verification. Saved information remains available.'); if(!response.ok)throw Error('Saved reference unavailable. Check book access and choose a saved scene, or retry.'); return await response.text(); }).finally(()=>{clearTimeout(timer);if(requests.get(key)?.controller===controller)requests.delete(key);}); requests.set(key,{controller,promise}); } return requests.get(key).promise; } async function refreshPane(pane) { if(!visible(pane))return; const tab=registry.get(state.panes[pane.index].tab); let record=pane.records.get(tab.id); if(!record){record={tab,stale:true,node:null,dirty:false,busy:false};pane.records.set(tab.id,record);} if(guarded(record)){pane.status.textContent='Updates available · this panel is still editing or busy at its previous position.';return;} if(!record.stale&&record.node){mount(pane,record);pane.status.textContent='';return;} const level=scopes.indexOf(tab.scope); if(level>=3&&!position.sceneId){ dispose(pane.host.contextRecord);pane.host.contextRecord=null;pane.host.replaceChildren(); pane.host.removeAttribute('aria-busy');pane.status.textContent='No verified current scene. Choose a saved scene to browse.';return; } const request=++pane.revision, epoch=generation; pane.status.textContent=record.node?'Updating saved information…':'Loading saved information…';pane.host.setAttribute('aria-busy','true'); try { const html=await fetchTab(tab); if(stopped||epoch!==generation||request!==pane.revision||state.panes[pane.index].tab!==tab.id||!visible(pane))return; if(guarded(record)){pane.status.textContent='Updates available · refresh deferred while editing or busy.';return;} const node=fragment(html); if(position.sceneId&&Number(node.dataset.sceneId)!==position.sceneId)throw Error('Reference position changed. Refresh saved data to retry.'); const focused=pane.host.contains(document.activeElement)?document.activeElement:null; const focusHref=focused?.closest('a')?.getAttribute('href'); remember(pane);dispose(record);record.node=node;record.stale=false;record.position={...position}; mount(pane,record); if(focusHref&&document.hasFocus())[...pane.host.querySelectorAll('a')].find(link=>link.getAttribute('href')===focusHref)?.focus({preventScroll:true}); pane.status.textContent=unavailable?'Saved reference · live Word position unavailable.':''; } catch(error) { if(epoch!==generation||request!==pane.revision||stopped)return; pane.status.textContent=error.name==='AbortError'?'Reference request interrupted. Use Refresh saved data to retry.':error.message; if(record.node)mount(pane,record); } finally { if(request===pane.revision)pane.host.removeAttribute('aria-busy'); } } const scopeChanged = (tab,before,after) => { const level=scopes.indexOf(tab.scope); if(level<=0)return false; const count=level===1?2:level===2?3:level===3?4:5; return fields.slice(0,count).some(field=>before[field]!==after[field]); }; function invalidate(hint={}) { if(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId)return; generation++;cancelRequests(); for(const pane of panes){for(const record of pane.records.values()){ if(record.tab.contentRefresh==='none')continue; // Scene projections can depend on established earlier records: book-level is conservative. record.stale=true; }void refreshPane(pane);} } function setPosition(next,force=false) { if((scope.bookId&&number(next.bookId)!==scope.bookId)||(scope.projectId&&number(next.projectId)&&number(next.projectId)!==scope.projectId))return; const normalized={...scope,...next,bookId:number(next.bookId)||scope.bookId,chapterId:number(next.chapterId),sceneId:number(next.sceneId),paragraphId:next.paragraphId||null}; const before=position; if(!force&&JSON.stringify(before)===JSON.stringify(normalized))return; position=normalized;generation++;cancelRequests(); sceneSelect.value=position.sceneId||''; root.querySelector('[data-context-editor]').href=position.sceneId?`/Scenes/Edit/${position.sceneId}`:'/Writer'; for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');for(const record of pane.records.values())if(force||scopeChanged(record.tab,before,position))record.stale=true;void refreshPane(pane);} } async function recoverOffice(force=false) { if(pinned||selectedDocument||nativeLeases.some(l=>l.wordAvailable&&(!scope.bookId||Number(l.bookId)===scope.bookId)))return; if(recoveryPending){recoveryAgain ||= force;return;} recoveryPending=true;const epoch=recoveryGeneration; try { const url=new URL('/Writing/Context/Position',location.origin);for(const [key,value]of Object.entries(scope))if(value)url.searchParams.set(key,value); const response=await fetch(url,{cache:'no-store',signal:AbortSignal.timeout(8000),headers:{'X-Requested-With':'XMLHttpRequest'}}); if(!response.ok||response.redirected)throw Error();const packet=await response.json(); if(epoch!==recoveryGeneration||selectedDocument||nativeLeases.some(l=>l.wordAvailable&&(!scope.bookId||Number(l.bookId)===scope.bookId)))return; const office=packet.position; window.PlotDirector?.wordNotifications?.connection('office',packet.connected); const indicator=document.querySelector('[data-word-companion-presence]');if(indicator)indicator.dataset.officeConnected=String(packet.connected); if(packet.connected&&office){unavailable=false;status.textContent='Following Word · saved reference data';setPosition(office,force);} else {unavailable=true;status.textContent='Word disconnected · saved scene browsing remains available';if(force)invalidate();} } catch {if(epoch===recoveryGeneration){unavailable=true;status.textContent='Word status unavailable · saved reference remains available';if(force)invalidate();}} finally {recoveryPending=false;if(recoveryAgain){recoveryAgain=false;void recoverOffice(true);}} } function followNative(leases,force=false) { nativeLeases=leases.filter(l=>Date.parse(l.expires)>Date.now());recoveryGeneration++; const available=nativeLeases.filter(l=>l.wordAvailable&&(!scope.bookId||Number(l.bookId)===scope.bookId)); const active=available.filter(l=>l.active); const chosen=selectedDocument?available.filter(l=>`${l.instanceId}/${l.sessionId}`===selectedDocument):active.length===1?active:available; const lease=chosen.length===1?chosen[0]:null; if(!lease){ if(selectedDocument||available.length){unavailable=true;nativeKey='';status.textContent=available.length>1&&!selectedDocument?'Choose a Word document using the connection indicator':'Selected Word document disconnected · saved reference remains available';generation++;cancelRequests();for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');if(current(pane))current(pane).stale=true;pane.status.textContent='Live position unavailable · displayed reference may be stale.';}return;} nativeKey='';void recoverOffice(force);return; } if(lease.wordSaved!==true||lease.positionVerified===false||!lease.sceneId){ unavailable=true;nativeKey='';generation++;cancelRequests();for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');if(current(pane))current(pane).stale=true;pane.status.textContent='Displayed reference is saved data · current Word scene is unavailable.';} status.textContent=lease.positionMessage||'Save Word and verify its scene mapping · saved reference remains available';return; } unavailable=false; const key=[lease.instanceId,lease.sessionId,lease.manuscriptId,lease.revision,lease.snapshotRevision,lease.chapterId,lease.sceneId].join(':'); const changed=nativeKey!==key;nativeKey=key; status.textContent='Following Word · saved reference data'; // Observed revision alone is not accepted content. It only causes position verification. setPosition({ ...scope,bookId:Number(lease.bookId),chapterId:Number(lease.chapterId),sceneId:Number(lease.sceneId),instanceId:lease.instanceId,sessionId:lease.sessionId },force||leases.reconnected); if(changed&&lease.mappingCurrent)invalidate({bookId:lease.bookId}); } function applyLayout() { grid.dataset.layout=state.layout;layoutSelect.value=state.layout; panes[1].element.hidden=state.layout==='single';divider.hidden=state.layout==='single'; divider.setAttribute('aria-orientation',state.layout==='rows'?'horizontal':'vertical'); const size=state.layout==='rows'?grid.clientHeight:grid.clientWidth; const minimum=state.layout==='rows'?120:220; const edge=Math.min(.45,minimum/Math.max(size-12,1)); const ratio=Math.max(edge,Math.min(1-edge,state.ratio)); grid.style.setProperty('--context-first',`calc((100% - .75rem) * ${ratio})`); divider.setAttribute('aria-valuenow',String(Math.round(ratio*100))); divider.setAttribute('aria-valuemin',String(Math.round(edge*100)));divider.setAttribute('aria-valuemax',String(Math.round((1-edge)*100))); for(const pane of panes){pane.select.value=state.panes[pane.index].tab;if(visible(pane))void refreshPane(pane);else{pane.revision++;dispose(current(pane));}} save(); } function resize(ratio) { state.ratio=Math.max(.2,Math.min(.8,ratio));applyLayout(); } let dragging=false; divider.addEventListener('pointerdown',event=>{if(event.button!==0)return;dragging=true;divider.setPointerCapture(event.pointerId);event.preventDefault();}); divider.addEventListener('pointermove',event=>{if(!dragging)return;const box=grid.getBoundingClientRect();resize(state.layout==='rows'?(event.clientY-box.top)/box.height:(event.clientX-box.left)/box.width);}); for(const type of ['pointerup','pointercancel','lostpointercapture'])divider.addEventListener(type,()=>dragging=false); divider.addEventListener('keydown',event=>{const keys=state.layout==='rows'?['ArrowUp','ArrowDown']:['ArrowLeft','ArrowRight'];if(![...keys,'Home','End'].includes(event.key))return;event.preventDefault();resize(event.key==='Home'?.2:event.key==='End'?.8:state.ratio+(event.key===keys[0]?-.05:.05));}); layoutSelect.addEventListener('change',()=>{panes.forEach(remember);state.layout=layoutSelect.value;applyLayout();}); for(const pane of panes){ pane.select.value=state.panes[pane.index].tab; pane.select.addEventListener('change',()=>{ if(guarded(current(pane))){pane.select.value=state.panes[pane.index].tab;pane.status.textContent='Finish or cancel editing before changing tools.';return;} remember(pane);dispose(current(pane));pane.revision++;state.panes[pane.index].tab=pane.select.value;save();void refreshPane(pane); }); pane.host.addEventListener('scroll',()=>{remember(pane);save();},{passive:true}); pane.element.addEventListener('context-panel-state',event=>{ const record=current(pane);if(!record)return;record.dirty=!!event.detail?.dirty;record.busy=!!event.detail?.busy;if(!guarded(record)&&record.stale)void refreshPane(pane); }); } async function navigate(sceneId,sendWord=false) { const id=number(sceneId);if(!id)return; const manual=++manualGeneration;navigationRequest?.abort(); setPosition({...scope,chapterId:null,sceneId:id},true);status.textContent=pinned?'Saved PlotDirector snapshot · manual selection':'Saved scene selected'; if(!sendWord||pinned||!scope.bookId)return; navigationRequest=new AbortController(); const token=document.querySelector('[data-word-sync-form] [name=__RequestVerificationToken]')?.value; const body=new URLSearchParams({bookId:scope.bookId,sceneId:id,navigationId:uuid(),__RequestVerificationToken:token||''}); if(selectedDocument){const [instanceId,sessionId]=selectedDocument.split('/');body.set('instanceId',instanceId);body.set('sessionId',sessionId);} try{const response=await fetch('/Writing/Context/Navigate',{method:'POST',body,signal:navigationRequest.signal,headers:{'X-Requested-With':'XMLHttpRequest'}});const packet=await response.json();if(manual===manualGeneration)status.textContent=packet.message||'Saved scene selected';}catch(error){if(error.name!=='AbortError'&&manual===manualGeneration)status.textContent='Saved scene selected · Word navigation unavailable';} } sceneSelect.addEventListener('change',event=>void navigate(sceneSelect.value,event.isTrusted)); for(const [selector,step]of [['[data-context-previous]',-1],['[data-context-next]',1]])root.querySelector(selector).addEventListener('click',event=>{const at=[...sceneSelect.options].findIndex(o=>Number(o.value)===position.sceneId);const next=sceneSelect.options[at+step];if(next?.value)void navigate(next.value,event.isTrusted);}); root.querySelector('[data-context-new]').addEventListener('click',()=>window.PlotDirectorWritingWorkspace.openContext({...position,pinned})); root.querySelector('[data-context-refresh]').addEventListener('click',()=>invalidate()); window.addEventListener('native-companion-presence',event=>{if(!pinned)followNative(event.detail||[],!!event.detail?.reconnected);}); window.addEventListener('plotdirector:word-document-selected',event=>{if(pinned)return;selectedDocument=event.detail||'';nativeKey='';save();followNative(nativeLeases,true);}); window.addEventListener('plotdirector:word-return-to-current',()=>{if(!pinned){nativeKey='';followNative(nativeLeases,true);}}); function wakeStatus(reconnected=false){window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status',{detail:{reconnected}}));} async function startConnection(){ if(stopped||connectionStarting||!connection||connection.state&&connection.state!=='Disconnected')return; connectionStarting=true; try{await connection.start();wakeStatus(true);void recoverOffice(true);}catch{status.textContent='Context notifications disconnected · retrying; saved browsing remains available';}finally{connectionStarting=false;} } if(!pinned&&window.signalR){ connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build(); connection.on('NativePresenceChanged',hint=>{window.dispatchEvent(new CustomEvent('plotdirector:native-presence-changed',{detail:hint}));wakeStatus();}); connection.on('ContextPositionChanged',()=>void recoverOffice()); connection.on('ContextInvalidated',hint=>{invalidate(hint);wakeStatus();}); connection.onreconnecting(()=>status.textContent='Context notifications reconnecting · saved reference may be stale'); connection.onreconnected(()=>{wakeStatus(true);void recoverOffice(true);invalidate();}); connection.onclose(()=>status.textContent='Context notifications disconnected · saved browsing remains available'); void startConnection(); } const timer=pinned?null:setInterval(()=>{void startConnection();void recoverOffice();},15000); document.addEventListener('visibilitychange',()=>{if(!document.hidden&&!pinned){void startConnection();wakeStatus(true);void recoverOffice(true);}}); window.addEventListener('pageshow',event=>{if(event.persisted)location.reload();}); // Duplicated browser tabs clone both URL and session storage. The live owner answers claims. const pageToken=uuid();let channel; if(window.BroadcastChannel){channel=new BroadcastChannel(`plotdirector.context.identity.${root.dataset.user}`);channel.onmessage=event=>{ const message=event.data;if(message.id!==windowId||message.token===pageToken)return; if(message.kind==='claim')channel.postMessage({kind:'occupied',id:windowId,token:pageToken,target:message.token}); if(message.kind==='occupied'&&message.target===pageToken){windowId=uuid();panes.forEach(pane=>{dispose(current(pane));pane.revision++;pane.records.clear();pane.host.replaceChildren();});state=defaults();selectedDocument=root.dataset.wordInstance&&root.dataset.wordSession?`${root.dataset.wordInstance}/${root.dataset.wordSession}`:'';save();const url=new URL(location.href);url.searchParams.set('contextWindow',windowId);history.replaceState(null,'',url);applyLayout();} };channel.postMessage({kind:'claim',id:windowId,token:pageToken});} const observer=new ResizeObserver(()=>applyLayout());observer.observe(grid); root.contextController={ get windowId(){return windowId;}, get position(){return {...position};}, invalidate,setPosition,registerLifecycle:(name,hooks)=>lifecycles[name]=hooks }; window.addEventListener('pagehide',()=>{stopped=true;panes.forEach(pane=>{remember(pane);dispose(current(pane));});save();cancelRequests();navigationRequest?.abort();clearInterval(timer);observer.disconnect();channel?.close();void connection?.stop();}); save();applyLayout(); if(pinned)status.textContent='Saved PlotDirector snapshot · manual selection · live follow disabled'; })();