diff --git a/PlotLine.Tests/Browser/context-maps-development.cjs b/PlotLine.Tests/Browser/context-maps-development.cjs new file mode 100644 index 00000000..52d02c46 --- /dev/null +++ b/PlotLine.Tests/Browser/context-maps-development.cjs @@ -0,0 +1,35 @@ +// Genuine Development forms, ordinary writer identity, registered disposable project. +const assert=require('node:assert/strict'),{open}=require('./dev-acceptance.cjs'); +let session,stage='login'; +(async()=>{try{ + session=await open();let p=session.page;const project=await session.project(); + const a=await session.create('Locations','?projectId='+project,{LocationName:'Harbour'}),b=await session.create('Locations','?projectId='+project,{LocationName:'Hill'}); + const book=await session.create('Books','?projectId='+project,{BookTitle:'Maps acceptance',BookNumber:1}),chapter=await session.create('Chapters','?bookId='+book,{ChapterTitle:'Map chapter',ChapterNumber:1}); + async function scene(name,place){await session.goto('/Scenes/Create?chapterId='+chapter);await p.locator('#SceneTitle').fill(name);await p.locator('#PrimaryLocationID').selectOption(String(place));await p.getByRole('button',{name:'Create scene',exact:true}).click();await p.waitForURL('**/Scenes/Edit/*');return Number(new URL(p.url()).pathname.split('/').at(-1));} + const first=await scene('At harbour',a),second=await scene('At hill',b); + const character=await session.create('Characters','?projectId='+project,{CharacterName:'Recorded traveller'},async page=>{const custom=page.locator('[name=CustomSex]');if(await custom.count()&&await custom.isEnabled())await custom.fill('Unspecified');}); + const unknown=await session.create('Characters','?projectId='+project,{CharacterName:'Unlocated traveller'},async page=>{const custom=page.locator('[name=CustomSex]');if(await custom.count()&&await custom.isEnabled())await custom.fill('Unspecified');}); + await session.goto('/Scenes/SceneCharactersEditor?sceneId='+first);await session.post('/Scenes/SaveSceneCharacters',{SceneID:first,'NewCharacter.CharacterID':character,'NewCharacter.LocationID':b});await session.post('/Scenes/SaveSceneCharacters',{SceneID:first,'NewCharacter.CharacterID':unknown}); + async function map(name,extra){await session.goto('/Maps?projectId='+project);await p.locator('#mapsWelcomeNew').click();await p.locator('#mapsNewForm [name=Name]').fill(name);await p.locator('#mapsNewForm [name=Starter]').selectOption('land');await p.locator('#mapsNewForm button[type=submit]').click();await p.waitForFunction(()=>window.PlotDirectorMapWorkspace?.document.features.length>1&&!PlotDirectorMapWorkspace.busy);const id=await p.evaluate(()=>PlotDirectorMapWorkspace.document.map.mapID); + const ids=await p.evaluate(()=>PlotDirectorMapWorkspace.document.features.slice(0,2).map(f=>f.featureID)); + for(const [feature,place] of [[ids[0],a],...(extra?[[ids[1],b]]:[])]){await p.locator(`[data-feature-id="${feature}"]`).click();const select=p.locator('[data-field=locationID]');await select.evaluate(e=>{for(let n=e.parentElement;n;n=n.parentElement)if(n.tagName==='DETAILS')n.open=true;});await select.selectOption(String(place));} + await p.locator('#mapsSave').click();await p.waitForFunction(()=>!PlotDirectorMapWorkspace.dirty&&!PlotDirectorMapWorkspace.busy);return {id,feature:ids[0]};} + stage='map forms';const one=await map('Local chart',false),two=await map('Regional chart',true); + const feature=`/Writing/Context?projectId=${project}&bookId=${book}&chapterId=${chapter}&sceneId=${first}&pinned=true`; + const ctx=await p.context().newPage();await ctx.goto('https://dev.plotdirector.com'+feature);await ctx.selectOption('[data-context-pane="0"] [data-context-tab]','maps'); + const ready=id=>ctx.waitForFunction(id=>document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.document.map.mapID===id,id); + stage='selection and recorded whereabouts';await ctx.locator('[data-spatial-resource]').selectOption(String(two.id));await ready(two.id);await ctx.locator('[data-spatial-characters]').getByText(/Recorded traveller/).waitFor();assert.match(await ctx.locator('[data-spatial-characters]').textContent(),/Hill/);assert.match(await ctx.locator('[data-spatial-characters]').textContent(),/Unlocated traveller.*Location unknown \/ unset/);assert.equal(await ctx.locator('[data-spatial-place]').count(),0);await ctx.waitForFunction(()=>document.querySelector('iframe').contentDocument.querySelector('[data-spatial-overlay] [aria-label*="Recorded traveller"]'));assert.equal(await ctx.frameLocator('iframe').locator('.spatial-map-background').count()>0,true); + const mutations=[];ctx.on('request',r=>{if(r.method()==='POST')mutations.push(new URL(r.url()).pathname);}); + const snapshot=()=>ctx.evaluate(()=>({position:{...document.querySelector('[data-context-workspace]').contextController.position},view:{...document.querySelector('iframe').contentWindow.PlotDirectorMapWorkspace.view}})); + stage='local browsing';const before=await snapshot();await ctx.locator('[data-spatial-zoom=in]').click();await ctx.waitForFunction(w=>document.querySelector('iframe').contentWindow.PlotDirectorMapWorkspace.view.wdocument.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected');assert.equal(await ctx.locator('[data-shared-focus-hold]').getAttribute('aria-pressed'),'true');const held=await snapshot();await session.goto(`/Maps?projectId=${project}&id=${two.id}`);await p.locator(`[data-feature-id="${two.feature}"]`).click();const width=p.locator('[data-field=width]').first();const value=Number(await width.inputValue())+23;await width.fill(String(value));await p.locator('#mapsSave').click();await p.waitForFunction(()=>!PlotDirectorMapWorkspace.dirty&&!PlotDirectorMapWorkspace.busy);await ctx.waitForFunction(v=>document.querySelector('iframe').contentWindow.PlotDirectorMapWorkspace.document.features[0].width===v,value);assert.deepEqual(await snapshot(),held); + stage='main editor navigation';await session.goto('/Locations/Details/'+a);await p.waitForFunction(()=>window.PlotDirectorPresenceConnection?.state==='Connected');const contextUrl=ctx.url();await ctx.getByRole('link',{name:'Open in Maps',exact:true}).click();await p.waitForURL(u=>u.pathname==='/Maps'&&u.searchParams.get('id')===String(two.id));assert.equal(ctx.url(),contextUrl);assert.deepEqual(await snapshot(),held); + stage='scene following';await ctx.locator('[data-spatial-resource]').selectOption(String(one.id));await ready(one.id);await ctx.selectOption('[data-context-scene]',String(second));await ready(two.id);assert.equal((await snapshot()).position.sceneId,second); + stage='split and narrow';await ctx.selectOption('[data-context-layout]','columns');await ctx.selectOption('[data-context-pane="1"] [data-context-tab]','maps');await ctx.locator('[data-context-pane="1"] iframe').waitFor();await ctx.setViewportSize({width:460,height:850});assert.equal(await ctx.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),true); + await session.close();session=await open();p=session.page;stage='fresh login persistence';await session.goto(`/Maps?projectId=${project}&id=${two.id}`);await p.waitForFunction(v=>window.PlotDirectorMapWorkspace?.document.features[0].width===v,value);await session.goto(feature);await p.selectOption('[data-context-pane="0"] [data-context-tab]','maps');await p.locator('[data-spatial-characters]').getByText(/Recorded traveller/).waitFor(); + console.log(JSON.stringify({passed:true,checks:['two linked maps selected locally','recorded character whereabouts only','lower geography emphasis','read-only Context','local zoom and inspection preserve focus','Hold saved map refresh preserves viewport','scene changes select relevant map','split narrow layout','fresh-login persistence'],featureUrl:'https://dev.plotdirector.com'+feature})); + }catch{console.error('Maps acceptance failed at '+stage+'; no credentials logged.');process.exitCode=1;} + finally{if(session){try{await session.cleanup();console.log('PASS disposable project cleanup');}catch{console.error('Cleanup incomplete; preserve journal.');process.exitCode=1;}finally{await session.close();}}} +})(); diff --git a/PlotLine/Views/Writing/_ContextSpatial.cshtml b/PlotLine/Views/Writing/_ContextSpatial.cshtml index 652d0537..fc30dc20 100644 --- a/PlotLine/Views/Writing/_ContextSpatial.cshtml +++ b/PlotLine/Views/Writing/_ContextSpatial.cshtml @@ -8,8 +8,8 @@

Loading recorded locations…

}else{
-
Open in @(Model.Kind=="maps"?"Maps":"Floor Plans")
-

+
@if(Model.Kind=="floorplans"){}Open in @(Model.Kind=="maps"?"Maps":"Floor Plans")
+

@if(Model.Kind=="maps"){
} } diff --git a/PlotLine/wwwroot/css/context-spatial.css b/PlotLine/wwwroot/css/context-spatial.css index a6ec07e0..69297ced 100644 --- a/PlotLine/wwwroot/css/context-spatial.css +++ b/PlotLine/wwwroot/css/context-spatial.css @@ -6,3 +6,5 @@ @container(max-width:580px){.spatial-location-layout{grid-template-columns:minmax(0,1fr);grid-template-rows:auto minmax(0,1fr)}.spatial-location-layout>nav{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));max-height:13rem;gap:.2rem}.spatial-scene{padding:.2rem}.spatial-scene-strip small{display:none}.spatial-toolbar{font-size:.8rem}.spatial-toolbar select{max-width:12rem}} .spatial-floor-viewport .floor-plan-resize-handle{display:none} + +.spatial-renderer-page [data-feature-id].spatial-map-background{opacity:.45} diff --git a/PlotLine/wwwroot/js/context-map-renderer.js b/PlotLine/wwwroot/js/context-map-renderer.js index ec85150f..9f136d6e 100644 --- a/PlotLine/wwwroot/js/context-map-renderer.js +++ b/PlotLine/wwwroot/js/context-map-renderer.js @@ -2,10 +2,10 @@ (() => { if(!document.body.classList.contains('spatial-renderer-page'))return; const api=window.PlotDirectorMapWorkspace,canvas=document.querySelector('#mapsCanvas'),app=document.querySelector('#mapsApp');if(!api||!canvas)return; - const origin=location.origin;let channel=null,highlights=[],placement=false,pointer=null; + const origin=location.origin;let channel=null,highlights=[],pointer=null; const send=(action,extra={})=>{if(channel)parent.postMessage({type:'plotdirector.spatial.renderer',channel,action,...extra},origin);}; const ns='http://www.w3.org/2000/svg',layer=document.createElementNS(ns,'g');layer.dataset.spatialOverlay='';layer.setAttribute('pointer-events','none');canvas.append(layer); - function paint(){layer.replaceChildren();const scale=api.view.w/Math.max(canvas.clientWidth,1);for(const item of highlights){const f=api.document.features.find(f=>f.featureID===item.featureID);if(!f||!f.isPlaced)continue;const g=document.createElementNS(ns,'g');g.setAttribute('transform',`translate(${f.x} ${f.y})`);g.setAttribute('role','img');g.setAttribute('aria-label',item.label);const roles=[...new Set(item.roles)].sort((a,b)=>a-b);for(let i=0;i['P','C','N'][r+1]).join(' · ');text.setAttribute('x',String(24*scale));text.setAttribute('y',String(-18*scale));text.setAttribute('font-size',String(13*scale));text.setAttribute('class','spatial-map-badge');g.append(text);const title=document.createElementNS(ns,'title');title.textContent=item.label;g.append(title);layer.append(g);}} + function paint(){const relevant=new Set(highlights.map(h=>h.featureID));for(const feature of canvas.querySelectorAll('[data-feature-id]'))feature.classList.toggle('spatial-map-background',relevant.size>0&&!relevant.has(feature.dataset.featureId));layer.replaceChildren();const scale=api.view.w/Math.max(canvas.clientWidth,1);for(const item of highlights){const f=api.document.features.find(f=>f.featureID===item.featureID);if(!f||!f.isPlaced)continue;const g=document.createElementNS(ns,'g');g.setAttribute('transform',`translate(${f.x} ${f.y})`);g.setAttribute('role','img');g.setAttribute('aria-label',item.label);const roles=[...new Set(item.roles)].sort((a,b)=>a-b);for(let i=0;i['P','C','N'][r+1]).join(' · ');text.setAttribute('x',String(24*scale));text.setAttribute('y',String(-18*scale));text.setAttribute('font-size',String(13*scale));text.setAttribute('class','spatial-map-badge');g.append(text);const title=document.createElementNS(ns,'title');title.textContent=item.label;g.append(title);layer.append(g);}} app.addEventListener('map-rendered',()=>{paint();send('viewport',{view:api.view});}); window.addEventListener('message',async e=>{if(e.origin!==origin||e.source!==parent||e.data?.type!=='plotdirector.spatial.command')return;const m=e.data;if(channel&&m.channel!==channel)return;channel=m.channel; if(m.action==='init'){if(m.view)api.setView(m.view);send('ready',{map:api.document.map,features:api.document.features,view:api.view});} @@ -13,14 +13,13 @@ if(m.action==='zoom')api.zoom(1/m.factor); if(m.action==='fit')api.fit(m.ids?.length?api.document.features.filter(f=>m.ids.includes(f.featureID)):api.document.features); if(m.action==='centre'){const f=api.document.features.find(f=>f.featureID===m.id);if(f&&(m.force||f.xapi.view.x+api.view.w||f.yapi.view.y+api.view.h))api.focus(f.featureID);if(f)api.select(f.featureID);} - if(m.action==='placement'){placement=!!m.active;canvas.classList.toggle('spatial-placing',placement);} if(m.action==='reload'){try{const r=await fetch(`/Maps/State?projectId=${api.document.map.projectID}&id=${api.document.map.mapID}`,{cache:'no-store'});if(!r.ok||r.redirected)throw Error('Map unavailable');api.replaceDocument(await r.json());send('ready',{map:api.document.map,features:api.document.features,view:api.view});}catch(error){send('error',{message:error.message});}} }); - canvas.addEventListener('pointerdown',e=>{pointer={x:e.clientX,y:e.clientY,id:e.target.closest('[data-feature-id],[data-boundary-feature-id]')?.dataset.featureId||e.target.closest('[data-boundary-feature-id]')?.dataset.boundaryFeatureId};if(placement){e.preventDefault();e.stopImmediatePropagation();canvas.setPointerCapture(e.pointerId);}},true); - canvas.addEventListener('pointerup',e=>{if(!pointer)return;const start=pointer;pointer=null;if(Math.hypot(start.x-e.clientX,start.y-e.clientY)>5)return;if(placement){e.preventDefault();e.stopImmediatePropagation();send('place',{point:{x:api.world(e)[0],y:api.world(e)[1]}});if(canvas.hasPointerCapture(e.pointerId))canvas.releasePointerCapture(e.pointerId);}else if(start.id){const f=api.document.features.find(f=>f.featureID===start.id);send('select',{feature:f});}},true); + canvas.addEventListener('pointerdown',e=>{pointer={x:e.clientX,y:e.clientY,id:e.target.closest('[data-feature-id],[data-boundary-feature-id]')?.dataset.featureId||e.target.closest('[data-boundary-feature-id]')?.dataset.boundaryFeatureId};},true); + canvas.addEventListener('pointerup',e=>{if(!pointer)return;const start=pointer;pointer=null;if(Math.hypot(start.x-e.clientX,start.y-e.clientY)>5)return;if(start.id){const f=api.document.features.find(f=>f.featureID===start.id);send('select',{feature:f});}},true); canvas.addEventListener('dblclick',e=>{e.preventDefault();e.stopImmediatePropagation();},true); - canvas.addEventListener('dragover',e=>{if(e.dataTransfer.types.includes('application/x-plotdirector-spatial-location')){e.preventDefault();e.stopImmediatePropagation();e.dataTransfer.dropEffect='copy';}},true); - canvas.addEventListener('drop',e=>{e.preventDefault();e.stopImmediatePropagation();try{const payload=JSON.parse(e.dataTransfer.getData('application/x-plotdirector-spatial-location'));send('drop',{payload,point:{x:api.world(e)[0],y:api.world(e)[1]}});}catch{}},true); - window.addEventListener('keydown',e=>{if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'){e.preventDefault();e.stopImmediatePropagation();}if(e.key==='Escape'&&placement){e.preventDefault();e.stopImmediatePropagation();send('cancel');}},true); + canvas.addEventListener('dragover',e=>{e.preventDefault();e.stopImmediatePropagation();if(e.dataTransfer)e.dataTransfer.dropEffect='none';},true); + canvas.addEventListener('drop',e=>{e.preventDefault();e.stopImmediatePropagation();},true); + window.addEventListener('keydown',e=>{if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'){e.preventDefault();e.stopImmediatePropagation();}},true); canvas.addEventListener('keyup',e=>{if(['Enter',' '].includes(e.key)){const id=e.target.closest('[data-feature-id]')?.dataset.featureId;if(id)send('select',{feature:api.document.features.find(f=>f.featureID===id)});}}); })(); diff --git a/PlotLine/wwwroot/js/context-spatial.js b/PlotLine/wwwroot/js/context-spatial.js index 4fcc1d4f..59351bba 100644 --- a/PlotLine/wwwroot/js/context-spatial.js +++ b/PlotLine/wwwroot/js/context-spatial.js @@ -59,16 +59,22 @@ } 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))spatial.append(btn('Place on map',()=>{bus.pendingPlacement=selection;return showTool('maps');}));}host.append(spatial);} + 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==='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&&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();q('[data-spatial-place]').disabled=!data.scope.canEdit||!resource||(kind==='maps'&&!selection);q('[data-spatial-place]').onclick=()=>kind==='maps'?startPlacement(selection):chooseRoom();updateAdvanced();} + function draw(){if(!data||disposed)return;error.textContent='';scenes();if(kind==='maps'){q('[data-spatial-feature]').replaceChildren();mapCharacters();}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&&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();if(kind==='floorplans'){q('[data-spatial-place]').disabled=!data.scope.canEdit||!resource;q('[data-spatial-place]').onclick=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 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','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);}}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 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();}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}); @@ -77,13 +83,9 @@ 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=>{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(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(); + instances.set(node,{position(next){if(busy)return false;if(kind==='maps'&&position.sceneId!==next.sceneId)resource=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);}});