71 lines
37 KiB
JavaScript
71 lines
37 KiB
JavaScript
/* 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,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:'spatial'});}
|
|
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.');await post(saved.route,{token:saved.token});undo=null;q('[data-spatial-undo]').hidden=true;root.contextController.invalidate({kind:'spatial',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.position<index&&s.locationID===id(location));if(repeated)row.append(el('small','Same location'));const mapped=resolution(data,id(location),'maps'),plans=resolution(data,id(location),'floorplans');row.append(el('small',`${mapped.length?'◉ Map available':''}${mapped.length&&plans.length?' · ':''}${plans.length?'▣ Floor plan available':''}`));draggable(pick,id(location));}const recorded=data.assignments.filter(a=>a.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 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);if(!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);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))spatial.append(btn('Place on map',()=>{bus.pendingPlacement=selection;return showTool('maps');}));}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==='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=Number(preferences.resource);const next=resource&&available.has(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();q('[data-spatial-place]').disabled=!data.scope.canEdit||!resource||(kind==='maps'&&!selection);q('[data-spatial-place]').onclick=()=>kind==='maps'?startPlacement(selection):chooseRoom();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 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)':''}`);}}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);}}if(kind==='maps'&&bus.pendingPlacement&&renderer.map?.()){const target=bus.pendingPlacement;bus.pendingPlacement=null;void startPlacement(target).catch(fail);}}
|
|
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(bus.pendingPlacement){const target=bus.pendingPlacement;bus.pendingPlacement=null;void startPlacement(target).catch(fail);}}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==='cancel'&&operation)clearOperation();if(m.action==='place'&&operation)void savePlacement(m.point);if(m.action==='drop'&&validDrop(m.payload))void dropPlacement(m.payload.locationId,m.point);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(){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();}blocks.forEach(b=>b.classList.toggle('spatial-selected',b===block));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();}}
|
|
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;const location=Number(b.dataset.locationId);if(location)void select(location);showRoom(b);},{signal:signal.signal});b.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();b.click();}},{signal:signal.signal});b.addEventListener('dragover',e=>{if(e.dataTransfer.types.includes(mime)){e.preventDefault();b.classList.add('spatial-drop');}},{signal:signal.signal});b.addEventListener('dragleave',()=>b.classList.remove('spatial-drop'),{signal:signal.signal});b.addEventListener('drop',e=>{e.preventDefault();b.classList.remove('spatial-drop');try{const p=JSON.parse(e.dataTransfer.getData(mime));if(validDrop(p))void associateRoom(b,p.locationId);}catch(error){fail(error);}},{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.textContent.trim()}`));if(data.scope.canEdit)feature.append(btn('Associate existing location',async()=>{const chosen=await picker('Associate existing location with this room',Number(b.dataset.locationId));if(chosen!==undefined&&chosen!==null)await associateRoom(b,chosen);}),btn('Create location and associate',()=>{const version=versions.find(v=>v.id===Number(b.dataset.block));return createLocation(false,data.planCatalog.find(p=>p.id===resource)?.locationID,{id:Number(b.dataset.block),version:version.version});}));}
|
|
async function associateRoom(b,location){if(busy)throw Error('Finish or cancel the current operation first.');if(Number(b.dataset.locationId)===location)return;const version=versions.find(v=>v.id===Number(b.dataset.block));const old=Number(b.dataset.locationId);const target={bookID:position.bookId,sceneID:position.sceneId,kind:'room',locationID:location,resourceID:item.id,geometryID:b.dataset.block,expected:version.version,replace:!!old};await confirmOperation(`Replace the recorded room association? Geometry and location parents will stay unchanged. Connected transition identities must be reviewed in the main editor.`,async()=>finish(await post('/SpatialContext/Mutate',target)));}
|
|
change();return {id:item.id,revision:String(item.modifiedDate),blocks,showRoom,highlight:items=>{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));}
|
|
async function startPlacement(location){if(!renderer?.map?.())throw Error('Choose and load a map first.');const existing=renderer.features().find(f=>f.locationID===location);if(existing&&(!existing.isLocked&&existing.geometryClass==='Marker')){await confirmOperation('This location already has a marker on this map. Reposition it explicitly?',()=>beginPlacement(location,existing));return;}if(existing){renderer.centre(existing.featureID,true);throw Error('A representation already exists. Edit complex or locked geometry in Maps.');}beginPlacement(location);}
|
|
function beginPlacement(location,existing){const map=renderer.map();const target={bookID:position.bookId,sceneID:position.sceneId,kind:'map',locationID:location,resourceID:resource,geometryID:existing?.featureID,expected:String(map.revision),replace:!!existing};operation=target;const panel=q('[data-spatial-operation]');panel.hidden=false;panel.replaceChildren(el('strong',`Place existing location: ${data.locations.find(l=>id(l)===location)?.locationName||location}`),el('p','Click a map position to save. The location record and its parent will stay unchanged.'),btn('Cancel',clearOperation));guard(true);renderer.command('placement',{active:true});return 'continue';}
|
|
async function savePlacement(point){const target=operation;if(!target)return;try{const result=await post('/SpatialContext/Mutate',{...target,x:point.x,y:point.y});clearOperation();await finish(result);}catch(e){fail(e);}}
|
|
async function dropPlacement(location,point){try{const existing=renderer?.features().find(f=>f.locationID===location);if(existing)throw Error('This location already has a representation on this map. Use Place location to reveal or explicitly reposition it.');const map=renderer.map(),target={bookID:position.bookId,sceneID:position.sceneId,kind:'map',locationID:location,resourceID:resource,expected:String(map.revision),x:point.x,y:point.y};await confirmOperation('Place this existing location at the dropped map position?',async()=>finish(await post('/SpatialContext/Mutate',target)));}catch(e){fail(e);}}
|
|
function chooseRoom(){if(!renderer?.blocks)return;const feature=q('[data-spatial-feature]');feature.replaceChildren(el('p','Select a room to associate an existing location. No geometry or parent location will be changed.'));const plan=data.planCatalog.find(p=>p.id===resource);if(plan)feature.append(btn('Associate this plan with a location',async()=>{const chosen=await picker('Associate floor plan with existing location',plan.locationID);if(chosen===undefined||chosen===null||chosen===plan.locationID)return;const target={bookID:position.bookId,sceneID:position.sceneId,kind:'plan',locationID:chosen,resourceID:resource,expected:plan.version,replace:!!plan.locationID};await confirmOperation('Associate this plan with the selected existing location?',async()=>finish(await post('/SpatialContext/Mutate',target)));}));}
|
|
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;position=next;void reload();return true;},invalidate(hint){if(busy)return false;if(!['locations','maps','floorplans','spatial','structure','characters','relationships','assets',undefined].includes(hint.kind))return true;if(kind==='floorplans'&&renderer&&['locations','spatial',undefined].includes(hint.kind))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);}});
|
|
})();
|