diff --git a/PlotLine.Tests/Browser/context-locations-development.cjs b/PlotLine.Tests/Browser/context-locations-development.cjs
new file mode 100644
index 00000000..5e55d59f
--- /dev/null
+++ b/PlotLine.Tests/Browser/context-locations-development.cjs
@@ -0,0 +1,27 @@
+// Real Development forms and persistent fixtures; no mocked reads or writes.
+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 room=await session.create('Locations','?projectId='+project,{LocationName:'Observation room'});
+ const yard=await session.create('Locations','?projectId='+project,{LocationName:'Courtyard'});
+ const book=await session.create('Books','?projectId='+project,{BookTitle:'Directional acceptance',BookNumber:1});
+ const chapter=await session.create('Chapters','?bookId='+book,{ChapterTitle:'Test chapter',ChapterNumber:1});
+ await session.goto('/Scenes/Create?chapterId='+chapter);await p.locator('#SceneTitle').fill('Sight and sound');await p.locator('#PrimaryLocationID').selectOption(String(room));await p.getByRole('button',{name:'Create scene',exact:true}).click();await p.waitForURL('**/Scenes/Edit/*');const scene=Number(new URL(p.url()).pathname.split('/').at(-1));
+ stage='directional relationship form';await session.goto('/Locations/Details/'+room);const form=p.locator('form[action="/Locations/AddRelationship"]');await form.locator('[name=ToLocationID]').selectOption(String(yard));await form.locator('[name=CanSeeMovement]').check();await form.locator('[name=CanHearLoudNoise]').check();await form.locator('[name=IsBidirectional]').check();await form.locator('[name=Notes]').fill('Directional saved evidence');await form.locator('button[type=submit]').click();await p.waitForURL('**/Locations/Details/'+room);
+ stage='recorded character form';const character=await session.create('Characters','?projectId='+project,{CharacterName:'Recorded observer'},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='+scene);await session.post('/Scenes/SaveSceneCharacters',{SceneID:scene,'NewCharacter.CharacterID':character,'NewCharacter.LocationID':room});
+ const feature=`/Writing/Context?projectId=${project}&bookId=${book}&chapterId=${chapter}&sceneId=${scene}&pinned=true`;
+ async function inspect(){await session.goto(feature);await p.selectOption('[data-context-pane="0"] [data-context-tab]','locations');await p.locator('[data-spatial-details] h2').filter({hasText:'Observation room'}).waitFor();}
+ async function verify(){const host=p.locator('[data-spatial-details]');await host.getByRole('heading',{name:'Can see',exact:true}).waitFor();assert.match(await host.textContent(),/Recorded observer/);assert.match(await host.textContent(),/movement: enabled/);assert.match(await host.textContent(),/clear sight: unset \/ not enabled/);assert.match(await host.textContent(),/loud noise: enabled/);assert.match(await host.textContent(),/normal speech: unset \/ not enabled/);assert.equal(await host.getByText('Unknown / unset: no relationship recorded in this direction.',{exact:true}).count(),2);assert.equal(await host.getByRole('link',{name:'Courtyard',exact:true}).count(),2);}
+ stage='live Context direction';await inspect();await verify();
+ stage='main-window navigation';const main=await p.context().newPage();await main.goto('https://dev.plotdirector.com/Locations/Details/'+room);await main.waitForFunction(()=>window.PlotDirectorPresenceConnection?.state==='Connected');const held=p.url();await p.getByRole('link',{name:'Courtyard',exact:true}).first().click();await main.waitForURL('**/Locations/Details/'+yard);assert.equal(p.url(),held);await main.close();
+ stage='split and narrow layout';await p.selectOption('[data-context-layout]','columns');await p.selectOption('[data-context-pane="1"] [data-context-tab]','locations');await p.locator('[data-context-pane="1"] [data-spatial-details]').getByRole('heading',{name:'Can see',exact:true}).waitFor();await p.setViewportSize({width:460,height:850});assert.equal(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),true);await p.setViewportSize({width:1280,height:900});await p.selectOption('[data-context-layout]','single');
+ stage='fresh login persistence';await session.close();session=await open();p=session.page;await inspect();await verify();
+ stage='incoming direction without reciprocity';const state=await p.evaluate(async url=>{const response=await fetch(url,{cache:'no-store'});if(!response.ok)throw Error('State unavailable');return response.json();},`/SpatialContext/State?bookId=${book}&sceneId=${scene}&locationId=${yard}`);assert.equal(state.sensoryRelationships.length,1);assert.equal(state.sensoryRelationships[0].fromLocationID,room);assert.equal(state.sensoryRelationships[0].toLocationID,yard);
+ // Inspect the destination through the existing window-local spatial bus.
+ await p.evaluate(id=>{const root=document.querySelector('[data-context-workspace]');window.PlotDirectorSpatialContext.inspect(root,id,'acceptance');},yard);await p.locator('[data-spatial-details] h2').filter({hasText:'Courtyard'}).waitFor();const host=p.locator('[data-spatial-details]');assert.equal(await host.getByRole('link',{name:'Observation room',exact:true}).count(),2);assert.equal(await host.getByText('Unknown / unset: no relationship recorded in this direction.',{exact:true}).count(),2);
+ console.log(JSON.stringify({passed:true,project,book,scene,checks:['normal relationship and character saves','four directional groups','unset flags','no reciprocal inference despite both-ways flag','recorded presence','split layout','narrow viewport','fresh-login persistence','incoming inspection'],featureUrl:'https://dev.plotdirector.com'+feature}));
+ }catch{console.error('Locations 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.Tests/Browser/context-locations.cjs b/PlotLine.Tests/Browser/context-locations.cjs
new file mode 100644
index 00000000..501eec96
--- /dev/null
+++ b/PlotLine.Tests/Browser/context-locations.cjs
@@ -0,0 +1,11 @@
+// Actual Locations lifecycle in a browser with synthetic read-only data.
+const {chromium}=require('playwright'),assert=require('node:assert/strict');
+(async()=>{const browser=await chromium.launch();try{
+ const page=await browser.newPage();await page.route('https://context.test/**',r=>r.fulfill({contentType:'text/html',body:'
'}));await page.goto('https://context.test/');
+ await page.evaluate(()=>{window.fixture={scope:{projectID:1,bookID:2,sceneID:3,primaryLocationID:10,canEdit:false},scenes:[{position:0,sceneID:3,locationID:10,label:'Current'}],assignments:[{sceneID:3,locationID:10,kind:'Scene location'}],locations:[{locationID:10,locationName:'Room'},{locationID:20,locationName:'Yard'}],characters:[{characterName:'',presenceTypeName:'Mentioned',locationName:null}],sensoryRelationships:[{fromLocationID:10,toLocationID:20,fromLocationName:'Room',toLocationName:'Yard',canSeeMovement:true,canHearLoudNoise:true,isBidirectional:true,notes:'barrier'}],relationships:[],types:[],maps:[],plans:[]};window.fetch=async()=>({ok:true,json:async()=>structuredClone(window.fixture)});document.querySelector('[data-context-workspace]').contextController={windowId:'test',position:{sceneId:3}};});
+ await page.addScriptTag({path:'PlotLine/wwwroot/js/context-spatial.js'});await page.evaluate(()=>PlotDirectorContextLifecycles.spatial.mount(document.querySelector('[data-spatial-context]'),{position:{projectId:1,bookId:2,sceneId:3},windowId:'test',paneId:'0'}));
+ const host=page.locator('[data-spatial-details]');await host.getByRole('heading',{name:'Can see',exact:true}).waitFor();assert.equal(await host.locator('script,b').count(),0);assert.match(await host.textContent(),/Mentioned · Location unknown \/ unset/);assert.equal(await host.getByText('Unknown / unset: no relationship recorded in this direction.',{exact:true}).count(),2);assert.equal(await host.getByRole('link',{name:'Yard',exact:true}).count(),2);assert.match(await host.textContent(),/movement: enabled/);assert.match(await host.textContent(),/clear sight: unset \/ not enabled/);
+ await page.evaluate(()=>PlotDirectorSpatialContext.inspect(document.querySelector('[data-context-workspace]'),20,'test'));await host.locator('h2').filter({hasText:'Yard'}).waitFor();assert.equal(await host.getByRole('link',{name:'Room',exact:true}).count(),2);assert.equal(await host.getByText('Unknown / unset: no relationship recorded in this direction.',{exact:true}).count(),2);
+ await page.evaluate(()=>{window.fixture.scope.primaryLocationID=null;window.fixture.assignments=[];window.fixture.characters=[];window.fixture.sensoryRelationships=[];PlotDirectorContextLifecycles.spatial.onInvalidation(document.querySelector('[data-spatial-context]'),{kind:'locations'});});await host.getByText('Unknown / unset: no scene characters recorded.',{exact:true}).waitFor();assert.equal(await host.getByText('Unknown / unset: no relationship recorded in this direction.',{exact:true}).count(),4);
+ console.log('PASS Locations lifecycle: incoming/outgoing asymmetry, no both-ways inference, unset flags/placements/presence, literal author text and main-window-compatible links');
+ }finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});
diff --git a/PlotLine/Services/Context/ContextSpatial.cs b/PlotLine/Services/Context/ContextSpatial.cs
index e85538a6..f20670c1 100644
--- a/PlotLine/Services/Context/ContextSpatial.cs
+++ b/PlotLine/Services/Context/ContextSpatial.cs
@@ -25,16 +25,21 @@ public sealed record SpatialMapLink(int LocationID,int ResourceID,string Name,Gu
public sealed record SpatialPlanLink(int ResourceID,string Name,int LocationID,int? FloorID,int? BlockID);
public sealed class SpatialCatalog {public int ID{get;set;}public string Name{get;set;}="";public string? Kind{get;set;}public int Revision{get;set;}public DateTime ModifiedDate{get;set;}public int? LocationID{get;set;}public string? Version{get;set;}}
public sealed record SpatialRelation(int ID,int FromLocationID,int ToLocationID,string FromName,string ToName,string TypeName,string? Notes);
+public sealed record SpatialCharacter(int CharacterID, string CharacterName, string? PresenceTypeName, int? LocationID, string? LocationName);
public sealed record SpatialVersion(int ID,string Version);
public sealed record SpatialFragment(string Kind,SpatialScope Scope);
-public sealed record SpatialDocument(SpatialScope Scope,SpatialScene[] Scenes,SpatialAssignment[] Assignments,SpatialLocation[] Locations,SpatialMapLink[] Maps,SpatialPlanLink[] Plans,SpatialCatalog[] MapCatalog,SpatialCatalog[] PlanCatalog,SpatialRelation[] Relationships,object[] Types);
+public sealed record SpatialDocument(SpatialScope Scope,SpatialScene[] Scenes,SpatialAssignment[] Assignments,SpatialLocation[] Locations,SpatialMapLink[] Maps,SpatialPlanLink[] Plans,SpatialCatalog[] MapCatalog,SpatialCatalog[] PlanCatalog,SpatialRelation[] Relationships,object[] Types)
+{
+ public LocationRelationship[] SensoryRelationships { get; init; } = [];
+ public SpatialCharacter[] Characters { get; init; } = [];
+}
public sealed record SpatialMutation(int BookID,int SceneID,string Kind,int? LocationID,int? ResourceID,string? GeometryID,string Expected,double? X=null,double? Y=null,bool Replace=false);
public sealed record SpatialMutationResult(int ProjectID,string Kind,int? ResourceID,string? GeometryID,string Version,string? Previous,bool Changed);
public sealed record SpatialReceipt(int User,SpatialMutation Target,string Previous,DateTime Expires);
public sealed record SpatialCreation(int BookID,int SceneID,string Name,int? ParentID,string? Expected=null,int? PlanID=null,string? BlockID=null,bool Replace=false);
public sealed record SpatialFloorCanvas(FloorPlanEditorViewModel Model,SpatialVersion[] Versions);
-public sealed class ContextSpatial(ISqlConnectionFactory connections,ICurrentUserService user,IDataProtectionProvider protection,ContextWorkspaceNotifications notifications)
+public sealed class ContextSpatial(ISqlConnectionFactory connections,ICurrentUserService user,IDataProtectionProvider protection,ContextWorkspaceNotifications notifications, ILocationRepository locationRepository, ICharacterRepository characters)
{
private int Author=>user.UserId??throw new UnauthorizedAccessException();
private IDataProtector Protector=>protection.CreateProtector("Context.Spatial.Undo.v1");
@@ -46,7 +51,16 @@ public sealed class ContextSpatial(ISqlConnectionFactory connections,ICurrentUse
{
using var db=connections.CreateConnection();using var data=await db.QueryMultipleAsync("dbo.SpatialContext_Read",new{UserID=Author,BookID=book,SceneID=scene,InspectID=inspect},commandType:CommandType.StoredProcedure);
var scope=await data.ReadSingleAsync();var scenes=(await data.ReadAsync()).ToArray();var assignments=(await data.ReadAsync()).ToArray();var locations=(await data.ReadAsync()).ToArray();var maps=(await data.ReadAsync()).ToArray();var plans=(await data.ReadAsync()).ToArray();var mapCatalog=(await data.ReadAsync()).ToArray();var planCatalog=(await data.ReadAsync()).ToArray();var relationships=(await data.ReadAsync()).ToArray();var types=(await data.ReadAsync()).Select(LocationWorkspaceIcons.Presentation).ToArray();
- return new(scope,scenes,assignments,locations,maps,plans,mapCatalog,planCatalog,relationships,types);
+ data.Dispose();
+ // Reuse canonical readers after authorising the manuscript position; only active
+ // endpoints in this project may contribute relationship labels or sensory flags.
+ var selected = inspect ?? scope.PrimaryLocationID;
+ var active = (await locationRepository.ListByProjectAsync(scope.ProjectID)).Where(x => !x.IsArchived).Select(x => x.LocationID).ToHashSet();
+ var sensory = selected.HasValue && active.Contains(selected.Value)
+ ? (await locationRepository.ListRelationshipsByLocationAsync(selected.Value)).Where(x => !x.IsArchived && active.Contains(x.FromLocationID) && active.Contains(x.ToLocationID)).ToArray()
+ : [];
+ var present = (await characters.ListSceneCharactersAsync(scene)).Where(x => x.ProjectID == scope.ProjectID).Select(x => new SpatialCharacter(x.CharacterID, x.CharacterName, x.PresenceTypeName, x.LocationID.HasValue && active.Contains(x.LocationID.Value) ? x.LocationID : null, x.LocationID.HasValue && active.Contains(x.LocationID.Value) ? x.LocationName : null)).ToArray();
+ return new(scope,scenes,assignments,locations,maps,plans,mapCatalog,planCatalog,relationships,types) { SensoryRelationships = sensory, Characters = present };
}
private async Task Apply(IDbConnection db,SpatialMutation input,IDbTransaction? transaction=null,string? previous=null)
{
diff --git a/PlotLine/wwwroot/js/context-spatial.js b/PlotLine/wwwroot/js/context-spatial.js
index d283830d..4fcc1d4f 100644
--- a/PlotLine/wwwroot/js/context-spatial.js
+++ b/PlotLine/wwwroot/js/context-spatial.js
@@ -39,7 +39,27 @@
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 locationSummary(host){
+ const section=el('section');section.append(el('h3','Current scene locations'));
+ const assigned=data.assignments.filter(a=>a.sceneID===data.scope.sceneID);
+ if(!assigned.length)section.append(el('p','Unknown / unset: no scene location or recorded placements.'));
+ for(const a of assigned){const name=path(data,a.locationID);section.append(name?btn(`${name} · ${a.kind}`,()=>select(a.locationID)):el('p',`Unavailable location · ${a.kind}`));}
+ section.append(el('h3','Recorded scene characters'));
+ if(!data.characters?.length)section.append(el('p','Unknown / unset: no scene characters recorded.'));
+ for(const c of data.characters||[])section.append(el('p',`${c.characterName} · ${c.presenceTypeName||'Presence unknown / unset'} · ${c.locationPath||c.locationName||'Location unknown / unset'}`));
+ section.append(el('p','Character records describe saved scene participation; they do not establish precise positions or witness knowledge.','small muted'));host.append(section);
+ }
+ function sensoryDetails(host,location){
+ const section=el('section');section.append(el('h3','Visibility and audibility'));
+ section.append(el('p','Saved direction is From → To: the From location can see or hear the To location when the corresponding flag is enabled. Potential sight or sound does not establish what a character witnessed. Reverse flags are not inferred, including from a travel “both ways” setting.','small muted'));
+ for(const [label,outgoing,flags] of [['Can see',true,['canSeeMovement','canSeeClearly']],['Can be seen from',false,['canSeeMovement','canSeeClearly']],['Can hear',true,['canHearNormalSpeech','canHearLoudNoise']],['Can be heard from',false,['canHearNormalSpeech','canHearLoudNoise']]]){
+ section.append(el('h4',label));const rows=(data.sensoryRelationships||[]).filter(r=>outgoing?r.fromLocationID===id(location):r.toLocationID===id(location));
+ if(!rows.length)section.append(el('p','Unknown / unset: no relationship recorded in this direction.'));
+ for(const r of rows){const other=outgoing?r.toLocationID:r.fromLocationID,name=outgoing?r.toLocationName:r.fromLocationName,line=el('div');const link=el('a',name);link.href=`/Locations/Details/${other}`;line.append(link,el('span',` · ${flags.map(f=>`${({canSeeMovement:'movement',canSeeClearly:'clear sight',canHearNormalSpeech:'normal speech',canHearLoudNoise:'loud noise'})[f]}: ${r[f]===true?'enabled':'unset / not enabled'}`).join(' · ')}`));if(r.notes)line.append(el('p',r.notes));section.append(line);}
+ }
+ section.append(el('p','Unset flags do not prove that seeing or hearing is impossible.','small muted'));host.append(section);
+ }
+ function details(){const host=q('[data-spatial-details]');host.replaceChildren();const current=data.scope,location=data.locations.find(l=>id(l)===selection);const actions=el('div',null,'spatial-toolbar');if(current.canEdit)actions.append(btn(`Change current scene location`,chooseAssignment),btn('New location for current scene',()=>createLocation(true,null)));host.append(actions);locationSummary(host);if(!location){sensoryDetails(host,location);host.append(el('p',selection?'The assigned or inspected location is unavailable. Choose an active location explicitly; the recorded assignment has not been changed.':'This scene has no assigned location. Inspect adjacent scenes or explicitly choose a location.'));if(current.canEdit){host.append(btn('Create new location for current scene',()=>createLocation(true,null)));for(const adjacent of data.scenes.filter(s=>s.position!==0&&s.locationID))host.append(btn(`Use ${adjacent.position<0?'previous':'next'} scene location`,()=>assign(adjacent.locationID)));}return;}const header=el('h2',location.locationName);header.prepend(icon(data,location));draggable(header,id(location));host.append(header,el('p',`${location.locationTypeName||'Unclassified'} · ${location.classification||'Unclassified'}`));const trail=el('nav',null,'spatial-path');trail.setAttribute('aria-label','Containing locations');for(const a of ancestors(data,id(location)).reverse())trail.append(btn(a.locationName,()=>select(id(a))));host.append(trail);const description=el('div',location.description||'No description recorded.','spatial-description');host.append(description);if(current.canEdit){const tools=el('div',null,'spatial-toolbar');tools.append(btn('Edit description',()=>edit('description',location)),btn('Rename',()=>edit('name',location)),btn('Type',()=>discrete('type',location)),btn('Classification',()=>discrete('classification',location)),btn('Create child',()=>createLocation(false,id(location))));host.append(tools);}const links=el('div',null,'spatial-toolbar');for(const [label,url]of [['Location Details',`/Locations/Details/${id(location)}`],['Edit Location',`/Locations/Edit/${id(location)}`]]){const a=el('a',label);a.href=url;links.append(a);}host.append(links);sensoryDetails(host,location);const children=data.locations.filter(l=>l.parentLocationID===id(location));if(children.length){const section=el('details');section.open=preferences.children!==false;section.append(el('summary',`Contained locations (${location.childCount})`));section.ontoggle=()=>{preferences.children=section.open;save();};for(const child of children)section.append(btn(child.locationName,()=>select(id(child))));if(location.childCount>children.length)section.append(el('small',`Showing ${children.length} immediate locations. Open Locations for the complete directory.`));host.append(section);}if(data.relationships.length){const section=el('details');section.append(el('summary','Recorded relationships'));for(const r of data.relationships)section.append(el('p',`${r.fromName} · ${r.typeName} · ${r.toName}${r.notes?' — '+r.notes:''}`));host.append(section);}const spatial=el('div',null,'spatial-toolbar');for(const tool of ['maps','floorplans']){const found=resolution(data,id(location),tool);spatial.append(btn(`Show ${tool==='maps'?'map':'floor plan'}${found.some(f=>f.depth)?' (containing location)':''}`,()=>showTool(tool)));if(tool==='maps'&¤t.canEdit&&!found.some(f=>f.depth===0))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&&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();}
diff --git a/PlotLine/wwwroot/js/context-workspace.js b/PlotLine/wwwroot/js/context-workspace.js
index 1796afec..345a659d 100644
--- a/PlotLine/wwwroot/js/context-workspace.js
+++ b/PlotLine/wwwroot/js/context-workspace.js
@@ -126,7 +126,7 @@
const affectedPanels = {
overview:['overview'], maps:['maps'], floorplans:['floorplans'], locations:['overview','locations','maps','floorplans'],
spatial:['locations','maps','floorplans'], names:['names'],
- characters:['overview','characters','relationships','names','maps','floorplans'],
+ characters:['overview','characters','relationships','names','locations','maps','floorplans'],
relationships:['overview','characters','relationships'],
dates:['overview','calendar'], intent:['overview','intent'],
plotlines:['overview','intent','plotlines','threads'], threads:['overview','intent','threads'],