diff --git a/PlotLine.Tests/Browser/context-floorplans-development.cjs b/PlotLine.Tests/Browser/context-floorplans-development.cjs new file mode 100644 index 00000000..44c45e73 --- /dev/null +++ b/PlotLine.Tests/Browser/context-floorplans-development.cjs @@ -0,0 +1,31 @@ +// Ordinary Development writer, real saved records, scoped 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(); + stage='locations';const places=[];for(const name of ['Study','Hall','Kitchen','Upstairs'])places.push(await session.create('Locations','?projectId='+project,{LocationName:name}));const [a,b,c,d]=places; + const book=await session.create('Books','?projectId='+project,{BookTitle:'Floor acceptance',BookNumber:1}),chapter=await session.create('Chapters','?bookId='+book,{ChapterTitle:'Rooms',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('In study',a),second=await scene('Upstairs',d); + for(const [name,place] of [['Recorded Guest',a],['Unlocated Guest',null]]){const who=await session.create('Characters','?projectId='+project,{CharacterName:name},async page=>{const field=page.locator('[name=CustomSex]');if(await field.count()&&await field.isEnabled())await field.fill('Unspecified');});await session.goto('/Scenes/SceneCharactersEditor?sceneId='+first);await session.post('/Scenes/SaveSceneCharacters',{SceneID:first,'NewCharacter.CharacterID':who,...(place?{'NewCharacter.LocationID':place}:{})});} + stage='floor plan forms';await session.goto('/FloorPlans?projectId='+project);await p.locator('[name=Name]').fill('Acceptance house');await p.locator('[name=LocationID]').selectOption(String(a));await p.locator('form[action="/FloorPlans/Create"] button[type=submit]').click();await p.waitForURL('**/FloorPlans/Edit/*');const plan=Number(new URL(p.url()).pathname.split('/').at(-1)); + for(const [name,order]of [['Ground',0],['Upper',1]]){await session.post('/FloorPlans/AddFloor',{FloorPlanID:plan,Name:name,SortOrder:order,GridWidth:18,GridHeight:14});} + await session.goto('/FloorPlans/Edit/'+plan);const floors=await p.locator('[data-floor-panel]').evaluateAll(ns=>ns.map(n=>Number(n.dataset.floorPanel)));assert.equal(floors.length,2); + for(const [i,place] of places.entries()){await session.post('/FloorPlans/AddBlock',{floorPlanId:plan,FloorPlanFloorID:floors[i===3?1:0],LocationID:place,X:i===1?7:1,Y:i===2?7:1,WidthCells:5,HeightCells:4,BlockType:'Room'});} + async function relationship(from,to,flags,id){await session.goto('/Locations/Details/'+from);const type=await p.locator('#LocationRelationshipTypeID option').evaluateAll(ns=>ns.find(n=>Number(n.value)>0)?.value);assert.ok(type);await session.post('/Locations/AddRelationship',{ProjectID:project,FromLocationID:from,ToLocationID:to,LocationRelationshipTypeID:type,...(id?{LocationRelationshipID:id}:{}),...flags});} + stage='saved directional relationships';await relationship(a,b,{CanSeeMovement:true});await relationship(a,c,{CanHearNormalSpeech:true});await relationship(b,a,{CanSeeClearly:true,CanHearLoudNoise:true}); + const feature=`/Writing/Context?projectId=${project}&bookId=${book}&chapterId=${chapter}&sceneId=${first}&pinned=true`,ctx=await p.context().newPage();await ctx.goto('https://dev.plotdirector.com'+feature);await ctx.selectOption('[data-context-pane="0"] [data-context-tab]','floorplans');const room=place=>ctx.locator(`[data-block][data-location-id="${place}"]`); + stage='scene floor, read-only and whereabouts';await room(a).waitFor();await ctx.waitForFunction(a=>document.querySelector(`[data-block][data-location-id="${a}"]`)?.classList.contains('spatial-selected'),a);assert.equal(await ctx.locator('[data-spatial-floor]').inputValue(),String(floors[0]));assert.equal(await ctx.locator('[data-spatial-place]').count(),0);assert.equal(await ctx.locator('.spatial-character-marker').count(),1);assert.match(await ctx.locator('[data-spatial-characters]').textContent(),/Unlocated Guest.*Location unknown/);assert.equal(await ctx.getByLabel('Visibility',{exact:true}).isChecked(),false);assert.equal(await ctx.getByLabel('Audibility',{exact:true}).isChecked(),false); + const posts=[];ctx.on('request',r=>{if(r.method()==='POST')posts.push(new URL(r.url()).pathname);});const focus=await ctx.evaluate(()=>({...document.querySelector('[data-context-workspace]').contextController.position})); + stage='overlays and direction';await ctx.getByLabel('Visibility',{exact:true}).check();await ctx.getByLabel('Audibility',{exact:true}).check();await ctx.waitForFunction(b=>document.querySelector(`[data-location-id="${b}"].spatial-visible`),b);assert.equal(await room(c).evaluate(n=>n.classList.contains('spatial-audible')),true);await room(b).click();await ctx.waitForFunction(a=>document.querySelector(`[data-location-id="${a}"].spatial-both`),a);assert.equal(await room(c).evaluate(n=>n.classList.contains('spatial-audible')),false); + stage='floor browsing and zoom';await ctx.locator('[data-spatial-floor]').selectOption(String(floors[1]));await ctx.locator('[data-spatial-zoom=in]').click();const view=await ctx.locator('[data-spatial-floor-world]').evaluate(n=>n.style.transform);assert.deepEqual(await ctx.evaluate(()=>({...document.querySelector('[data-context-workspace]').contextController.position})),focus);assert.deepEqual(posts,[]); + stage='held plan save refresh';await ctx.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected');const old=await ctx.locator('[data-spatial-floor-canvas]').elementHandle();await session.goto('/FloorPlans/Edit/'+plan);await session.post('/FloorPlans/SavePlan',{FloorPlanID:plan,ProjectID:project,LocationID:a,Name:'Acceptance house saved'});await ctx.waitForFunction(n=>!n.isConnected,old);await ctx.locator('[data-spatial-resource] option').filter({hasText:'Acceptance house saved'}).waitFor({state:'attached'});assert.equal(await ctx.locator('[data-spatial-floor]').inputValue(),String(floors[1]));assert.equal(await ctx.locator('[data-spatial-floor-world]').evaluate(n=>n.style.transform),view);assert.equal(await room(b).evaluate(n=>n.classList.contains('spatial-selected')),true); + stage='held relationship save refresh';await ctx.locator('[data-spatial-floor]').selectOption(String(floors[0]));await room(a).click();await ctx.waitForFunction(b=>document.querySelector(`[data-location-id="${b}"].spatial-visible`),b);await session.goto('/Locations/Details/'+a);const relation=await p.evaluate(async ({book,first,a,b})=>{const data=await(await fetch(`/SpatialContext/State?bookId=${book}&sceneId=${first}&locationId=${a}`)).json();return data.sensoryRelationships.find(r=>r.fromLocationID===a&&r.toLocationID===b).locationRelationshipID;},{book,first,a,b});assert.ok(relation);await relationship(a,b,{CanSeeMovement:true,CanHearLoudNoise:true},relation);await ctx.waitForFunction(b=>document.querySelector(`[data-location-id="${b}"].spatial-both`),b); + stage='scene following';await ctx.selectOption('[data-context-scene]',String(second));await ctx.waitForFunction(d=>document.querySelector(`[data-location-id="${d}"].spatial-selected`),d);assert.equal(await ctx.locator('[data-spatial-floor]').inputValue(),String(floors[1])); + stage='split themes and narrow';await ctx.selectOption('[data-context-layout]','columns');await ctx.selectOption('[data-context-pane="1"] [data-context-tab]','floorplans');await ctx.locator('[data-context-pane="1"] [data-spatial-floor-canvas]').waitFor();for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue'])await ctx.evaluate(t=>{localStorage.setItem('plotdirector.applicationTheme',t);window.dispatchEvent(new StorageEvent('storage',{key:'plotdirector.applicationTheme',newValue:t}));},theme);await ctx.setViewportSize({width:460,height:850});assert.equal(await ctx.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),true); + stage='main editor navigation';await session.goto('/Locations/Details/'+a);await p.waitForFunction(()=>window.PlotDirectorPresenceConnection?.state==='Connected');const url=ctx.url();await ctx.locator('[data-context-pane="0"] [data-spatial-advanced]').click();await p.waitForURL('**/FloorPlans/Edit/'+plan+'*');assert.equal(ctx.url(),url); + await session.close();session=await open();p=session.page;stage='fresh login persistence';await session.goto(feature);await p.selectOption('[data-context-pane="0"] [data-context-tab]','floorplans');await p.locator('[data-spatial-resource] option').filter({hasText:'Acceptance house saved'}).waitFor({state:'attached'});await p.getByLabel('Visibility',{exact:true}).check();await p.getByLabel('Audibility',{exact:true}).check();await p.waitForFunction(b=>document.querySelector(`[data-location-id="${b}"].spatial-both`),b); + console.log(JSON.stringify({passed:true,checks:['saved scene floor and room','explicit room initials and unknown presence list','default-off directional visibility/audibility/both','read-only local browsing preserves focus','held plan and relationship saves refresh preserving selection floor viewport','scene follows floor','split narrow and seven themes','main editor navigation','fresh-login server persistence'],featureUrl:'https://dev.plotdirector.com'+feature})); + }catch(error){console.error('Floor Plans acceptance failed at '+stage+' ('+error.name+'); 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-spatial.cjs b/PlotLine.Tests/Browser/context-spatial.cjs index 4e2d21ee..a802ceb7 100644 --- a/PlotLine.Tests/Browser/context-spatial.cjs +++ b/PlotLine.Tests/Browser/context-spatial.cjs @@ -9,17 +9,23 @@ step='locations';const t=Date.now();await page.selectOption(tab(0),'locations'); step='adjacent inspection';await pane(0).locator('[data-scene-position="-1"] button').click();await pane(0).getByRole('heading',{name:'Lounge',exact:true}).waitFor();assert.equal(await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),22);await pane(0).getByRole('button',{name:'Return to scene location'}).click(); step='maps renderer';await page.selectOption(tab(0),'maps');await pane(0).locator('iframe').waitFor();await page.waitForFunction(()=>document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.document.features.length===2);await page.waitForTimeout(150);const frame=page.frames().find(f=>f.url().includes('/SpatialContext/Map'));assert.equal(await frame.locator('.spatial-map-ring').count(),3);await shot('02-maps-single');await frame.locator('[data-feature-id="21111111-2222-4333-8444-555555555555"]').first().click();await pane(0).getByText('No associated location; inspection does not assign this feature to a scene.',{exact:true}).waitFor();assert.match(await pane(0).locator('[data-spatial-advanced]').getAttribute('href'),/featureId=21111111-2222-4333-8444-555555555555/);assert.equal(await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),22);await pane(0).locator('[data-spatial-resource]').selectOption('2');await pane(0).getByText('No authoritative representation of the inspected location on this resource.',{exact:true}).waitFor();assert.match(await pane(0).locator('[data-spatial-advanced]').getAttribute('href'),/id=2$/);await pane(0).locator('[data-spatial-resource]').selectOption('1');await pane(0).getByText('Represented through containing location:',{exact:false}).waitFor(); step='floor renderer';await page.selectOption(tab(0),'floorplans');await pane(0).locator('[data-block="51"]').waitFor();assert.equal(await pane(0).locator('.spatial-room-badge').count(),3);await shot('03-floorplans-single'); +step='directional overlays and explicit whereabouts'; +await page.route('**/SpatialContext/State?*',async route=>{const response=await route.fetch(),d=await response.json();d.characters=[{characterID:1,characterName:'Recorded Guest',locationID:103},{characterID:2,characterName:'Unknown Guest'},{characterID:3,characterName:'House Guest',locationID:102}];d.sensoryRelationships=[{fromLocationID:103,toLocationID:104,canSeeMovement:true},{fromLocationID:103,toLocationID:105,canHearNormalSpeech:true},{fromLocationID:104,toLocationID:103,canSeeClearly:true,canHearLoudNoise:true}];return route.fulfill({json:d});}); +await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({projectId:7,bookId:12,kind:'locations'})); +await pane(0).locator('.spatial-character-marker').waitFor();assert.equal(await pane(0).locator('.spatial-character-marker').count(),1);assert.equal(await pane(0).locator('.spatial-visible,.spatial-audible,.spatial-both').count(),0); +await pane(0).getByLabel('Visibility',{exact:true}).check();await pane(0).getByLabel('Audibility',{exact:true}).check();assert.equal(await pane(0).locator('[data-block="52"].spatial-visible').count(),1);assert.equal(await pane(0).locator('[data-block="53"].spatial-audible').count(),1);assert.equal(await pane(0).locator('[data-block="51"].spatial-selected').count(),1); +await pane(0).locator('[data-block="52"]').click();await pane(0).locator('[data-block="51"].spatial-both').waitFor();assert.equal(await pane(0).locator('[data-block="53"].spatial-audible').count(),0);assert.equal(await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),22); +await pane(0).getByRole('button',{name:'Return to scene location'}).click();await pane(0).locator('[data-block="51"].spatial-selected').waitFor();await page.unroute('**/SpatialContext/State?*'); step='split dedup and coordination';await page.selectOption('[data-context-layout]','columns');await page.selectOption(tab(0),'locations');await page.selectOption(tab(1),'maps');await pane(1).locator('iframe').waitFor();await page.waitForTimeout(200);await shot('04-locations-maps');await pane(0).locator('.spatial-path button').filter({hasText:'The old house'}).click();await pane(0).getByRole('heading',{name:'The old house',exact:true}).waitFor();await pane(1).locator('[data-spatial-resolution]').filter({hasText:'Directly associated'}).waitFor(); step='locations floor';await page.selectOption(tab(1),'floorplans');await pane(1).locator('[data-block="51"]').waitFor();await shot('05-locations-floorplans');await pane(1).locator('[data-block="52"]').click();await pane(0).getByRole('heading',{name:'Lounge',exact:true}).waitFor(); step='metadata refresh retains chosen level and viewport';await pane(1).locator('[data-spatial-floor]').selectOption('42');const oldFloorCanvas=await pane(1).locator('[data-spatial-floor-canvas]').elementHandle(),savedTransform=await pane(1).locator('[data-spatial-floor-world]').evaluate(n=>n.style.transform);await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({projectId:7,bookId:12,kind:'locations'}));await page.waitForFunction(node=>!node.isConnected,oldFloorCanvas);assert.equal(await pane(1).locator('[data-spatial-floor]').inputValue(),'42');assert.equal(await pane(1).locator('[data-spatial-floor-world]').evaluate(n=>n.style.transform),savedTransform);await pane(1).locator('[data-spatial-floor]').selectOption('41'); step='maps floor';await page.selectOption(tab(0),'maps');await pane(0).locator('iframe').waitFor();await page.waitForTimeout(100);await shot('06-maps-floorplans');await page.selectOption('[data-context-layout]','rows');await shot('07-stacked'); step='same building retains renderer and viewport';await page.evaluate(()=>{window.spatialFrame=document.querySelector('[data-context-pane="0"] iframe');spatialFrame.contentWindow.PlotDirectorMapWorkspace.setView({x:-250,y:-200,w:900,h:600});document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:24});});await pane(0).locator('[data-scene-position="0"] button').filter({hasText:'Lounge'}).waitFor();assert.equal(await page.evaluate(()=>window.spatialFrame===document.querySelector('[data-context-pane="0"] iframe')),true);assert.equal(await page.evaluate(()=>window.spatialFrame.contentWindow.PlotDirectorMapWorkspace.view.w),900);await shot('10-repeated-location');await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:22}));await pane(0).locator('[data-scene-position="0"] button').filter({hasText:'Bedroom'}).waitFor(); -step='paragraph no loading';const before=requests.length;await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:22,paragraphId:'a-paragraph'}));await page.waitForTimeout(100);assert.equal(requests.length,before); +step='paragraph no loading';await pane(1).locator('[data-block="51"].spatial-selected').waitFor();const before=requests.length;await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:22,paragraphId:'a-paragraph'}));await page.waitForTimeout(100);assert.equal(requests.length,before); step='active edit stays pinned';await page.selectOption('[data-context-layout]','columns');await page.selectOption(tab(0),'locations');await pane(0).getByRole('button',{name:'Edit description'}).click();await pane(0).locator('textarea').fill('Unsaved author draft');await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:23}));assert.equal(await pane(0).locator('textarea').inputValue(),'Unsaved author draft');assert.equal(await pane(0).locator('[data-spatial-context]').getAttribute('data-scene-id'),'22');for(const close of await page.locator('[data-toast-host] button').all())await close.click();await pane(0).getByRole('button',{name:'Cancel',exact:true}).click();await pane(0).getByText('This scene has no assigned location.',{exact:false}).waitFor();await shot('15-unassigned'); step='read-only map browsing';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();await page.selectOption(tab(1),'maps');await pane(1).locator('iframe').waitFor();await page.waitForFunction(()=>document.querySelector('[data-context-pane="1"] iframe')?.contentWindow?.PlotDirectorMapWorkspace?.document.features.length===2);assert.equal(await pane(1).locator('[data-spatial-place]').count(),0);assert.equal(await pane(0).getByRole('link',{name:'Place in Maps',exact:true}).count(),1);let attempted;await page.route('**/SpatialContext/Mutate',route=>{attempted=route.request().postDataJSON();return route.fulfill({status:409,json:{message:'Synthetic concurrent change; previous geometry retained.'}});});const mapFrame=page.frames().find(f=>f.url().includes('/SpatialContext/Map'));await mapFrame.locator('#mapsCanvas').click({position:{x:100,y:100}});assert.equal(attempted,undefined);assert.equal(await mapFrame.evaluate(()=>PlotDirectorMapWorkspace.mode),'explore');await shot('13-read-only-map'); step='native cross-pane map drop is ignored';const dragSource=await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).boundingBox(),dropTarget=await mapFrame.locator('#mapsCanvas').boundingBox();await page.mouse.move(dragSource.x+30,dragSource.y+10);await page.mouse.down();await page.mouse.move(dragSource.x+60,dragSource.y+12,{steps:5});await page.mouse.move(dropTarget.x+100,dropTarget.y+100,{steps:25});await page.mouse.up();assert.equal(await pane(1).getByRole('button',{name:'Confirm',exact:true}).count(),0);assert.equal(attempted,undefined);assert.equal(await mapFrame.evaluate(()=>PlotDirectorMapWorkspace.document.features.length),2); -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='floor inspection is read-only';await page.selectOption(tab(1),'floorplans');await pane(1).locator('[data-block="52"]').waitFor();await pane(1).locator('[data-block="52"]').click();assert.equal(await pane(1).locator('[data-spatial-place]').count(),0);assert.equal(await pane(1).getByRole('button',{name:'Associate existing location',exact:true}).count(),0);assert.equal(attempted,undefined); 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);} diff --git a/PlotLine/Views/Writing/_ContextSpatial.cshtml b/PlotLine/Views/Writing/_ContextSpatial.cshtml index fc30dc20..dc7476f3 100644 --- a/PlotLine/Views/Writing/_ContextSpatial.cshtml +++ b/PlotLine/Views/Writing/_ContextSpatial.cshtml @@ -8,8 +8,8 @@

Loading recorded locations…

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

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

} diff --git a/PlotLine/wwwroot/css/context-spatial.css b/PlotLine/wwwroot/css/context-spatial.css index 69297ced..285d8bbd 100644 --- a/PlotLine/wwwroot/css/context-spatial.css +++ b/PlotLine/wwwroot/css/context-spatial.css @@ -8,3 +8,12 @@ .spatial-floor-viewport .floor-plan-resize-handle{display:none} .spatial-renderer-page [data-feature-id].spatial-map-background{opacity:.45} + +/* Sensory potential uses border patterns as well as theme colours. */ +.spatial-floor-viewport .spatial-visible{outline:4px dotted var(--bs-info-text-emphasis,var(--plotline-ink));outline-offset:3px} +.spatial-floor-viewport .spatial-audible{outline:4px dashed var(--bs-warning-text-emphasis,var(--plotline-ink));outline-offset:3px} +.spatial-floor-viewport .spatial-both{outline:5px double var(--bs-success-text-emphasis,var(--plotline-ink));outline-offset:3px} +.spatial-floor-viewport .spatial-selected{outline:4px solid var(--bs-primary);outline-offset:3px} +.spatial-character-marker{display:inline-flex;position:relative;z-index:9;align-items:center;justify-content:center;min-width:24px;height:24px;border:1px solid var(--plotline-ink);border-radius:50%;background:var(--plotline-surface);color:var(--plotline-ink);font-size:11px;margin:2px} +.context-spatial [data-spatial-characters]{max-height:8rem;overflow:auto;flex:none} +.spatial-sensory-legend{padding:.25rem;max-width:55rem} diff --git a/PlotLine/wwwroot/js/context-spatial.js b/PlotLine/wwwroot/js/context-spatial.js index 59351bba..6b91e666 100644 --- a/PlotLine/wwwroot/js/context-spatial.js +++ b/PlotLine/wwwroot/js/context-spatial.js @@ -14,7 +14,7 @@ function path(data,location){return ancestors(data,location).reverse().map(l=>l.locationName).join(' / ');} function resolution(data,location,kind){const links=kind==='maps'?data.maps:data.plans;for(const [depth,l]of ancestors(data,location).entries()){const found=links.filter(x=>x.locationID===id(l)&&(kind!=='maps'||x.isPlaced));if(found.length)return found.map(link=>({...link,depth,represented:id(l)})).sort((a,b)=>Number(!!b.blockID)-Number(!!a.blockID)||Number(!!b.floorID)-Number(!!a.floorID));}return [];} function icon(data,location){const t=data.types.find(t=>t.assignable!==false&&String(t.value)===String(location?.locationTypeID??''));const n=el('span',null,`spatial-type text-${t?.tone||'secondary'}`);if(t?.path){const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('aria-hidden','true');const p=document.createElementNS(svg.namespaceURI,'path');p.setAttribute('d',t.path);p.setAttribute('fill',t.filled?'currentColor':'none');svg.append(p);n.append(svg);}n.title=t?.label||'Unclassified';return n;} - function mount(node,context){if(instances.has(node))return;const root=node.closest('[data-context-workspace]'),bus=session(root),kind=node.dataset.spatialContext,abort=new AbortController();let position=context.position,data,selection,loadedInspection,epoch=0,disposed=false,busy=false,resource=null,renderer=null,floorSnapshot=null,operation=null,undo=null; + function mount(node,context){if(instances.has(node))return;const root=node.closest('[data-context-workspace]'),bus=session(root),kind=node.dataset.spatialContext,abort=new AbortController();let position=context.position,data,selection,loadedInspection,epoch=0,disposed=false,busy=false,resource=null,renderer=null,floorSnapshot=null,floorRoom=null,visibility=false,audibility=false,operation=null,undo=null; const q=s=>node.querySelector(s),status=q('[data-spatial-status]'),error=q('[data-spatial-error]'),canvas=q('[data-spatial-canvas]'); const pref=`plotdirector.spatial.v1.${root.dataset.user}.${context.windowId}.${position.projectId}.${kind}`;let preferences={};try{preferences=JSON.parse(localStorage.getItem(pref))||{};}catch{} const save=()=>{try{localStorage.setItem(pref,JSON.stringify(preferences));}catch{}}; @@ -62,30 +62,45 @@ 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();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 draw(){if(!data||disposed)return;error.textContent='';scenes();if(kind!=='locations')mapCharacters();if(kind==='maps')q('[data-spatial-feature]').replaceChildren();q('[data-spatial-return]').disabled=selection===data.scope.primaryLocationID;q('[data-spatial-return]').onclick=()=>select(data.scope.primaryLocationID);if(kind==='locations'){details();return;}const options=catalog(),links=relevant(),available=new Set(links.map(l=>l.resourceID));const preferred=kind==='maps'?Number(preferences.resource):0;const next=resource&&options.some(x=>x.id===resource)?resource:available.has(preferred)?preferred:links[0]?.resourceID||resource&&options.some(x=>x.id===resource)&&resource||null;const menu=q('[data-spatial-resource]');menu.replaceChildren(new Option('Choose existing resource',''),...options.map(r=>new Option(r.name,String(r.id))));menu.value=next||'';menu.onchange=()=>{resource=Number(menu.value)||null;preferences.resource=resource;save();void renderResource();};q('[data-spatial-resolution]').textContent=resourceCaption(next);if(resource!==next){resource=next;void renderResource();}else if(renderer){if(renderer.revision!==String(catalog().find(c=>c.id===resource)?.modifiedDate)){void renderResource();}else highlight();}else void renderResource();updateAdvanced();} function updateAdvanced(){const advanced=q('[data-spatial-advanced]');const represented=resolution(data,selection,kind).find(l=>l.resourceID===resource);advanced.href=kind==='maps'?`/Maps?projectId=${position.projectId}&id=${resource}${represented?.featureID?'&featureId='+encodeURIComponent(represented.featureID):''}`:`/FloorPlans/Edit/${resource}${represented?.blockID?'?selectedBlockId='+represented.blockID:''}`;advanced.hidden=!resource;} function resourceCaption(target=resource){const found=resolution(data,selection,kind).filter(x=>x.resourceID===target);return found.length?(found[0].depth?`Represented through containing location: ${path(data,found[0].represented)}. This is not an exact position for the inspected location.`:'Directly associated with the inspected location.'):'No authoritative representation of the inspected location on this resource.';} function mapCharacters(){ const host=q('[data-spatial-characters]');host.replaceChildren(el('h3','Recorded scene characters')); for(const c of data.characters||[]){const location=c.locationID?data.locations.find(l=>id(l)===c.locationID):null;const row=el('p');row.append(el('span',`${c.characterName} · ${c.presenceTypeName||'Presence unknown / unset'} · `));row.append(location?btn(path(data,c.locationID),()=>select(c.locationID)):el('span',c.locationName||'Location unknown / unset'));host.append(row);} if(!data.characters?.length)host.append(el('p','Unknown / unset: no scene characters recorded.')); - host.append(el('p','Only saved character locations are shown. Scene participation alone does not establish whereabouts. Containing geography is not a precise position.','small muted')); + host.append(el('p',kind==='floorplans'?'Initials mark only a uniquely associated, explicitly saved room. Other characters remain in this presence list; positions within rooms are unknown.':'Only saved character locations are shown. Scene participation alone does not establish whereabouts. Containing geography is not a precise position.','small muted')); } function sceneHighlights(){const grouped=new Map();for(const s of data.scenes){const found=resolution(data,s.locationID,kind).filter(l=>l.resourceID===resource);for(const f of found){const key=kind==='maps'?f.featureID:f.blockID;if(!key)continue;if(!grouped.has(key))grouped.set(key,{featureID:key,roles:[],label:[]});const value=grouped.get(key);value.roles.push(s.position);value.label.push(`${['Previous','Current','Next'][s.position+1]}: ${path(data,s.locationID)}${f.depth?' (containing location)':''}`);}}if(kind==='maps')for(const c of data.characters||[]){if(!c.locationID)continue;for(const f of resolution(data,c.locationID,kind).filter(l=>l.resourceID===resource)){if(!grouped.has(f.featureID))grouped.set(f.featureID,{featureID:f.featureID,roles:[],label:[]});const value=grouped.get(f.featureID);value.roles.push(0);value.label.push(`${c.characterName}: ${c.locationName||path(data,c.locationID)}${f.depth?' (containing location; exact position unknown)':''}`);}}return [...grouped.values()].map(x=>({...x,label:x.label.join(' · ')}));} function annotate(){if(kind==='locations'||!data)return;for(const scene of data.scenes){const row=q(`[data-scene-position="${scene.position}"]`);if(!row)continue;row.querySelector('.spatial-elsewhere')?.remove();const resolved=resolution(data,scene.locationID,kind),here=resolved.filter(l=>l.resourceID===resource);let label='';if(scene.locationID){if(!resolved.length)label=kind==='maps'?'No mapped representation':'No associated plan';else if(!here.length)label=kind==='maps'?'On another map':'On another plan';else if(kind==='floorplans'&&here.every(l=>l.floorID&&l.floorID!==renderer?.getFloor?.()))label='On another level';else if(kind==='floorplans'&&!here.some(l=>l.blockID))label='Plan available; no associated room';else if(here.some(l=>l.depth))label='Containing location represented';}if(label)row.append(el('small',label,'spatial-elsewhere'));}} function highlight(){if(!renderer)return;annotate();renderer.highlight(sceneHighlights());const target=resolution(data,selection,kind).find(x=>x.resourceID===resource);if(renderer.selection!==selection){renderer.selection=selection;if(target){if(kind==='floorplans'&&!target.blockID&&target.floorID)renderer.floor?.(target.floorID);else renderer.centre(kind==='maps'?target.featureID:target.blockID,false);}}} async function renderResource(){if(!canvas)return;updateAdvanced();q('[data-spatial-feature]').replaceChildren();q('[data-spatial-resolution]').textContent=resourceCaption();const item=catalog().find(c=>c.id===resource);if(!item){renderer?.dispose();renderer=null;canvas.replaceChildren(el('p',`No suitable ${kind==='maps'?'map':'floor plan'} is associated. Choose an existing resource above or open the main World workspace.`));return;}if(kind==='maps'&&renderer?.id===resource){renderer.revision=String(item.modifiedDate);renderer.command('reload');return;}if(kind==='floorplans'&&renderer)floorSnapshot={id:renderer.id,floor:renderer.getFloor?.(),selection:renderer.selection};renderer?.dispose();renderer=null;canvas.replaceChildren();const target=resource,scope={...position};if(kind==='maps'){const frame=el('iframe');frame.title='Context map';frame.src=`/SpatialContext/Map?bookId=${scope.bookId}&sceneId=${scope.sceneId}&id=${target}`;const channel=crypto.randomUUID();let features=[],map,ready=false;const command=(action,args={})=>frame.contentWindow?.postMessage({type:'plotdirector.spatial.command',channel,action,...args},location.origin);const receive=e=>{if(e.origin!==location.origin||e.source!==frame.contentWindow||e.data?.channel!==channel||e.data.type!=='plotdirector.spatial.renderer')return;const m=e.data;if(m.action==='ready'){features=m.features;map=m.map;ready=true;highlight();}if(m.action==='viewport'){preferences.views??={};preferences.views[target]=m.view;save();}if(m.action==='select'&&m.feature)void(async()=>{if(m.feature.locationID)await select(m.feature.locationID);if(disposed||renderer?.id!==target)return;const detail=q('[data-spatial-feature]');detail.replaceChildren(el('strong',m.feature.name),el('small',m.feature.locationID?'Associated story location':'No associated location; inspection does not assign this feature to a scene.'));if(m.feature.notes)detail.append(el('p',m.feature.notes));q('[data-spatial-advanced]').href=`/Maps?projectId=${position.projectId}&id=${target}&featureId=${encodeURIComponent(m.feature.featureID)}`;})().catch(fail);if(m.action==='error')fail(Error(m.message));};window.addEventListener('message',receive);renderer={id:target,revision:String(item.modifiedDate),command,highlight:items=>command('highlight',{highlights:items}),centre:(id,force)=>{if(ready)command('centre',{id,force});},fit:()=>command('fit',{ids:sceneHighlights().map(h=>h.featureID)}),zoom:factor=>command('zoom',{factor}),features:()=>features,map:()=>map,dispose:()=>window.removeEventListener('message',receive)};frame.onload=()=>command('init',{view:preferences.views?.[target]});canvas.append(frame);}else{const request=++epoch;try{const response=await fetch(`/SpatialContext/Floor?bookId=${scope.bookId}&sceneId=${scope.sceneId}&id=${target}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error('Floor plan unavailable.');const html=await response.text();if(disposed||request!==epoch||resource!==target)return;canvas.innerHTML=html;renderer=floorRenderer(canvas,item);if(floorSnapshot?.id===item.id){renderer.floor?.(floorSnapshot.floor);renderer.selection=floorSnapshot.selection;}highlight();}catch(e){fail(e);}}} - function floorRenderer(host,item){const container=host.querySelector('[data-spatial-floor-canvas]'),world=container.querySelector('[data-spatial-floor-world]'),viewport=container.querySelector('.spatial-floor-viewport'),level=container.querySelector('[data-spatial-floor]'),versions=JSON.parse(container.querySelector('[data-room-versions]').textContent);const engine=window.PlotDirectorFloorPlanRenderer.create(container);let view={x:0,y:0,scale:1},drag=null;const panels=[...container.querySelectorAll('[data-floor-panel]')],blocks=[...container.querySelectorAll('[data-block]')];const signal=new AbortController();function current(){return panels.find(p=>p.dataset.floorPanel===level.value);}function transform(){world.style.transform=`translate(${view.x}px,${view.y}px) scale(${view.scale})`;preferences.floorViews??={};preferences.floorViews[`${item.id}/${level.value}`]={...view};save();}function fit(){const grid=current()?.querySelector('[data-floor-grid]');if(!grid)return;const w=grid.offsetWidth||Number(grid.dataset.gridWidth)*34,h=grid.offsetHeight||Number(grid.dataset.gridHeight)*34;view={scale:Math.min((viewport.clientWidth-24)/w,(viewport.clientHeight-24)/h,1.5),x:12,y:12};transform();}function change(){preferences.floorLevels??={};preferences.floorLevels[item.id]=level.value;save();queueMicrotask(annotate);if(!current()){viewport.replaceChildren(el('p','This plan has no floors yet. Open Floor Plans to add a level.'));return;}for(const p of panels)p.classList.toggle('active',p===current());const visibleBlocks=engine.refreshSharedWalls(current());engine.refreshHiddenLocationStyles(visibleBlocks);engine.positionTransitions(current(),visibleBlocks);view=preferences.floorViews?.[`${item.id}/${level.value}`]||{x:0,y:0,scale:1};transform();if(!preferences.floorViews?.[`${item.id}/${level.value}`])fit();}level.onchange=change;function centre(blockId,force){const block=blocks.find(b=>Number(b.dataset.block)===Number(blockId));if(!block)return;const panel=block.closest('[data-floor-panel]');if(level.value!==panel.dataset.floorPanel){level.value=panel.dataset.floorPanel;change();}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});} + function floorRenderer(host,item){const container=host.querySelector('[data-spatial-floor-canvas]'),world=container.querySelector('[data-spatial-floor-world]'),viewport=container.querySelector('.spatial-floor-viewport'),level=container.querySelector('[data-spatial-floor]'),versions=JSON.parse(container.querySelector('[data-room-versions]').textContent);const engine=window.PlotDirectorFloorPlanRenderer.create(container);let view={x:0,y:0,scale:1},drag=null;const panels=[...container.querySelectorAll('[data-floor-panel]')],blocks=[...container.querySelectorAll('[data-block]')];const signal=new AbortController();function current(){return panels.find(p=>p.dataset.floorPanel===level.value);}function transform(){world.style.transform=`translate(${view.x}px,${view.y}px) scale(${view.scale})`;preferences.floorViews??={};preferences.floorViews[`${item.id}/${level.value}`]={...view};save();}function fit(){const grid=current()?.querySelector('[data-floor-grid]');if(!grid)return;const w=grid.offsetWidth||Number(grid.dataset.gridWidth)*34,h=grid.offsetHeight||Number(grid.dataset.gridHeight)*34;view={scale:Math.min((viewport.clientWidth-24)/w,(viewport.clientHeight-24)/h,1.5),x:12,y:12};transform();}function change(){preferences.floorLevels??={};preferences.floorLevels[item.id]=level.value;save();queueMicrotask(annotate);if(!current()){viewport.replaceChildren(el('p','This plan has no floors yet. Open Floor Plans to add a level.'));return;}for(const p of panels)p.classList.toggle('active',p===current());const visibleBlocks=engine.refreshSharedWalls(current());engine.refreshHiddenLocationStyles(visibleBlocks);engine.positionTransitions(current(),visibleBlocks);view=preferences.floorViews?.[`${item.id}/${level.value}`]||{x:0,y:0,scale:1};transform();if(!preferences.floorViews?.[`${item.id}/${level.value}`])fit();}level.onchange=change;function centre(blockId,force){const block=blocks.find(b=>Number(b.dataset.block)===Number(blockId));if(!block)return;const panel=block.closest('[data-floor-panel]');if(level.value!==panel.dataset.floorPanel){level.value=panel.dataset.floorPanel;change();}floorRoom=Number(block.dataset.block);decorate();if(force){const x=block.offsetLeft,y=block.offsetTop;view.x=viewport.clientWidth/2-(x+block.offsetWidth/2)*view.scale;view.y=viewport.clientHeight/2-(y+block.offsetHeight/2)*view.scale;transform();}} + const overlays=el('div',null,'spatial-toolbar spatial-sensory-controls'); + for(const [label,key] of [['Visibility','visibility'],['Audibility','audibility']]){const wrap=el('label'),input=el('input');input.type='checkbox';input.checked=key==='visibility'?visibility:audibility;input.onchange=()=>{if(key==='visibility')visibility=input.checked;else audibility=input.checked;decorate();};wrap.append(input,document.createTextNode(label));overlays.append(wrap);} + const legend=el('p','Selected room: solid outline · Visible: dotted · Audible: dashed · Both: double. From selected room → highlighted room only; reverse relationships are not inferred. Unset flags do not prove impossibility.','small spatial-sensory-legend');container.prepend(overlays,legend); + function decorate(){ + const selected=blocks.find(b=>Number(b.dataset.block)===floorRoom),location=Number(selected?.dataset.locationId); + for(const b of blocks){const target=Number(b.dataset.locationId);let see=false,hear=false; + for(const r of data.sensoryRelationships||[])if(r.fromLocationID===location&&r.toLocationID===target){see ||= visibility&&(r.canSeeMovement===true||r.canSeeClearly===true);hear ||= audibility&&(r.canHearNormalSpeech===true||r.canHearLoudNoise===true);} + b.classList.toggle('spatial-selected',b===selected);b.classList.toggle('spatial-visible',b!==selected&&see&&!hear);b.classList.toggle('spatial-audible',b!==selected&&hear&&!see);b.classList.toggle('spatial-both',b!==selected&&see&&hear);b.setAttribute('aria-pressed',String(b===selected)); + b.querySelectorAll('.spatial-character-marker').forEach(n=>n.remove()); + // A marker identifies an explicitly saved room, never an inferred coordinate or containing room. + const peers=blocks.filter(other=>Number(other.dataset.locationId)===target); + if(target&&peers.length===1)for(const c of data.characters||[])if(c.locationID===target){const marker=el('span',c.characterName.trim().split(/\s+/).slice(0,2).map(n=>Array.from(n)[0]).join(''),'spatial-character-marker');marker.title=`${c.characterName} · recorded room; position within room unknown`;marker.setAttribute('aria-label',marker.title);b.append(marker);} + } + } + for(const b of blocks){b.tabIndex=0;b.setAttribute('role','button');b.setAttribute('aria-label',b.textContent.trim());b.addEventListener('click',()=>{if(drag?.moved)return;floorRoom=Number(b.dataset.block);decorate();const location=Number(b.dataset.locationId);if(location)void select(location);showRoom(b);},{signal:signal.signal});b.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();b.click();}},{signal:signal.signal});} + viewport.addEventListener('wheel',e=>{e.preventDefault();const r=viewport.getBoundingClientRect(),x=e.clientX-r.left,y=e.clientY-r.top,scale=Math.max(.08,Math.min(4,view.scale*Math.exp(-e.deltaY*.001)));view.x=x-(x-view.x)*scale/view.scale;view.y=y-(y-view.y)*scale/view.scale;view.scale=scale;transform();},{passive:false,signal:signal.signal});viewport.addEventListener('pointerdown',e=>{if(e.button!==0)return;drag={x:e.clientX,y:e.clientY,vx:view.x,vy:view.y,moved:false};if(!e.target.closest('[data-block]'))viewport.setPointerCapture(e.pointerId);},{signal:signal.signal});viewport.addEventListener('pointermove',e=>{if(!drag||!viewport.hasPointerCapture(e.pointerId))return;drag.moved=Math.hypot(e.clientX-drag.x,e.clientY-drag.y)>4;view.x=drag.vx+e.clientX-drag.x;view.y=drag.vy+e.clientY-drag.y;transform();},{signal:signal.signal});viewport.addEventListener('pointerup',e=>{if(viewport.hasPointerCapture(e.pointerId))viewport.releasePointerCapture(e.pointerId);setTimeout(()=>drag=null,0);},{signal:signal.signal}); - function showRoom(b){const feature=q('[data-spatial-feature]');feature.replaceChildren(el('span',`Room: ${b.textContent.trim()}`));if(data.scope.canEdit)feature.append(btn('Associate existing location',async()=>{const chosen=await picker('Associate existing location with this room',Number(b.dataset.locationId));if(chosen!==undefined&&chosen!==null)await associateRoom(b,chosen);}),btn('Create location and associate',()=>{const version=versions.find(v=>v.id===Number(b.dataset.block));return createLocation(false,data.planCatalog.find(p=>p.id===resource)?.locationID,{id:Number(b.dataset.block),version:version.version});}));} - async function associateRoom(b,location){if(busy)throw Error('Finish or cancel the current operation first.');if(Number(b.dataset.locationId)===location)return;const version=versions.find(v=>v.id===Number(b.dataset.block));const old=Number(b.dataset.locationId);const target={bookID:position.bookId,sceneID:position.sceneId,kind:'room',locationID:location,resourceID:item.id,geometryID:b.dataset.block,expected:version.version,replace:!!old};await confirmOperation(`Replace the recorded room association? Geometry and location parents will stay unchanged. Connected transition identities must be reviewed in the main editor.`,async()=>finish(await post('/SpatialContext/Mutate',target)));} - 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()}; + function showRoom(b){const feature=q('[data-spatial-feature]');feature.replaceChildren(el('span',`Room: ${b.getAttribute('aria-label')}`),el('small','Read-only inspection. Character markers identify recorded rooms; positions within rooms are unknown. Open Floor Plans for editing.'));q('[data-spatial-advanced]').href=`/FloorPlans/Edit/${item.id}?selectedBlockId=${b.dataset.block}`;} + + if(panels.some(p=>p.dataset.floorPanel===preferences.floorLevels?.[item.id]))level.value=preferences.floorLevels[item.id];change();return {id:item.id,revision:String(item.modifiedDate),blocks,showRoom,highlight:items=>{decorate();for(const b of blocks){b.querySelectorAll('.spatial-room-badge').forEach(n=>n.remove());b.classList.remove('spatial-position-0','spatial-position-1','spatial-position-2');const h=items.find(h=>Number(h.featureID)===Number(b.dataset.block));if(h){h.roles.forEach(r=>b.classList.add(`spatial-position-${r+1}`));b.append(el('span',h.roles.map(r=>['Previous','Current','Next'][r+1]).join(' · '),'spatial-room-badge'));b.title=h.label;b.setAttribute('aria-description',h.label);}}},centre,fit,getFloor:()=>Number(level.value),floor:id=>{if(panels.some(p=>Number(p.dataset.floorPanel)===id)){level.value=String(id);change();}},zoom:factor=>{view.scale=Math.max(.08,Math.min(4,view.scale*factor));transform();},dispose:()=>signal.abort()}; } async function confirmOperation(message,commit){if(busy)throw Error('Finish or cancel the current operation first.');const target={...position};const panel=q('[data-spatial-operation]');panel.hidden=false;panel.replaceChildren(el('p',message));guard(true);panel.append(btn('Confirm',async()=>{try{if(await commit(target)!=='continue')clearOperation();}catch(e){fail(e);}}),btn('Cancel',clearOperation));} - 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;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(); + instances.set(node,{position(next){if(busy)return false;if(kind!=='locations'&&position.sceneId!==next.sceneId){resource=null;floorRoom=null;floorSnapshot=null;}position=next;void reload();return true;},invalidate(hint){if(busy)return false;if(kind==='floorplans'&&renderer&&(hint.kinds||[hint.kind]).some(k=>['floorplans','locations','spatial',undefined].includes(k)))renderer.revision=null;invalidateCache();void reload();return true;},dispose(){disposed=true;epoch++;bus.listeners.delete(listener);renderer?.dispose();abort.abort();},busy:()=>busy});void reload(); } window.PlotDirectorContextLifecycles??={};window.PlotDirectorContextLifecycles.spatial={mount,onCacheInvalidation:invalidateCache,dispose:node=>{instances.get(node)?.dispose();instances.delete(node);},canRefresh:node=>!instances.get(node)?.busy(),onPosition:(node,next)=>instances.get(node)?.position(next)===true,onInvalidation:(node,hint)=>instances.get(node)?.invalidate(hint)===true}; window.PlotDirectorSpatialContext=Object.freeze({ancestors,resolution,path,subscribe(root,listener){const s=session(root);s.listeners.add(listener);return()=>s.listeners.delete(listener);},inspect(root,location,source){if(location!==null&&(!Number.isSafeInteger(location)||location<=0))throw TypeError('A canonical location identifier is required.');session(root).select(location,source);}});