/* Spatial inspection is window-local. Persisted edits exclusively use authorised canonical services. */ (() => { 'use strict'; const instances=new WeakMap(),requests=new Map(),sessions=new WeakMap(),mime='application/x-plotdirector-spatial-location'; const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!=null)n.textContent=text;if(cls)n.className=cls;return n;}; const btn=(text,fn)=>{const b=el('button',text);b.type='button';b.onclick=()=>Promise.resolve().then(fn).catch(error=>window.PlotDirector?.toast?.error(error.message));return b;}; const same=(a,b)=>a?.bookId===b?.bookId&&a?.sceneId===b?.sceneId; const id=l=>l?.locationID; let invalidating=false; function invalidateCache(){if(!invalidating){invalidating=true;requests.clear();queueMicrotask(()=>invalidating=false);}} function state(position,location,refresh=false){const url=`/SpatialContext/State?bookId=${position.bookId}&sceneId=${position.sceneId}${location?`&locationId=${location}`:''}`;if(refresh)requests.delete(url);if(requests.size>40)requests.delete(requests.keys().next().value);if(!requests.has(url)){const promise=fetch(url,{cache:'no-store'}).then(async r=>{if(!r.ok||r.redirected)throw Error('Spatial context is unavailable. Check book access and refresh.');const result=await r.json();if(requests.get(url)===promise&&!location&&result.scope.primaryLocationID)requests.set(`${url}&locationId=${result.scope.primaryLocationID}`,Promise.resolve(result));return result;}).catch(e=>{if(requests.get(url)===promise)requests.delete(url);throw e;});requests.set(url,promise);}return requests.get(url);} function session(root){if(!sessions.has(root))sessions.set(root,{location:null,scene:null,listeners:new Set(),revision:0,select(location,source,force=false){if(!force&&this.location===location)return;this.location=location;this.revision++;for(const fn of this.listeners)fn({version:1,location,source,revision:this.revision,windowId:root.contextController?.windowId,projectId:Number(root.dataset.scopeProjectId),bookId:Number(root.dataset.scopeBookId)});}});return sessions.get(root);} function ancestors(data,location){const result=[],seen=new Set();while(location&&!seen.has(location)){seen.add(location);const r=data.locations.find(l=>id(l)===location);if(!r)break;result.push(r);location=r.parentLocationID;}return result;} function path(data,location){return ancestors(data,location).reverse().map(l=>l.locationName).join(' / ');} function resolution(data,location,kind){const links=kind==='maps'?data.maps:data.plans;for(const [depth,l]of ancestors(data,location).entries()){const found=links.filter(x=>x.locationID===id(l)&&(kind!=='maps'||x.isPlaced));if(found.length)return found.map(link=>({...link,depth,represented:id(l)})).sort((a,b)=>Number(!!b.blockID)-Number(!!a.blockID)||Number(!!b.floorID)-Number(!!a.floorID));}return [];} function icon(data,location){const t=data.types.find(t=>t.assignable!==false&&String(t.value)===String(location?.locationTypeID??''));const n=el('span',null,`spatial-type text-${t?.tone||'secondary'}`);if(t?.path){const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('aria-hidden','true');const p=document.createElementNS(svg.namespaceURI,'path');p.setAttribute('d',t.path);p.setAttribute('fill',t.filled?'currentColor':'none');svg.append(p);n.append(svg);}n.title=t?.label||'Unclassified';return n;} function mount(node,context){if(instances.has(node))return;const root=node.closest('[data-context-workspace]'),bus=session(root),kind=node.dataset.spatialContext,abort=new AbortController();let position=context.position,data,selection,loadedInspection,epoch=0,disposed=false,busy=false,resource=null,renderer=null,floorSnapshot=null,floorRoom=null,visibility=false,audibility=false,operation=null,undo=null; const q=s=>node.querySelector(s),status=q('[data-spatial-status]'),error=q('[data-spatial-error]'),canvas=q('[data-spatial-canvas]'); const pref=`plotdirector.spatial.v1.${root.dataset.user}.${context.windowId}.${position.projectId}.${kind}`;let preferences={};try{preferences=JSON.parse(localStorage.getItem(pref))||{};}catch{} const save=()=>{try{localStorage.setItem(pref,JSON.stringify(preferences));}catch{}}; const guard=(value,deferRefresh=false)=>{busy=value;node.dispatchEvent(new CustomEvent('context-panel-state',{bubbles:true,detail:{dirty:value,busy:false,deferRefresh}}));}; const fail=e=>{if(!disposed){error.textContent=e.message;if(data)q('[data-spatial-return]').disabled=false;}}; async function post(route,body){const r=await fetch(route,{method:'POST',headers:{'Content-Type':'application/json','RequestVerificationToken':q('[name="__RequestVerificationToken"]').value},body:JSON.stringify(body)});const result=await r.json();if(!r.ok)throw Error(result.message||'The change could not be saved. Existing work is unchanged.');return result;} async function reload(refresh=false){const current=++epoch,p={...position},location=bus.location;try{status.textContent='Loading spatial context…';const result=await state(p,location,refresh);if(disposed||current!==epoch||!same(position,p))return;data=result;loadedInspection=location??result.scope.primaryLocationID;if(bus.scene!==`${p.bookId}/${p.sceneId}`){bus.scene=`${p.bookId}/${p.sceneId}`;bus.select(data.scope.primaryLocationID,context.paneId);}selection=bus.location;status.textContent='';draw();}catch(e){if(current===epoch)fail(e);}} async function select(location){bus.select(location,context.paneId);if(selection===location)return;selection=location;if(data?.locations.some(l=>id(l)===location)&&loadedInspection===location)draw();else await reload();} const listener=message=>{if(disposed||busy||message.source===context.paneId)return;selection=message.location;if(data?.locations.some(l=>id(l)===selection)&&loadedInspection===selection)draw();else void reload();};bus.listeners.add(listener); async function finish(result,route='/SpatialContext/Undo',inspection){if(result.assignment){if(result.assignment.result?.kind==='scene')inspection=result.id;result=result.assignment;}undo=result.undoToken?{token:result.undoToken,route}:null;q('[data-spatial-undo]').hidden=!undo;window.PlotDirector?.toast?.success('Spatial information saved.');guard(false,true);if(inspection!==undefined&&root.contextController.position.sceneId===position.sceneId){bus.location=inspection;bus.revision++;}root.contextController.invalidate({projectId:position.projectId,bookId:position.bookId,kind:result.result?.kind==='map'?'maps':['room','plan'].includes(result.result?.kind)?'floorplans':'locations'});} q('[data-spatial-undo]').onclick=async()=>{try{const saved=undo;if(!saved)return;if(busy)throw Error('Finish or cancel the current operation before Undo.');const result=await post(saved.route,{token:saved.token});undo=null;q('[data-spatial-undo]').hidden=true;root.contextController.invalidate({kind:result.result?.kind==='map'?'maps':['room','plan'].includes(result.result?.kind)?'floorplans':'locations',projectId:position.projectId,bookId:position.bookId});}catch(e){fail(e);}}; function clearOperation(){operation=null;q('[data-spatial-operation]').replaceChildren();q('[data-spatial-operation]').hidden=true;renderer?.command?.('placement',{active:false});guard(false);} async function form(title,build,commit){if(busy)throw Error('Finish or cancel the current operation first.');const panel=q('[data-spatial-operation]');panel.hidden=false;panel.replaceChildren(el('strong',title));guard(true);const controls=await build(panel);panel.append(btn('Save',async()=>{try{const result=await commit(controls);clearOperation();await finish(result,result.attribute?'/LocationWorkspace/Undo':'/SpatialContext/Undo');}catch(e){fail(e);}}),btn('Cancel',clearOperation));controls?.focus?.();} async function picker(title,selected,allowRoot=false){const content=el('div'),dialog=el('dialog',null,'pd-location-picker-dialog');dialog.append(el('h2',title),content);document.body.append(dialog);const wasBusy=busy;guard(true);try{const result=await window.PlotDirectorLocationPicker.data(position.projectId);const picker=window.PlotDirectorLocationPicker.mount(content,{...result,selected: selected==null?undefined:String(selected),allowRoot,rootLabel:allowRoot?'No assigned location':undefined});return await new Promise(resolve=>{let value;dialog.append(btn('Choose',()=>{if(picker.value===undefined)return;value=picker.value===''?null:Number(picker.value);dialog.close();}),btn('Cancel',()=>dialog.close()));dialog.addEventListener('close',()=>resolve(value),{once:true});dialog.showModal();picker.focus();});}finally{dialog.remove();guard(wasBusy);}} function payload(location=selection){return {version:1,windowId:context.windowId,projectId:position.projectId,bookId:position.bookId,locationId:location};} function validDrop(p){return p?.version===1&&p.windowId===context.windowId&&p.projectId===position.projectId&&p.bookId===position.bookId&&Number.isSafeInteger(p.locationId);} function draggable(n,location){if(!location)return;n.draggable=true;n.addEventListener('dragstart',e=>{e.dataTransfer.setData(mime,JSON.stringify(payload(location)));e.dataTransfer.effectAllowed='copy';});} function scenes(){const host=q('[data-spatial-scenes]');host.replaceChildren();for(const index of [-1,0,1]){const scene=data.scenes.find(s=>s.position===index),label=['Previous','Current','Next'][index+1],row=el('div',null,`spatial-scene spatial-position-${index+1}`);row.dataset.scenePosition=index;row.append(el('strong',`${label} scene`));if(!scene){row.append(el('small',index<0?'Start of manuscript':'End of manuscript'));host.append(row);continue;}const location=data.locations.find(l=>id(l)===scene.locationID);row.title=scene.label;const pick=btn(location?.locationName||(scene.locationID?'Assigned location unavailable':'No location assigned'),()=>select(scene.locationID));if(location)pick.prepend(icon(data,location));pick.classList.toggle('active',selection===scene.locationID&&!!selection);row.append(pick,el('small',scene.label));if(location){row.append(el('small',path(data,id(location))));const repeated=data.scenes.some(s=>s.positiona.sceneID===scene.sceneID&&a.kind!=='Scene location');if(recorded.length){const extra=el('details');extra.append(el('summary','Other recorded positions'));for(const a of recorded){const r=data.locations.find(l=>id(l)===a.locationID);if(r)extra.append(btn(`${r.locationName} · ${a.kind}`,()=>select(a.locationID)));}row.append(extra);}host.append(row);}} async function assign(location){const target={bookID:position.bookId,sceneID:data.scope.sceneID,kind:'scene',expected:data.scope.version,locationID:location};await finish(await post('/SpatialContext/Mutate',target),'/SpatialContext/Undo',location);} async function chooseAssignment(){const current=data.scope;const target={...position};const chosen=await picker(`Assign location to ${current.label}`,current.primaryLocationID,true);if(chosen===undefined)return;if(!same(position,target))throw Error('Scene changed. Choose the current scene location again.');await assign(chosen);} async function edit(attribute,location){const fixed={...location},name=fixed.locationName;await form(`${attribute==='description'?'Edit description':'Rename'}: ${name}`,panel=>{const input=el(attribute==='description'?'textarea':'input');input.value=attribute==='description'?(fixed.description||''):name;input.setAttribute('aria-label',attribute);if(attribute==='description')input.rows=9;panel.append(input);return input;},input=>post('/LocationWorkspace/Assign',{projectId:position.projectId,attribute,changes:[{id:id(fixed),value:input.value,version:fixed.updatedDate}]}));} async function discrete(attribute,location){const fixed={...location};let value;if(attribute==='type'){guard(true);try{value=await window.PlotDirectorLocationTypes.choose({taxonomy:data.types,selected:String(fixed.locationTypeID??'')});}finally{guard(false);}if(value===null)return;}else{await form(`Classification: ${fixed.locationName}`,panel=>{const input=el('select');for(const v of ['Unclassified','Real','Fictional','Fictionalised'])input.add(new Option(v,v==='Unclassified'?'':v));input.value=fixed.classification||'';panel.append(input);return input;},input=>post('/LocationWorkspace/Assign',{projectId:position.projectId,attribute,changes:[{id:id(fixed),value:input.value,version:fixed.updatedDate}]}));return;}await finish(await post('/LocationWorkspace/Assign',{projectId:position.projectId,attribute,changes:[{id:id(fixed),value,version:fixed.updatedDate}]}),'/LocationWorkspace/Undo');} async function createLocation(assignScene=false,parent=selection,block=null){const target={...position},scope={...data.scope},plan=resource;await form(assignScene?`Create location for ${scope.label}`:block?'Create and associate location':'Create child location',panel=>{const name=el('input');name.placeholder='Location name';name.setAttribute('aria-label','Location name');let parentId=parent;const parentLabel=el('small',parent?`Parent: ${path(data,parent)}`:'Parent: Root level');panel.append(name,parentLabel,btn('Choose parent',async()=>{const chosen=await picker('Review containing location',parentId,true);if(chosen!==undefined){parentId=chosen;parentLabel.textContent=chosen?`Parent location ${chosen}`:'Parent: Root level';}}));return {name,parent:()=>parentId};},controls=>post('/SpatialContext/Create',{bookID:target.bookId,sceneID:scope.sceneID,name:controls.name.value,parentID:controls.parent(),expected:assignScene?scope.version:block?.version,planID:block?plan:null,blockID:block?String(block.id):null,replace:!!block}));} async function showTool(tool){bus.select(selection,context.paneId,true);const visible=[...root.querySelectorAll('[data-context-pane]:not([hidden]) [data-context-tab]')].some(s=>s.value===tool);if(visible){root.contextController.openTool(tool,context.paneId,'other');return;}let opened=false;const dialog=el('dialog',null,'pd-location-picker-dialog');dialog.append(el('h2',`Show ${tool==='maps'?'map':'floor plan'}`),el('p','Choose where to open this spatial perspective.'));for(const [label,destination]of [['This pane','current'],['Other pane / create split','other']])dialog.append(btn(label,()=>{dialog.close();if(root.contextController.openTool(tool,context.paneId,destination))opened=true;else fail(Error('Finish or cancel editing in the destination pane first.'));}));dialog.append(btn('Cancel',()=>dialog.close()));dialog.onclose=()=>{if(!opened)bus.pendingPlacement=null;dialog.remove();};document.body.append(dialog);dialog.showModal();} function locationSummary(host){ const section=el('section');section.append(el('h3','Current scene locations')); const assigned=data.assignments.filter(a=>a.sceneID===data.scope.sceneID); if(!assigned.length)section.append(el('p','Unknown / unset: no scene location or recorded placements.')); for(const a of assigned){const name=path(data,a.locationID);section.append(name?btn(`${name} · ${a.kind}`,()=>select(a.locationID)):el('p',`Unavailable location · ${a.kind}`));} section.append(el('h3','Recorded scene characters')); if(!data.characters?.length)section.append(el('p','Unknown / unset: no scene characters recorded.')); for(const c of data.characters||[])section.append(el('p',`${c.characterName} · ${c.presenceTypeName||'Presence unknown / unset'} · ${c.locationPath||c.locationName||'Location unknown / unset'}`)); section.append(el('p','Character records describe saved scene participation; they do not establish precise positions or witness knowledge.','small muted'));host.append(section); } function sensoryDetails(host,location){ const section=el('section');section.append(el('h3','Visibility and audibility')); section.append(el('p','Saved direction is From → To: the From location can see or hear the To location when the corresponding flag is enabled. Potential sight or sound does not establish what a character witnessed. Reverse flags are not inferred, including from a travel “both ways” setting.','small muted')); for(const [label,outgoing,flags] of [['Can see',true,['canSeeMovement','canSeeClearly']],['Can be seen from',false,['canSeeMovement','canSeeClearly']],['Can hear',true,['canHearNormalSpeech','canHearLoudNoise']],['Can be heard from',false,['canHearNormalSpeech','canHearLoudNoise']]]){ section.append(el('h4',label));const rows=(data.sensoryRelationships||[]).filter(r=>outgoing?r.fromLocationID===id(location):r.toLocationID===id(location)); if(!rows.length)section.append(el('p','Unknown / unset: no relationship recorded in this direction.')); for(const r of rows){const other=outgoing?r.toLocationID:r.fromLocationID,name=outgoing?r.toLocationName:r.fromLocationName,line=el('div');const link=el('a',name);link.href=`/Locations/Details/${other}`;line.append(link,el('span',` · ${flags.map(f=>`${({canSeeMovement:'movement',canSeeClearly:'clear sight',canHearNormalSpeech:'normal speech',canHearLoudNoise:'loud noise'})[f]}: ${r[f]===true?'enabled':'unset / not enabled'}`).join(' · ')}`));if(r.notes)line.append(el('p',r.notes));section.append(line);} } section.append(el('p','Unset flags do not prove that seeing or hearing is impossible.','small muted'));host.append(section); } function details(){const host=q('[data-spatial-details]');host.replaceChildren();const current=data.scope,location=data.locations.find(l=>id(l)===selection);const actions=el('div',null,'spatial-toolbar');if(current.canEdit)actions.append(btn(`Change current scene location`,chooseAssignment),btn('New location for current scene',()=>createLocation(true,null)));host.append(actions);locationSummary(host);if(!location){sensoryDetails(host,location);host.append(el('p',selection?'The assigned or inspected location is unavailable. Choose an active location explicitly; the recorded assignment has not been changed.':'This scene has no assigned location. Inspect adjacent scenes or explicitly choose a location.'));if(current.canEdit){host.append(btn('Create new location for current scene',()=>createLocation(true,null)));for(const adjacent of data.scenes.filter(s=>s.position!==0&&s.locationID))host.append(btn(`Use ${adjacent.position<0?'previous':'next'} scene location`,()=>assign(adjacent.locationID)));}return;}const header=el('h2',location.locationName);header.prepend(icon(data,location));draggable(header,id(location));host.append(header,el('p',`${location.locationTypeName||'Unclassified'} · ${location.classification||'Unclassified'}`));const trail=el('nav',null,'spatial-path');trail.setAttribute('aria-label','Containing locations');for(const a of ancestors(data,id(location)).reverse())trail.append(btn(a.locationName,()=>select(id(a))));host.append(trail);const description=el('div',location.description||'No description recorded.','spatial-description');host.append(description);if(current.canEdit){const tools=el('div',null,'spatial-toolbar');tools.append(btn('Edit description',()=>edit('description',location)),btn('Rename',()=>edit('name',location)),btn('Type',()=>discrete('type',location)),btn('Classification',()=>discrete('classification',location)),btn('Create child',()=>createLocation(false,id(location))));host.append(tools);}const links=el('div',null,'spatial-toolbar');for(const [label,url]of [['Location Details',`/Locations/Details/${id(location)}`],['Edit Location',`/Locations/Edit/${id(location)}`]]){const a=el('a',label);a.href=url;links.append(a);}host.append(links);sensoryDetails(host,location);const children=data.locations.filter(l=>l.parentLocationID===id(location));if(children.length){const section=el('details');section.open=preferences.children!==false;section.append(el('summary',`Contained locations (${location.childCount})`));section.ontoggle=()=>{preferences.children=section.open;save();};for(const child of children)section.append(btn(child.locationName,()=>select(id(child))));if(location.childCount>children.length)section.append(el('small',`Showing ${children.length} immediate locations. Open Locations for the complete directory.`));host.append(section);}if(data.relationships.length){const section=el('details');section.append(el('summary','Recorded relationships'));for(const r of data.relationships)section.append(el('p',`${r.fromName} · ${r.typeName} · ${r.toName}${r.notes?' — '+r.notes:''}`));host.append(section);}const spatial=el('div',null,'spatial-toolbar');for(const tool of ['maps','floorplans']){const found=resolution(data,id(location),tool);spatial.append(btn(`Show ${tool==='maps'?'map':'floor plan'}${found.some(f=>f.depth)?' (containing location)':''}`,()=>showTool(tool)));if(tool==='maps'&¤t.canEdit&&!found.some(f=>f.depth===0)){const link=el('a','Place in Maps');link.href=`/Maps?projectId=${position.projectId}`;spatial.append(link);}}host.append(spatial);} function catalog(){return kind==='maps'?data.mapCatalog:data.planCatalog;} function relevant(){const found=resolution(data,selection,kind);if(found.length)return found.sort((a,b)=>data.scenes.filter(s=>resolution(data,s.locationID,kind).some(l=>l.resourceID===b.resourceID)).length-data.scenes.filter(s=>resolution(data,s.locationID,kind).some(l=>l.resourceID===a.resourceID)).length||a.name.localeCompare(b.name));return data.scenes.flatMap(s=>resolution(data,s.locationID,kind));} function draw(){if(!data||disposed)return;error.textContent='';scenes();if(kind!=='locations')mapCharacters();if(kind==='maps')q('[data-spatial-feature]').replaceChildren();q('[data-spatial-return]').disabled=selection===data.scope.primaryLocationID;q('[data-spatial-return]').onclick=()=>select(data.scope.primaryLocationID);if(kind==='locations'){details();return;}const options=catalog(),links=relevant(),available=new Set(links.map(l=>l.resourceID));const preferred=kind==='maps'?Number(preferences.resource):0;const next=resource&&options.some(x=>x.id===resource)?resource:available.has(preferred)?preferred:links[0]?.resourceID||resource&&options.some(x=>x.id===resource)&&resource||null;const menu=q('[data-spatial-resource]');menu.replaceChildren(new Option('Choose existing resource',''),...options.map(r=>new Option(r.name,String(r.id))));menu.value=next||'';menu.onchange=()=>{resource=Number(menu.value)||null;preferences.resource=resource;save();void renderResource();};q('[data-spatial-resolution]').textContent=resourceCaption(next);if(resource!==next){resource=next;void renderResource();}else if(renderer){if(renderer.revision!==String(catalog().find(c=>c.id===resource)?.modifiedDate)){void renderResource();}else highlight();}else void renderResource();updateAdvanced();} function updateAdvanced(){const advanced=q('[data-spatial-advanced]');const represented=resolution(data,selection,kind).find(l=>l.resourceID===resource);advanced.href=kind==='maps'?`/Maps?projectId=${position.projectId}&id=${resource}${represented?.featureID?'&featureId='+encodeURIComponent(represented.featureID):''}`:`/FloorPlans/Edit/${resource}${represented?.blockID?'?selectedBlockId='+represented.blockID:''}`;advanced.hidden=!resource;} function resourceCaption(target=resource){const found=resolution(data,selection,kind).filter(x=>x.resourceID===target);return found.length?(found[0].depth?`Represented through containing location: ${path(data,found[0].represented)}. This is not an exact position for the inspected location.`:'Directly associated with the inspected location.'):'No authoritative representation of the inspected location on this resource.';} function mapCharacters(){ const host=q('[data-spatial-characters]');host.replaceChildren(el('h3','Recorded scene characters')); for(const c of data.characters||[]){const location=c.locationID?data.locations.find(l=>id(l)===c.locationID):null;const row=el('p');row.append(el('span',`${c.characterName} · ${c.presenceTypeName||'Presence unknown / unset'} · `));row.append(location?btn(path(data,c.locationID),()=>select(c.locationID)):el('span',c.locationName||'Location unknown / unset'));host.append(row);} if(!data.characters?.length)host.append(el('p','Unknown / unset: no scene characters recorded.')); host.append(el('p',kind==='floorplans'?'Initials mark only a uniquely associated, explicitly saved room. Other characters remain in this presence list; positions within rooms are unknown.':'Only saved character locations are shown. Scene participation alone does not establish whereabouts. Containing geography is not a precise position.','small muted')); } function sceneHighlights(){const grouped=new Map();for(const s of data.scenes){const found=resolution(data,s.locationID,kind).filter(l=>l.resourceID===resource);for(const f of found){const key=kind==='maps'?f.featureID:f.blockID;if(!key)continue;if(!grouped.has(key))grouped.set(key,{featureID:key,roles:[],label:[]});const value=grouped.get(key);value.roles.push(s.position);value.label.push(`${['Previous','Current','Next'][s.position+1]}: ${path(data,s.locationID)}${f.depth?' (containing location)':''}`);}}if(kind==='maps')for(const c of data.characters||[]){if(!c.locationID)continue;for(const f of resolution(data,c.locationID,kind).filter(l=>l.resourceID===resource)){if(!grouped.has(f.featureID))grouped.set(f.featureID,{featureID:f.featureID,roles:[],label:[]});const value=grouped.get(f.featureID);value.roles.push(0);value.label.push(`${c.characterName}: ${c.locationName||path(data,c.locationID)}${f.depth?' (containing location; exact position unknown)':''}`);}}return [...grouped.values()].map(x=>({...x,label:x.label.join(' · ')}));} function annotate(){if(kind==='locations'||!data)return;for(const scene of data.scenes){const row=q(`[data-scene-position="${scene.position}"]`);if(!row)continue;row.querySelector('.spatial-elsewhere')?.remove();const resolved=resolution(data,scene.locationID,kind),here=resolved.filter(l=>l.resourceID===resource);let label='';if(scene.locationID){if(!resolved.length)label=kind==='maps'?'No mapped representation':'No associated plan';else if(!here.length)label=kind==='maps'?'On another map':'On another plan';else if(kind==='floorplans'&&here.every(l=>l.floorID&&l.floorID!==renderer?.getFloor?.()))label='On another level';else if(kind==='floorplans'&&!here.some(l=>l.blockID))label='Plan available; no associated room';else if(here.some(l=>l.depth))label='Containing location represented';}if(label)row.append(el('small',label,'spatial-elsewhere'));}} function highlight(){if(!renderer)return;annotate();renderer.highlight(sceneHighlights());const target=resolution(data,selection,kind).find(x=>x.resourceID===resource);if(renderer.selection!==selection){renderer.selection=selection;if(target){if(kind==='floorplans'&&!target.blockID&&target.floorID)renderer.floor?.(target.floorID);else renderer.centre(kind==='maps'?target.featureID:target.blockID,false);}}} async function renderResource(){if(!canvas)return;updateAdvanced();q('[data-spatial-feature]').replaceChildren();q('[data-spatial-resolution]').textContent=resourceCaption();const item=catalog().find(c=>c.id===resource);if(!item){renderer?.dispose();renderer=null;canvas.replaceChildren(el('p',`No suitable ${kind==='maps'?'map':'floor plan'} is associated. Choose an existing resource above or open the main World workspace.`));return;}if(kind==='maps'&&renderer?.id===resource){renderer.revision=String(item.modifiedDate);renderer.command('reload');return;}if(kind==='floorplans'&&renderer)floorSnapshot={id:renderer.id,floor:renderer.getFloor?.(),selection:renderer.selection};renderer?.dispose();renderer=null;canvas.replaceChildren();const target=resource,scope={...position};if(kind==='maps'){const frame=el('iframe');frame.title='Context map';frame.src=`/SpatialContext/Map?bookId=${scope.bookId}&sceneId=${scope.sceneId}&id=${target}`;const channel=crypto.randomUUID();let features=[],map,ready=false;const command=(action,args={})=>frame.contentWindow?.postMessage({type:'plotdirector.spatial.command',channel,action,...args},location.origin);const receive=e=>{if(e.origin!==location.origin||e.source!==frame.contentWindow||e.data?.channel!==channel||e.data.type!=='plotdirector.spatial.renderer')return;const m=e.data;if(m.action==='ready'){features=m.features;map=m.map;ready=true;highlight();}if(m.action==='viewport'){preferences.views??={};preferences.views[target]=m.view;save();}if(m.action==='select'&&m.feature)void(async()=>{if(m.feature.locationID)await select(m.feature.locationID);if(disposed||renderer?.id!==target)return;const detail=q('[data-spatial-feature]');detail.replaceChildren(el('strong',m.feature.name),el('small',m.feature.locationID?'Associated story location':'No associated location; inspection does not assign this feature to a scene.'));if(m.feature.notes)detail.append(el('p',m.feature.notes));q('[data-spatial-advanced]').href=`/Maps?projectId=${position.projectId}&id=${target}&featureId=${encodeURIComponent(m.feature.featureID)}`;})().catch(fail);if(m.action==='error')fail(Error(m.message));};window.addEventListener('message',receive);renderer={id:target,revision:String(item.modifiedDate),command,highlight:items=>command('highlight',{highlights:items}),centre:(id,force)=>{if(ready)command('centre',{id,force});},fit:()=>command('fit',{ids:sceneHighlights().map(h=>h.featureID)}),zoom:factor=>command('zoom',{factor}),features:()=>features,map:()=>map,dispose:()=>window.removeEventListener('message',receive)};frame.onload=()=>command('init',{view:preferences.views?.[target]});canvas.append(frame);}else{const request=++epoch;try{const response=await fetch(`/SpatialContext/Floor?bookId=${scope.bookId}&sceneId=${scope.sceneId}&id=${target}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error('Floor plan unavailable.');const html=await response.text();if(disposed||request!==epoch||resource!==target)return;canvas.innerHTML=html;renderer=floorRenderer(canvas,item);if(floorSnapshot?.id===item.id){renderer.floor?.(floorSnapshot.floor);renderer.selection=floorSnapshot.selection;}highlight();}catch(e){fail(e);}}} function floorRenderer(host,item){const container=host.querySelector('[data-spatial-floor-canvas]'),world=container.querySelector('[data-spatial-floor-world]'),viewport=container.querySelector('.spatial-floor-viewport'),level=container.querySelector('[data-spatial-floor]'),versions=JSON.parse(container.querySelector('[data-room-versions]').textContent);const engine=window.PlotDirectorFloorPlanRenderer.create(container);let view={x:0,y:0,scale:1},drag=null;const panels=[...container.querySelectorAll('[data-floor-panel]')],blocks=[...container.querySelectorAll('[data-block]')];const signal=new AbortController();function current(){return panels.find(p=>p.dataset.floorPanel===level.value);}function transform(){world.style.transform=`translate(${view.x}px,${view.y}px) scale(${view.scale})`;preferences.floorViews??={};preferences.floorViews[`${item.id}/${level.value}`]={...view};save();}function fit(){const grid=current()?.querySelector('[data-floor-grid]');if(!grid)return;const w=grid.offsetWidth||Number(grid.dataset.gridWidth)*34,h=grid.offsetHeight||Number(grid.dataset.gridHeight)*34;view={scale:Math.min((viewport.clientWidth-24)/w,(viewport.clientHeight-24)/h,1.5),x:12,y:12};transform();}function change(){preferences.floorLevels??={};preferences.floorLevels[item.id]=level.value;save();queueMicrotask(annotate);if(!current()){viewport.replaceChildren(el('p','This plan has no floors yet. Open Floor Plans to add a level.'));return;}for(const p of panels)p.classList.toggle('active',p===current());const visibleBlocks=engine.refreshSharedWalls(current());engine.refreshHiddenLocationStyles(visibleBlocks);engine.positionTransitions(current(),visibleBlocks);view=preferences.floorViews?.[`${item.id}/${level.value}`]||{x:0,y:0,scale:1};transform();if(!preferences.floorViews?.[`${item.id}/${level.value}`])fit();}level.onchange=change;function centre(blockId,force){const block=blocks.find(b=>Number(b.dataset.block)===Number(blockId));if(!block)return;const panel=block.closest('[data-floor-panel]');if(level.value!==panel.dataset.floorPanel){level.value=panel.dataset.floorPanel;change();}floorRoom=Number(block.dataset.block);decorate();if(force){const x=block.offsetLeft,y=block.offsetTop;view.x=viewport.clientWidth/2-(x+block.offsetWidth/2)*view.scale;view.y=viewport.clientHeight/2-(y+block.offsetHeight/2)*view.scale;transform();}} const overlays=el('div',null,'spatial-toolbar spatial-sensory-controls'); for(const [label,key] of [['Visibility','visibility'],['Audibility','audibility']]){const wrap=el('label'),input=el('input');input.type='checkbox';input.checked=key==='visibility'?visibility:audibility;input.onchange=()=>{if(key==='visibility')visibility=input.checked;else audibility=input.checked;decorate();};wrap.append(input,document.createTextNode(label));overlays.append(wrap);} const legend=el('p','Selected room: solid outline · Visible: dotted · Audible: dashed · Both: double. From selected room → highlighted room only; reverse relationships are not inferred. Unset flags do not prove impossibility.','small spatial-sensory-legend');container.prepend(overlays,legend); function decorate(){ const selected=blocks.find(b=>Number(b.dataset.block)===floorRoom),location=Number(selected?.dataset.locationId); for(const b of blocks){const target=Number(b.dataset.locationId);let see=false,hear=false; for(const r of data.sensoryRelationships||[])if(r.fromLocationID===location&&r.toLocationID===target){see ||= visibility&&(r.canSeeMovement===true||r.canSeeClearly===true);hear ||= audibility&&(r.canHearNormalSpeech===true||r.canHearLoudNoise===true);} b.classList.toggle('spatial-selected',b===selected);b.classList.toggle('spatial-visible',b!==selected&&see&&!hear);b.classList.toggle('spatial-audible',b!==selected&&hear&&!see);b.classList.toggle('spatial-both',b!==selected&&see&&hear);b.setAttribute('aria-pressed',String(b===selected)); b.querySelectorAll('.spatial-character-marker').forEach(n=>n.remove()); // A marker identifies an explicitly saved room, never an inferred coordinate or containing room. const peers=blocks.filter(other=>Number(other.dataset.locationId)===target); if(target&&peers.length===1)for(const c of data.characters||[])if(c.locationID===target){const marker=el('span',c.characterName.trim().split(/\s+/).slice(0,2).map(n=>Array.from(n)[0]).join(''),'spatial-character-marker');marker.title=`${c.characterName} · recorded room; position within room unknown`;marker.setAttribute('aria-label',marker.title);b.append(marker);} } } for(const b of blocks){b.tabIndex=0;b.setAttribute('role','button');b.setAttribute('aria-label',b.textContent.trim());b.addEventListener('click',()=>{if(drag?.moved)return;floorRoom=Number(b.dataset.block);decorate();const location=Number(b.dataset.locationId);if(location){renderer.selection=location;void select(location);}showRoom(b);},{signal:signal.signal});b.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();b.click();}},{signal:signal.signal});} viewport.addEventListener('wheel',e=>{e.preventDefault();const r=viewport.getBoundingClientRect(),x=e.clientX-r.left,y=e.clientY-r.top,scale=Math.max(.08,Math.min(4,view.scale*Math.exp(-e.deltaY*.001)));view.x=x-(x-view.x)*scale/view.scale;view.y=y-(y-view.y)*scale/view.scale;view.scale=scale;transform();},{passive:false,signal:signal.signal});viewport.addEventListener('pointerdown',e=>{if(e.button!==0)return;drag={x:e.clientX,y:e.clientY,vx:view.x,vy:view.y,moved:false};if(!e.target.closest('[data-block]'))viewport.setPointerCapture(e.pointerId);},{signal:signal.signal});viewport.addEventListener('pointermove',e=>{if(!drag||!viewport.hasPointerCapture(e.pointerId))return;drag.moved=Math.hypot(e.clientX-drag.x,e.clientY-drag.y)>4;view.x=drag.vx+e.clientX-drag.x;view.y=drag.vy+e.clientY-drag.y;transform();},{signal:signal.signal});viewport.addEventListener('pointerup',e=>{if(viewport.hasPointerCapture(e.pointerId))viewport.releasePointerCapture(e.pointerId);setTimeout(()=>drag=null,0);},{signal:signal.signal}); function showRoom(b){const feature=q('[data-spatial-feature]');feature.replaceChildren(el('span',`Room: ${b.getAttribute('aria-label')}`),el('small','Read-only inspection. Character markers identify recorded rooms; positions within rooms are unknown. Open Floor Plans for editing.'));q('[data-spatial-advanced]').href=`/FloorPlans/Edit/${item.id}?selectedBlockId=${b.dataset.block}`;} if(panels.some(p=>p.dataset.floorPanel===preferences.floorLevels?.[item.id]))level.value=preferences.floorLevels[item.id];change();return {id:item.id,revision:String(item.modifiedDate),blocks,showRoom,highlight:items=>{decorate();for(const b of blocks){b.querySelectorAll('.spatial-room-badge').forEach(n=>n.remove());b.classList.remove('spatial-position-0','spatial-position-1','spatial-position-2');const h=items.find(h=>Number(h.featureID)===Number(b.dataset.block));if(h){h.roles.forEach(r=>b.classList.add(`spatial-position-${r+1}`));b.append(el('span',h.roles.map(r=>['Previous','Current','Next'][r+1]).join(' · '),'spatial-room-badge'));b.title=h.label;b.setAttribute('aria-description',h.label);}}},centre,fit,getFloor:()=>Number(level.value),floor:id=>{if(panels.some(p=>Number(p.dataset.floorPanel)===id)){level.value=String(id);change();}},zoom:factor=>{view.scale=Math.max(.08,Math.min(4,view.scale*factor));transform();},dispose:()=>signal.abort()}; } async function confirmOperation(message,commit){if(busy)throw Error('Finish or cancel the current operation first.');const target={...position};const panel=q('[data-spatial-operation]');panel.hidden=false;panel.replaceChildren(el('p',message));guard(true);panel.append(btn('Confirm',async()=>{try{if(await commit(target)!=='continue')clearOperation();}catch(e){fail(e);}}),btn('Cancel',clearOperation));} for(const b of node.querySelectorAll('[data-spatial-zoom]'))b.onclick=()=>renderer?.zoom(b.dataset.spatialZoom==='in'?1.25:.8);q('[data-spatial-fit]')?.addEventListener('click',()=>renderer?.fit());q('[data-spatial-centre]')?.addEventListener('click',()=>{const found=resolution(data,selection,kind).find(l=>l.resourceID===resource);if(found)renderer?.centre(kind==='maps'?found.featureID:found.blockID,true);}); instances.set(node,{position(next){if(busy)return false;if(kind!=='locations'&&position.sceneId!==next.sceneId){resource=null;floorRoom=null;floorSnapshot=null;}position=next;void reload();return true;},invalidate(hint){if(busy)return false;if(kind==='floorplans'&&renderer&&(hint.kinds||[hint.kind]).some(k=>['floorplans','locations','spatial',undefined].includes(k)))renderer.revision=null;invalidateCache();void reload();return true;},dispose(){disposed=true;epoch++;bus.listeners.delete(listener);renderer?.dispose();abort.abort();},busy:()=>busy});void reload(); } window.PlotDirectorContextLifecycles??={};window.PlotDirectorContextLifecycles.spatial={mount,onCacheInvalidation:invalidateCache,dispose:node=>{instances.get(node)?.dispose();instances.delete(node);},canRefresh:node=>!instances.get(node)?.busy(),onPosition:(node,next)=>instances.get(node)?.position(next)===true,onInvalidation:(node,hint)=>instances.get(node)?.invalidate(hint)===true}; window.PlotDirectorSpatialContext=Object.freeze({ancestors,resolution,path,subscribe(root,listener){const s=session(root);s.listeners.add(listener);return()=>s.listeners.delete(listener);},inspect(root,location,source){if(location!==null&&(!Number.isSafeInteger(location)||location<=0))throw TypeError('A canonical location identifier is required.');session(root).select(location,source);}}); })();