(() => { '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 announce=()=>root.dispatchEvent(new Event("context-capabilities-changed")); 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; let windowBusy=false; root.addEventListener("context-window-state",event=>{windowBusy=!!event.detail?.busy;announce();}); const requests = new Map(); const lifecycles = { reference: { mount() {}, dispose() {} }, ...(window.PlotDirectorContextLifecycles || {}) }; const read = (name,key) => { try { return window[name].getItem(key); } catch { return null; } }; const write = (name,key,value) => { try { window[name].setItem(key,value); return true; } catch { return false; } }; 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 { } const restoredState=state?.version===1&&Array.isArray(state.panes)&&state.panes.length===2; if (!restoredState) 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 = restoredState ? (typeof state.selectedDocument==='string'?state.selectedDocument:'') : root.dataset.wordInstance && root.dataset.wordSession ? `${root.dataset.wordInstance}/${root.dataset.wordSession}` : ''; function presentSelectedDocument() { const [instance,session]=selectedDocument.split('/');root.dataset.wordInstance=instance||'';root.dataset.wordSession=session||''; } presentSelectedDocument(); 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); const level=scopes.indexOf(tab.scope),count=level<=0?0:level+1; if(fields.slice(0,count).some(field=>position[field]!=null&&String(node.dataset[field])!==String(position[field])))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.':'';announce(); } 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.projectId&&scope.projectId&&Number(hint.projectId)!==scope.projectId)return; 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; if(hint.kind==='relationships'&&!['overview','characters','relationships'].includes(record.tab.id))continue; if(hint.kind==='characters'&&!['overview','characters','relationships','names'].includes(record.tab.id))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]').dataset.contextEntity=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);} announce(); } async function recoverOffice(){if(window.PlotDirectorSharedFocus)await window.PlotDirectorSharedFocus.refresh();} function followNative(leases){const changed=leases.some(l=>Number(l.bookId)===scope.bookId&&l.snapshotRevision&&nativeLeases.find(old=>old.instanceId===l.instanceId&&old.sessionId===l.sessionId)?.snapshotRevision!==l.snapshotRevision);nativeLeases=leases.filter(l=>Date.parse(l.expires)>Date.now());if(changed||leases.reconnected){invalidate({bookId:scope.bookId});void refreshStructure();void window.PlotDirectorSharedFocus?.validateLocal();}} async function refreshStructure(){try{const response=await fetch(`/NarrativeFocus/Read?projectId=${scope.projectId}&bookId=${scope.bookId}`,{cache:'no-store'});if(!response.ok||response.redirected)return;const data=await response.json(),id=position.sceneId,options=[new Option('Choose a saved scene',''),...data.positions.filter(p=>p.sceneID).map(p=>new Option(p.label,String(p.sceneID)))];if(id&&!options.some(o=>Number(o.value)===id)){const missing=new Option('Reference unavailable · choose another scene',String(id));missing.disabled=true;options.push(missing);}sceneSelect.replaceChildren(...options);sceneSelect.value=id||'';}catch{/* Saved reference remains visible. */}} 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();announce(); } 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);announce(); }); 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&&!event.detail?.deferRefresh)void refreshPane(pane);announce(); }); } async function navigate(sceneId){const id=number(sceneId);if(!id)return;if(windowBusy||panes.some(p=>guarded(current(p)))){status.textContent='Save or cancel the current editor before changing manuscript position.';return;}if(!window.PlotDirectorSharedFocus){status.textContent='Focus is initialising; retry this selection.';return;}const moved=await window.PlotDirectorSharedFocus.navigate({projectID:scope.projectId,bookID:scope.bookId,sceneID:id});if(!moved)sceneSelect.value=position.sceneId||'';} function sharedPosition(event){const p=event.detail.position;setPosition({projectId:p.projectID,bookId:p.bookID,chapterId:p.chapterID,sceneId:p.sceneID,paragraphId:p.paragraphID});status.textContent=window.PlotDirectorSharedFocus?.held?'Held at local manuscript position · saved data remains live':'Following shared manuscript focus · saved reference data';} window.addEventListener('plotdirector:shared-focus',sharedPosition); root.querySelector('[data-context-go-focus]')?.addEventListener('click',()=>void window.PlotDirectorSharedFocus?.go()); 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',()=>{const choices=[...sceneSelect.options].filter(o=>number(o.value)),at=choices.findIndex(o=>Number(o.value)===position.sceneId),next=at<0?(step>0?choices[0]:choices.at(-1)):choices[at+step];if(next)void navigate(next.value);}); 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=>{followNative(event.detail||[]);}); window.addEventListener('plotdirector:word-document-selected',event=>{selectedDocument=event.detail||'';presentSelectedDocument();const url=new URL(location.href);if(selectedDocument){url.searchParams.set('instanceId',root.dataset.wordInstance);url.searchParams.set('sessionId',root.dataset.wordSession);}else{url.searchParams.delete('instanceId');url.searchParams.delete('sessionId');}history.replaceState(null,'',url);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);root.dispatchEvent(new Event('context-connection-ready'));}catch{status.textContent='Context notifications disconnected · retrying; saved browsing remains available';}finally{connectionStarting=false;} } if(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);if(hint.kind==='structure')void refreshStructure();wakeStatus();}); connection.onreconnecting(()=>status.textContent='Context notifications reconnecting · saved reference may be stale'); connection.onreconnected(()=>{wakeStatus(true);void recoverOffice(true);invalidate();root.dispatchEvent(new Event('context-connection-ready'));}); connection.onclose(()=>status.textContent='Context notifications disconnected · saved browsing remains available'); void startConnection(); } const timer=setInterval(()=>{void startConnection();announce();},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; const identityChannel=`plotdirector.context.identity.${root.dataset.user}`; try { if(window.BroadcastChannel)channel=new BroadcastChannel(identityChannel); } catch { } if(!channel){ // Storage events also reach cloned tabs when BroadcastChannel is unavailable. const key=identityChannel+'.claim'; if(write('localStorage',key,JSON.stringify({kind:'probe',token:pageToken}))){ const receive=event=>{if(event.key===key&&event.newValue){try{channel?.onmessage?.({data:JSON.parse(event.newValue)});}catch{}}}; channel={postMessage:message=>write('localStorage',key,JSON.stringify({...message,nonce:uuid()})),close:()=>window.removeEventListener('storage',receive)}; window.addEventListener('storage',receive); } } if(channel){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,get connection(){return connection;},get announcement(){return {version:1,bookID:position.bookId,windowID:windowId,panes:panes.filter(visible).map(pane=>({paneID:String(pane.index),toolID:state.panes[pane.index].tab,actions:registry.get(state.panes[pane.index].tab).actions||[],available:!windowBusy&&!!current(pane)?.node&&!current(pane).stale&&!guarded(current(pane))}))};},receiveInteraction:async delivery=>{if(windowBusy)return 'busy';const pane=panes.find(p=>String(p.index)===delivery.paneID);if(!pane||!visible(pane))return 'not-visible';const record=current(pane);if(guarded(record))return 'busy';if(!record?.node||record.stale)return 'unavailable';record.stale=true;await refreshPane(pane);if(record.stale||guarded(record))return 'unavailable';return await lifecycles[record.tab.lifecycle]?.onInteraction?.(record.node,delivery.command,{position:{...position},pane})||'not-visible';},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(); status.textContent='Shared manuscript focus initialising · local saved data remains available'; })();