diff --git a/PlotLine.Tests/Browser/context-spatial-development-pwa.cjs b/PlotLine.Tests/Browser/context-spatial-development-pwa.cjs new file mode 100644 index 00000000..ba248dd3 --- /dev/null +++ b/PlotLine.Tests/Browser/context-spatial-development-pwa.cjs @@ -0,0 +1,3 @@ +// Real installed Chromium PWA on Development; reads only the dedicated synthetic world. +const{chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');const file=process.argv[2];if(!file?.startsWith('/tmp/pd-dev-browser-'))throw Error('Dedicated identity required');const identity=JSON.parse(fs.readFileSync(file));assert.equal(identity.Database,'PlotDirector_Development');assert(identity.Email.startsWith('pwa-browser-'));const f=identity.SpatialFixture;assert(f?.scenes?.length===3); +(async()=>{const base='https://dev.plotdirector.com',profile=fs.mkdtempSync('/tmp/pd-spatial-development-pwa-'),context=await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1600,height:1050}}),cdp=await context.browser().newBrowserCDPSession(),manifestId=base+'/Projects';try{const tab=context.pages()[0];await tab.goto(base+'/Account/Login');await tab.locator('#Email').fill(identity.Email);await tab.locator('#Password').fill(identity.Password);await Promise.all([tab.waitForURL('**/Projects'),tab.locator('form button[type=submit]').click()]);await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/Projects'});await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=context.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:base+`/Writing/Context?projectId=${identity.ProjectID}&bookId=${identity.BookID}&sceneId=${f.scenes[1]}&pinned=true`});const page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));const errors=[];page.on('pageerror',e=>errors.push(e.message));const pane=i=>page.locator(`[data-context-pane="${i}"]`);await page.selectOption('[data-context-pane="0"] [data-context-tab]','locations');await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor();await page.selectOption('[data-context-layout]','columns');await page.selectOption('[data-context-pane="1"] [data-context-tab]','maps');await page.waitForFunction(()=>document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.document.features.length===1);assert.equal(await page.frames().find(frame=>frame.url().includes('/SpatialContext/Map')).locator('.spatial-map-ring').count(),3);await page.screenshot({path:'/tmp/pd-spatial-evidence/development-installed-pwa-maps.png'});await page.selectOption('[data-context-pane="1"] [data-context-tab]','floorplans');await pane(1).locator('.spatial-room-badge').first().waitFor();assert.equal(await pane(1).locator('.spatial-room-badge').count(),3);await page.screenshot({path:'/tmp/pd-spatial-evidence/development-installed-pwa-floorplans.png'});await page.selectOption('[data-context-layout]','rows');await page.screenshot({path:'/tmp/pd-spatial-evidence/development-installed-pwa-stacked.png'});assert.deepEqual(errors,[]);fs.writeFileSync('/tmp/pd-spatial-evidence/development-installed-pwa-results.json',JSON.stringify({passed:true,installed:true,target:'Development',fixturesOnly:true,errors},null,2));console.log('PASS authenticated Development installed Chromium PWA: Locations, Maps, Floor Plans, shared scene highlights, side-by-side/stacked layout, no page errors');}finally{await cdp.send('PWA.uninstall',{manifestId}).catch(()=>{});await context.close();fs.rmSync(profile,{recursive:true,force:true});}})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/Browser/context-spatial.cjs b/PlotLine.Tests/Browser/context-spatial.cjs index 12d60e9d..b3cb0ec4 100644 --- a/PlotLine.Tests/Browser/context-spatial.cjs +++ b/PlotLine.Tests/Browser/context-spatial.cjs @@ -20,6 +20,7 @@ step='native cross-pane location drop';const dragSource=await pane(0).getByRole( step='room association reviewed conflict';await page.selectOption(tab(1),'floorplans');await pane(1).locator('[data-block="52"]').waitFor();await pane(1).locator('[data-block="52"]').click();await page.route('**/LocationWorkspace/Picker?*',route=>route.fulfill({json:{locations:[{id:102,name:'The old house',parent:null,type:'4'},{id:103,name:'Bedroom',parent:102,type:'4'},{id:104,name:'Lounge',parent:102,type:'4'}],types:[]}}));await pane(1).getByRole('button',{name:'Associate existing location',exact:true}).click();await page.locator('dialog [data-picker-id="103"]').waitFor();await page.locator('dialog [data-picker-id="103"] .pd-location-picker-name').click();await page.getByRole('button',{name:'Choose',exact:true}).click();await pane(1).getByRole('button',{name:'Confirm',exact:true}).waitFor();await shot('14-room-association');await pane(1).getByRole('button',{name:'Confirm',exact:true}).click();await pane(1).getByText('Synthetic concurrent change; previous geometry retained.').waitFor();assert.equal(attempted.kind,'room');assert.equal(attempted.locationID,103);assert.equal(attempted.geometryID,'52');assert.equal(attempted.replace,true);assert.equal(await pane(1).locator('[data-block="52"]').getAttribute('data-location-id'),'104');await pane(1).getByRole('button',{name:'Cancel',exact:true}).click(); step='native room drop';const roomSource=await pane(0).getByRole('heading',{name:'Lounge',exact:true}).boundingBox(),roomTarget=await pane(1).locator('[data-block="51"]').boundingBox();await page.mouse.move(roomSource.x+25,roomSource.y+10);await page.mouse.down();await page.mouse.move(roomSource.x+55,roomSource.y+12,{steps:5});await page.mouse.move(roomTarget.x+40,roomTarget.y+40,{steps:25});await page.mouse.up();await pane(1).getByRole('button',{name:'Confirm',exact:true}).waitFor();await shot('14-native-room-drop');await pane(1).getByRole('button',{name:'Cancel',exact:true}).click(); step='unmapped location';await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:26}));await pane(0).getByRole('heading',{name:'Remote valley',exact:true}).waitFor();await shot('12-unmapped-location');await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:22}));await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor(); +step='unavailable assignment remains recorded';await page.route('**/SpatialContext/State?bookId=12&sceneId=28*',async route=>{const r=await route.fetch();const data=await r.json();data.scope.primaryLocationID=999;data.scenes.find(s=>s.position===0).locationID=999;return route.fulfill({json:data});});await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:28}));await pane(0).getByText('Assigned location unavailable',{exact:true}).waitFor();assert(await pane(0).getByText('The assigned or inspected location is unavailable.',{exact:false}).count());await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:22}));await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor(); step='themes';if(await pane(0).getByRole('button',{name:'Return to scene location'}).isEnabled())await pane(0).getByRole('button',{name:'Return to scene location'}).click();await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:22}));await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor();for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await page.evaluate(t=>{localStorage.setItem('plotdirector.applicationTheme',t);window.dispatchEvent(new StorageEvent('storage',{key:'plotdirector.applicationTheme',newValue:t}));},theme);await page.waitForTimeout(40);await shot('theme-'+theme);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false);} step='narrow';await page.setViewportSize({width:768,height:900});await shot('16-narrow');assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false); step='independent Context windows';const second=await context.newPage();await second.goto(base+'/Writing/Context?pinned=true');await second.selectOption('[data-context-pane="0"] [data-context-tab]','locations');await second.getByRole('heading',{name:'Bedroom',exact:true}).waitFor();await page.setViewportSize({width:1440,height:1000});await pane(0).locator('[data-scene-position="-1"] button').click();await pane(0).getByRole('heading',{name:'Lounge',exact:true}).waitFor();assert.equal(await second.getByRole('heading',{name:'Bedroom',exact:true}).count(),1);assert.notEqual(await second.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId),await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId));await second.close(); diff --git a/PlotLine/wwwroot/js/context-spatial.js b/PlotLine/wwwroot/js/context-spatial.js index a110031a..a0592ff0 100644 --- a/PlotLine/wwwroot/js/context-spatial.js +++ b/PlotLine/wwwroot/js/context-spatial.js @@ -18,7 +18,7 @@ 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;}; + 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();} @@ -31,14 +31,14 @@ 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||'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);}} + 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 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','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 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();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();};const selectedLinks=resolution(data,selection,kind).filter(x=>x.resourceID===next);q('[data-spatial-resolution]').textContent=selectedLinks.length?(selectedLinks[0].depth?`Represented through containing location: ${path(data,selectedLinks[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.';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();const advanced=q('[data-spatial-advanced]');advanced.href=kind==='maps'?`/Maps?projectId=${position.projectId}&id=${resource}`:`/FloorPlans/Edit/${resource}`;advanced.hidden=!resource;}