feat(context): integrate scene locations maps and floor plans

This commit is contained in:
Nick Beckley 2026-11-27 16:52:53 +00:00
parent c059f3b2a6
commit 01757170c7
30 changed files with 1151 additions and 472 deletions

View File

@ -0,0 +1,41 @@
# Spatial Context
Locations, Maps and Floor Plans are independently loadable Scene-scoped Context tools. The unified parent retains window identity, two panes, layout, divider, preferences, effective manuscript focus, Hold/Follow and the single native-companion SignalR connection. It supplies generic lifecycle `onPosition` and `onInvalidation` hooks, guarded pane closing and an explicit-destination `openTool` contract. No spatial business logic belongs in the parent.
## Read contract
`ContextSpatial` calls the forward-only migration 339 procedures through Dapper. `SpatialContext_Scope` authorises an active scene/book/project; the three-scene read uses `NarrativeSceneOrder.BookSceneIndex ± 1`, within one book. Empty chapters do not introduce synthetic scenes. `Scenes.PrimaryLocationID` remains the primary assignment. Recorded character/asset/occupancy positions remain separately labelled and never supply a missing primary.
The response includes the three scenes' assigned locations, cycle-safe same-project ancestors, at most forty immediate children of the inspected location, relevant explicit associations, lightweight resource catalogues, relationships and canonical taxonomy presentation. It does not load manuscript paragraphs or the whole location directory. The shared hierarchical picker loads its directory only when invoked.
Direct associations win. Otherwise the nearest active containing location with an authoritative association supplies candidates. Room/block associations take precedence among floor-plan associations at the same depth. Equal candidates prefer coverage of adjacent scenes; an author's still-relevant resource choice is retained. Inherited positions are expressly labelled as containing locations, never exact child positions. No associations are inferred from matching names.
## Local selection and refresh
`context-spatial.js` owns one session per Context root in the current browser window. Its selection message contains location ID, source pane and monotonic revision. It is neither stored nor broadcast. Other visible spatial panes inspect the same location; selecting an ordinary map feature or room never calls manuscript navigation or scene assignment. Future tools such as Assets can call `PlotDirectorSpatialContext.subscribe(contextRoot, handler)` and retain the returned unsubscribe callback for disposal. `inspect(contextRoot, canonicalLocationId, sourceId)` publishes inspection only. Version 1 messages carry location, source, revision, Context window ID and project/book scope; consumers must retain these isolation rules and never treat inspection as an assignment command.
State requests are shared by book, scene and inspected location, with a bounded cache; stale response epochs are ignored. Paragraph movement does not invoke Scene-scoped lifecycle updates. Visible tools handle relevant invalidations themselves; inactive tools remain stale without loading. Location changes retain renderers when resource revisions are unchanged. Resource and viewport preferences use author/window/project/tool/resource keys in local storage. Transient placement and inspection selection are never persisted.
## Renderers
Maps uses the existing Maps Razor template and `maps-workspace.js` renderer in an authorised same-origin renderer-only iframe. Its minimal layout has no SignalR or native focus scripts. Editor controls stay hidden; explore mode provides canonical geometry, surrounding features, backgrounds, wheel zoom and pan. The channel/source/origin-checked bridge adds ephemeral combined P/C/N rings and explicit placement coordinates. It cannot save geometry. The main Maps route now validates optional `featureId` before revealing a feature.
Floor Plans shares `_FloorPlanStage`, `FloorPlanPresentation` and `floor-plan-renderer.js` with the main editor. Original wall segmentation, transitions, hidden-room treatment, geometry and backgrounds remain canonical. Context supplies read-only viewport transforms and ephemeral room badges. Building-level associations do not select an arbitrary room. Editor geometry tools remain in World.
## Explicit mutations
Existing `LocationWorkspace` services handle versioned rename, prose, type and classification edits, protected Undo and child creation. Context scene/marker/plan/room writes use `SpatialContext_Mutate`: project ownership and edit role, active-location validation, transaction, audit and compare-and-swap are enforced server-side. Scene assignment targets the explicitly labelled current scope scene. Atomic create-and-assign rolls back location creation if assignment fails.
Marker placement inserts an existing location's canonical marker. Duplicate representations are rejected. Repositioning requires explicit confirmation and an unlocked marker; complex geometry stays in Maps. Map revision protects both mutation and Undo. Undo removes only the created marker or restores its original placement.
Room association uses the canonical block's LocationID and a full-row SHA-256 version, read with geometry under repeatable-read isolation. Plan association uses a full-row version. Neither operation changes geometry or location containment. Replacements require confirmation. Persisted changes emit existing lightweight Context invalidations and user-bound, expiring protected Undo receipts. Held windows still receive persisted changes.
Active operations report shared dirty/busy state; tab changes and pane closure are blocked, scene changes defer that pane's refresh, and operation targets remain pinned. Explicit Save/Cancel protects description drafts. Closing the browser warns about active operations.
## Boundaries and limitations
Canonical floor-plan blocks require a location ID; there is no separate unassociated-room store. A block can be deliberately reassociated, but Context rejects replacement if recorded floor transitions reference the old or proposed location. Doors/windows use those identities; their reconciliation belongs in the main editor. This preserves transitions rather than creating a competing association model.
Immediate child exploration is bounded to forty entries; open Locations for a larger directory. Advanced boundaries, snapping, smoothing, walls, furniture and architectural construction remain in the main World editors. No routing, geocoding, name inference, AI requests or automatic story-data mutations are introduced.
Physical Windows/Word verification and installed PWA results must be recorded separately from synthetic focus tests in the delivery report.

View File

@ -0,0 +1,7 @@
// Creates only disposable, dedicated-author fixtures through normal authenticated endpoints.
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-'));assert(identity.ProjectID&&identity.BookID);assert(!identity.SpatialFixture);const base='https://dev.plotdirector.com';
(async()=>{const browser=await chromium.launch();try{const page=await browser.newPage({viewport:{width:1440,height:1000}});await page.goto(base+'/Account/Login');await page.locator('#Email').fill(identity.Email);await page.locator('#Password').fill(identity.Password);await Promise.all([page.waitForURL('**/Projects'),page.locator('form button[type=submit]').click()]);await page.goto(base+`/Locations?projectId=${identity.ProjectID}`);await page.locator('[data-location-records][aria-busy=false]').waitFor();let token=await page.locator('[name=__RequestVerificationToken]').first().inputValue();async function json(route,body){const r=await page.request.post(base+route,{headers:{RequestVerificationToken:token},data:body});if(!r.ok())throw Error(`${route}: ${r.status()} ${(await r.text()).slice(0,200)}`);return r.json();}async function form(route,values){const r=await page.request.post(base+route,{form:{__RequestVerificationToken:token,...Object.fromEntries(Object.entries(values).filter(([k,v])=>v!=null).map(([k,v])=>[k,String(v)]))}});if(!r.ok())throw Error(`${route}: ${r.status()}`);return r;}
const locations=[];for(const [name,parent]of [['Spatial acceptance house',null],['Bedroom',0],['Lounge',0],['Kitchen',0],['Unmapped valley',null]]){const result=await json('/LocationWorkspace/Create',{projectId:identity.ProjectID,name,parentId:parent==null?null:locations[parent]});locations.push(result.id);}const chapters=[];for(const n of [1,2]){await page.goto(base+`/Chapters/Create?bookId=${identity.BookID}`);const defaults=await page.locator('form[action="/Chapters/Save"]').evaluate(f=>Object.fromEntries(new FormData(f)));const r=await form('/Chapters/Save',{...defaults,ChapterID:0,BookID:identity.BookID,ChapterNumber:n,ChapterTitle:`Spatial disposable chapter ${n}`});assert.match(r.url(),/\/Chapters\/Details\/\d+/);chapters.push(Number(new URL(r.url()).pathname.split('/').pop()));}const scenes=[];for(const [index,chapter,title,location]of [[1,chapters[0],'Spatial disposable previous',locations[2]],[1,chapters[1],'Spatial disposable current',locations[1]],[2,chapters[1],'Spatial disposable next',locations[3]]]){await page.goto(base+`/Scenes/Create?chapterId=${chapter}`);const inputs=JSON.parse(fs.readFileSync('/tmp/pd-spatial-lookups.json'));const r=await form('/Scenes/Save',{...inputs,SceneID:0,ChapterID:chapter,SceneNumber:index,SceneTitle:title,PrimaryLocationID:location});assert.match(r.url(),/\/Scenes\/Edit\/\d+/);scenes.push(Number(new URL(r.url()).pathname.split('/').pop()));}
const createdMap=await form('/Maps/Create',{ProjectID:identity.ProjectID,Name:'Spatial disposable town map',Kind:'Region'});const mapId=(await createdMap.json()).id;const mapResponse=await page.request.get(base+`/Maps/State?projectId=${identity.ProjectID}&id=${mapId}`);const document=await mapResponse.json();document.features=[{featureID:crypto.randomUUID(),mapID:mapId,name:'Spatial acceptance house',type:'Custom',geometryClass:'Marker',layer:'Places',x:100,y:80,width:48,height:48,isPlaced:true,isProvisional:false,isLocked:false,showLabel:true,locationID:locations[0],geometryJson:'{}'}];await json('/Maps/Save',document);
const plan=await form('/FloorPlans/Create',{ProjectID:identity.ProjectID,Name:'Spatial disposable house plan',LocationID:locations[0]});assert.match(plan.url(),/\/FloorPlans\/Edit\/\d+/);const planId=Number(new URL(plan.url()).pathname.split('/').pop());await form('/FloorPlans/AddFloor',{FloorPlanID:planId,Name:'Ground floor',SortOrder:0,GridWidth:18,GridHeight:14});await page.goto(base+`/FloorPlans/Edit/${planId}`);const floor=Number(await page.locator('[data-floor-panel]').first().getAttribute('data-floor-panel'));assert(floor);for(const [index,x,y]of [[1,2,2],[2,7,2],[3,2,6]])await form('/FloorPlans/AddBlock',{floorPlanId:planId,FloorPlanFloorID:floor,LocationID:locations[index],X:x,Y:y,WidthCells:5,HeightCells:4,BlockType:'Room'});
identity.SpatialFixture={locations,chapters,scenes,mapId,planId,floor};fs.writeFileSync(file,JSON.stringify(identity,null,2),{mode:0o600});await page.goto(base+`/Writing/Context?projectId=${identity.ProjectID}&bookId=${identity.BookID}&sceneId=${scenes[1]}&pinned=true`);await page.screenshot({path:'/tmp/pd-spatial-evidence/development-before.png'});console.log('PASS dedicated Development spatial fixtures: five locations, two chapters, three scenes, canonical map and floor plan; existing author records untouched.');}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});

View File

@ -0,0 +1,5 @@
// Actual installed Chromium application; synthetic loopback fixtures, no author data.
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
(async()=>{const base='http://127.0.0.1:5238',profile=fs.mkdtempSync('/tmp/pd-spatial-installed-'),context=await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1440,height:1000}}),cdp=await context.browser().newBrowserCDPSession(),manifestId=base+'/Projects';try{
const tab=context.pages()[0];await tab.goto(base+'/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture?page=calendar-test'});await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=context.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:base+'/Writing/Context?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}"]`),tabSelector=i=>`[data-context-pane="${i}"] [data-context-tab]`;await page.selectOption(tabSelector(0),'locations');await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor();await page.selectOption('[data-context-layout]','columns');await page.selectOption(tabSelector(1),'maps');await pane(1).locator('iframe').waitFor();await page.waitForFunction(()=>document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.document.features.length===2);fs.mkdirSync('/tmp/pd-spatial-evidence',{recursive:true});await page.screenshot({path:'/tmp/pd-spatial-evidence/installed-pwa-locations-maps.png'});await page.selectOption(tabSelector(1),'floorplans');await pane(1).locator('[data-block="51"]').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.screenshot({path:`/tmp/pd-spatial-evidence/installed-pwa-${theme}.png`});assert(!await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2));}await page.selectOption('[data-context-layout]','rows');await page.screenshot({path:'/tmp/pd-spatial-evidence/installed-pwa-stacked.png'});assert.deepEqual(errors,[]);console.log('PASS actual installed Chromium PWA: Locations/Maps/Floor Plans, split panes, seven themes, 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;});

View File

@ -0,0 +1,2 @@
const vm=require('node:vm'),fs=require('node:fs'),assert=require('node:assert/strict'),{performance}=require('node:perf_hooks');const window={};vm.runInNewContext(fs.readFileSync('PlotLine/wwwroot/js/context-spatial.js','utf8'),{window});const {resolution,ancestors,path}=window.PlotDirectorSpatialContext;
const data={locations:[{locationID:1,locationName:'Country'},{locationID:2,parentLocationID:1,locationName:'House'},{locationID:3,parentLocationID:2,locationName:'Room'},{locationID:4,parentLocationID:2,locationName:'Other room'}],maps:[{resourceID:10,locationID:1,isPlaced:true},{resourceID:20,locationID:2,isPlaced:true},{resourceID:30,locationID:3,isPlaced:false}],plans:[{resourceID:40,locationID:2},{resourceID:50,locationID:3},{resourceID:60,locationID:3,blockID:99,floorID:11}]};assert.equal(resolution(data,3,'maps')[0].resourceID,20);assert.equal(resolution(data,3,'maps')[0].depth,1);assert.equal(resolution(data,3,'floorplans')[0].blockID,99);assert.equal(resolution(data,3,'floorplans')[0].depth,0);assert.equal(resolution(data,4,'floorplans')[0].resourceID,40);assert.equal(path(data,3),'Country / House / Room');assert.equal(resolution(data,null,'maps').length,0);assert.equal(resolution(data,999,'maps').length,0);data.locations[0].parentLocationID=3;assert.equal(ancestors(data,3).length,3);data.locations[0].parentLocationID=null;data.maps.push({resourceID:70,locationID:3,isPlaced:true});assert.equal(resolution(data,3,'maps')[0].resourceID,70);assert.equal(resolution(data,3,'maps')[0].depth,0);console.log('PASS shared spatial resolver: direct, nearest containing, room precedence, unplaced exclusion, unavailable, cycle safety, no name inference');

View File

@ -0,0 +1,26 @@
// Actual compiled Context fragments and canonical renderers; synthetic fixtures, no database writes.
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238',out=process.env.PD_SPATIAL_EVIDENCE||'/tmp/pd-spatial-evidence';fs.mkdirSync(out,{recursive:true});
(async()=>{const browser=await chromium.launch();let step='setup';try{const context=await browser.newContext({viewport:{width:1440,height:1000}});const errors=[],requests=[];
await context.route('**/native-companion/**',r=>r.fulfill({json:[]}));await context.route('**/SharedFocus/**',r=>r.fulfill({json:{}}));await context.route('**/Writing/Context/Position*',r=>r.fulfill({json:{connected:false}}));await context.route('**/Writing/Context/MyWindows*',r=>r.fulfill({json:[]}));
await context.route('**/Writing/Context/Tabs/*',r=>{const u=new URL(r.request().url());return r.fulfill({contentType:'text/html',body:`<div data-context-tab-fragment data-project-id="7" data-book-id="12" data-chapter-id="${u.searchParams.get('chapterId')}" data-scene-id="${u.searchParams.get('sceneId')}">Existing Context tab</div>`});});
const page=await context.newPage();page.on('pageerror',e=>errors.push(e.message));page.on('request',r=>{if(r.url().includes('/SpatialContext/'))requests.push(r.url());});await page.goto(base+'/Writing/Context?pinned=true');const tab=i=>`[data-context-pane="${i}"] [data-context-tab]`,pane=i=>page.locator(`[data-context-pane="${i}"]`);const shot=async name=>page.screenshot({path:`${out}/${name}.png`});
step='locations';const t=Date.now();await page.selectOption(tab(0),'locations');await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor();const load=Date.now()-t;assert.equal(await pane(0).locator('.spatial-scene').count(),3);await shot('01-locations-single');
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');
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='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='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='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='placement cancellation and rejected write';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);await pane(0).getByRole('button',{name:'Place on map',exact:true}).click();await pane(1).locator('[data-spatial-operation]').filter({hasText:'Place existing location: Bedroom'}).waitFor();await shot('13-map-placement');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}});await pane(1).getByText('Synthetic concurrent change; previous geometry retained.').waitFor();assert.equal(attempted.locationID,103);assert.equal(attempted.sceneID,22);assert.equal(attempted.kind,'map');assert.equal(await mapFrame.evaluate(()=>PlotDirectorMapWorkspace.document.features.length),2);await pane(1).getByRole('button',{name:'Cancel',exact:true}).click();
step='native cross-pane location drop';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();await pane(1).getByRole('button',{name:'Confirm',exact:true}).waitFor();await shot('13-native-cross-pane-drop');await pane(1).getByRole('button',{name:'Cancel',exact:true}).click();
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='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();
assert.deepEqual(errors,[]);fs.writeFileSync(`${out}/results.json`,JSON.stringify({passed:true,locations_initial_ms:load,spatial_requests:requests.length,paragraph_spatial_requests:0,errors},null,2));console.log('PASS spatial Context: actual Razor/renderers, coordinated panes, paragraph stability, pinned edits, seven themes');await browser.close();}catch(e){console.error('FAIL',step,e);await browser.close();process.exitCode=1;}})();

View File

@ -15,6 +15,7 @@ using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
if(args.Contains("--spatial-context-database")){await SpatialContextDatabaseTests.Run(args.Last());return;}
if(args.Contains("--location-taxonomy-fixture")){await LocationsWorkspaceDatabaseTests.ExportTaxonomy(args[^2],args[^1]);return;}
if(args.Contains("--locations-workspace-database")){await LocationsWorkspaceDatabaseTests.Run(args.Last());return;}
if(args.Contains("--shared-focus-concurrent")){await SharedFocusDatabaseTests.Concurrent();return;}

View File

@ -0,0 +1,12 @@
using PlotLine.Models;
using PlotLine.ViewModels;
using PlotLine.Services.Context;
internal static class SpatialContextBrowserFixture
{
public static SpatialScope Scope(int scene=22)=>new(){ProjectID=7,BookID=12,ChapterID=10,SceneID=scene,ChapterTitle="The crossing",SceneTitle="A quiet arrival",ChapterNumber=1,SceneNumber=2,PrimaryLocationID=103,CanEdit=true,Version=new(2026,11,27,12,0,0)};
public static SpatialDocument Data(int scene=22,int? inspect=null){var scope=Scope(scene);var names=new[]{"Aster country","Harbour town","The old house","Bedroom","Lounge","Kitchen","Unmapped garden","Remote valley"};var locations=names.Select((name,i)=>new SpatialLocation{LocationID=100+i,ParentLocationID=i==0||i==7?null:i==1?100:i==2?101:102,LocationName=name,LocationTypeID=i<2?1:4,LocationTypeName=i<2?"Country":"Building",Classification="Fictional",Description=$"Recorded description of {name}.\nThe author uses this space to record atmosphere, entrances and useful details whilst writing.",UpdatedDate=scope.Version,ChildCount=i==0||i==1?1:i==2?4:0}).ToArray();var scenes=new[]{new SpatialScene{Position=-1,SceneID=21,ChapterID=9,ChapterNumber=1,ChapterTitle="Before",SceneNumber=1,SceneTitle="A conversation",LocationID=104},new SpatialScene{Position=0,SceneID=scene,ChapterID=10,ChapterNumber=2,ChapterTitle="Arrival",SceneNumber=1,SceneTitle="The quiet room",LocationID=scene==23?null:scene==24?104:scene==26?107:103},new SpatialScene{Position=1,SceneID=25,ChapterID=10,ChapterNumber=2,SceneNumber=2,SceneTitle="Breakfast",LocationID=105}};scope.PrimaryLocationID=scenes[1].LocationID;
return new(scope,scenes,[],locations,[new(102,1,"Harbour town map",Guid.Parse("11111111-2222-4333-8444-555555555555"),true,"Marker",false)],[new(31,"The old house",102,null,null),new(31,"The old house",103,41,51),new(31,"The old house",104,41,52),new(31,"The old house",105,41,53)],[new(){ID=1,Name="Harbour town map",Kind="Town",Revision=1,ModifiedDate=scope.Version}],[new(){ID=31,Name="The old house",LocationID=102,ModifiedDate=scope.Version,Version="fixture-plan-version"}],[],[PlotLine.Services.LocationWorkspaceIcons.Presentation("1","Country"),PlotLine.Services.LocationWorkspaceIcons.Presentation("4","Building")]);
}
public static MapsViewModel Map(){var map=new StoryMap{MapID=1,ProjectID=7,Name="Harbour town map",Kind="Region",Revision=1};return new(){Project=new(){ProjectID=7},Maps=[map],Document=new(){Map=map,Features=[new(){FeatureID=Guid.Parse("11111111-2222-4333-8444-555555555555"),MapID=1,Name="The old house",LocationID=102,GeometryClass="Marker",Type="Custom",X=100,Y=80,Width=48,Height=48,IsPlaced=true,ShowLabel=true},new(){FeatureID=Guid.Parse("21111111-2222-4333-8444-555555555555"),MapID=1,Name="Woodland",GeometryClass="Area",Type="Forest",X=-150,Y=-100,Width=200,Height=130,IsPlaced=true,ShowLabel=true}]}};}
public static SpatialFloorCanvas Floor()=>new(new(){Project=new(){ProjectID=7},FloorPlan=new(){FloorPlanID=31,ProjectID=7,Name="The old house",LocationID=102},Floors=[new(){FloorPlanFloorID=41,FloorPlanID=31,Name="Ground floor",GridWidth=18,GridHeight=14},new(){FloorPlanFloorID=42,FloorPlanID=31,Name="Upper floor",GridWidth=18,GridHeight=14}],Blocks=[new(){FloorPlanBlockID=51,FloorPlanFloorID=41,LocationID=103,LocationName="Bedroom",BlockType="Room",X=2,Y=2,WidthCells=5,HeightCells=4},new(){FloorPlanBlockID=52,FloorPlanFloorID=41,LocationID=104,LocationName="Lounge",BlockType="Room",X=7,Y=2,WidthCells=6,HeightCells=4},new(){FloorPlanBlockID=53,FloorPlanFloorID=41,LocationID=105,LocationName="Kitchen",BlockType="Room",X=2,Y=6,WidthCells=5,HeightCells=4}],Transitions=[new(){FloorPlanTransitionID=61,FloorPlanFloorID=41,FromLocationID=103,ToLocationID=104,FromLocationName="Bedroom",ToLocationName="Lounge",TransitionType="Door"},new(){FloorPlanTransitionID=62,FloorPlanFloorID=41,FromLocationID=103,ToLocationID=105,FromLocationName="Bedroom",ToLocationName="Kitchen",TransitionType="Archway"}]},[new(51,"fixture-room-51"),new(52,"fixture-room-52"),new(53,"fixture-room-53")]);
}

View File

@ -0,0 +1,53 @@
using System.Data;
using System.Diagnostics;
using System.Text.Json;
using Dapper;
using Microsoft.Data.SqlClient;
using PlotLine.Services.Context;
using PlotLine.Models;
internal static class SpatialContextDatabaseTests
{
public static async Task Run(string configPath){using var config=JsonDocument.Parse(await File.ReadAllTextAsync(configPath));var builder=new SqlConnectionStringBuilder(config.RootElement.GetProperty("connection").GetString());if(builder.DataSource!="192.168.10.10,1433"||!builder.InitialCatalog.StartsWith("PlotDirector_Qualification_SpatialContext",StringComparison.Ordinal))throw new Exception("Disposable spatial clone required.");using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync();var f=await db.QueryFirstAsync<(int UserID,int ProjectID,int BookID,int SceneID)>("SELECT TOP(1) a.UserID,p.ProjectID,b.BookID,s.SceneID FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID=a.ProjectID JOIN dbo.Books b ON b.ProjectID=p.ProjectID JOIN dbo.Chapters c ON c.BookID=b.BookID JOIN dbo.Scenes s ON s.ChapterID=c.ChapterID WHERE a.IsActive=1 AND a.AccessRole='Owner' AND p.IsArchived=0 AND b.IsArchived=0 AND c.IsArchived=0 AND s.IsArchived=0 ORDER BY s.SceneID");var fixture=new{f.UserID,f.ProjectID,f.BookID,f.SceneID};var args=new{fixture.UserID,fixture.BookID,fixture.SceneID};
// All successful fixture mutations and existing clone scene changes roll back together.
using(var tx=db.BeginTransaction()){
var ids=(await db.QueryAsync<int>("DECLARE @ids TABLE(ID int);INSERT dbo.Locations(ProjectID,LocationName) OUTPUT inserted.LocationID INTO @ids VALUES(@ProjectID,N'Spatial fixture house'),(@ProjectID,N'Spatial fixture bedroom'),(@ProjectID,N'Spatial fixture lounge');SELECT ID FROM @ids;",fixture,tx)).ToArray();await db.ExecuteAsync("UPDATE dbo.Locations SET ParentLocationID=@parent WHERE LocationID=@child; UPDATE dbo.Scenes SET PrimaryLocationID=@child WHERE SceneID=@SceneID",new{parent=ids[0],child=ids[1],fixture.SceneID},tx);
var map=await db.ExecuteScalarAsync<int>("INSERT dbo.StoryMaps(ProjectID,Name,Kind) VALUES(@ProjectID,N'Spatial fixture map',N'Region');SELECT CONVERT(int,SCOPE_IDENTITY());",fixture,tx);
async Task<SpatialMutationResult> Change(string kind,int? location,int? resource,string expected,string? geometry=null,double? x=null,double? y=null,bool restore=false,string? previous=null,bool replace=false)=>await db.QuerySingleAsync<SpatialMutationResult>("dbo.SpatialContext_Mutate",new{fixture.UserID,fixture.BookID,fixture.SceneID,Kind=kind,LocationID=location,ResourceID=resource,Expected=expected,GeometryID=geometry,X=x,Y=y,Restore=restore,Previous=previous,Replace=replace},tx,commandType:CommandType.StoredProcedure);
var revision=await db.ExecuteScalarAsync<int>("SELECT Revision FROM dbo.StoryMaps WHERE MapID=@map",new{map},tx);var placed=await Change("map",ids[0],map,revision.ToString(),x:120,y:95);if(!placed.Changed||placed.GeometryID==null)throw new Exception("Placement result missing.");
var timer=Stopwatch.StartNew();using(var rows=await db.QueryMultipleAsync("dbo.SpatialContext_Read",args,tx,commandType:CommandType.StoredProcedure)){
var scope=await rows.ReadSingleAsync<SpatialScope>();var scenes=(await rows.ReadAsync<SpatialScene>()).ToArray();var assignments=(await rows.ReadAsync<SpatialAssignment>()).ToArray();var locations=(await rows.ReadAsync<SpatialLocation>()).ToArray();var maps=(await rows.ReadAsync<SpatialMapLink>()).ToArray();var plans=(await rows.ReadAsync<SpatialPlanLink>()).ToArray();var mapCatalog=(await rows.ReadAsync<SpatialCatalog>()).ToArray();var planCatalog=(await rows.ReadAsync<SpatialCatalog>()).ToArray();var relations=(await rows.ReadAsync<SpatialRelation>()).ToArray();var types=(await rows.ReadAsync<LocationTypeTaxonomyEntry>()).ToArray();if(scope.PrimaryLocationID!=ids[1]||!locations.Any(l=>l.LocationID==ids[0])||!maps.Any(m=>m.LocationID==ids[0]&&m.ResourceID==map)||types.Length<100)throw new Exception("Shared spatial read lost primary, ancestor or canonical taxonomy.");if(scenes.Single(s=>s.Position==0).SceneID!=fixture.SceneID)throw new Exception("Current scene resolution failed.");var expected=(await db.QueryAsync<int>("SELECT n.SceneID FROM dbo.NarrativeSceneOrder n WHERE n.BookID=@BookID AND ABS(n.BookSceneIndex-(SELECT BookSceneIndex FROM dbo.NarrativeSceneOrder WHERE SceneID=@SceneID))<=1 ORDER BY n.BookSceneIndex",fixture,tx)).ToArray();if(!scenes.Select(s=>s.SceneID).SequenceEqual(expected))throw new Exception("Authoritative sequence mismatch.");}
Console.WriteLine($"PASS spatial Dapper projection, authoritative scene order, primary and ancestor resources; {timer.Elapsed.TotalMilliseconds:F1} ms");
var moved=await Change("map",ids[0],map,placed.Version,placed.GeometryID,180,150,replace:true);var undoMove=await Change("map",ids[0],map,moved.Version,moved.GeometryID,restore:true,previous:moved.Previous,replace:true);if(await db.ExecuteScalarAsync<double>("SELECT X FROM dbo.MapFeatures WHERE FeatureID=@id",new{id=Guid.Parse(moved.GeometryID!)},tx)!=120)throw new Exception("Reposition undo failed.");await Change("map",ids[0],map,undoMove.Version,placed.GeometryID,restore:true,previous:placed.Previous);if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.MapFeatures WHERE FeatureID=@id",new{id=Guid.Parse(placed.GeometryID!)},tx)!=0)throw new Exception("Placement undo failed.");
var scopeBefore=await db.QuerySingleAsync<SpatialScope>("dbo.SpatialContext_Scope",args,tx,commandType:CommandType.StoredProcedure);var sceneChange=await Change("scene",ids[2],null,scopeBefore.Version.ToString("O"));await Change("scene",ids[2],null,sceneChange.Version,restore:true,previous:sceneChange.Previous);if(await db.ExecuteScalarAsync<int>("SELECT PrimaryLocationID FROM dbo.Scenes WHERE SceneID=@SceneID",fixture,tx)!=ids[1])throw new Exception("Scene assignment Undo failed.");
var plan=await db.ExecuteScalarAsync<int>("INSERT dbo.FloorPlans(ProjectID,Name,LocationID) VALUES(@ProjectID,N'Spatial fixture plan',@location);SELECT CONVERT(int,SCOPE_IDENTITY());",new{fixture.ProjectID,location=ids[0]},tx);var floor=await db.ExecuteScalarAsync<int>("INSERT dbo.FloorPlanFloors(FloorPlanID,Name) VALUES(@plan,N'Ground');SELECT CONVERT(int,SCOPE_IDENTITY());",new{plan},tx);var block=await db.ExecuteScalarAsync<int>("INSERT dbo.FloorPlanBlocks(FloorPlanFloorID,LocationID,X,Y,WidthCells,HeightCells) VALUES(@floor,@location,2,3,4,5);SELECT CONVERT(int,SCOPE_IDENTITY());",new{floor,location=ids[1]},tx);var roomVersion=(await db.QueryAsync<SpatialVersion>("dbo.SpatialContext_RoomVersions",new{fixture.UserID,fixture.BookID,fixture.SceneID,PlanID=plan},tx,commandType:CommandType.StoredProcedure)).Single(v=>v.ID==block);var room=await Change("room",ids[2],plan,roomVersion.Version,block.ToString(),replace:true);await Change("room",ids[2],plan,room.Version,block.ToString(),restore:true,previous:room.Previous,replace:true);if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.FloorPlanBlocks WHERE FloorPlanBlockID=@block AND LocationID=@location AND X=2 AND Y=3 AND WidthCells=4 AND HeightCells=5",new{block,location=ids[1]},tx)!=1)throw new Exception("Room association touched geometry or failed Undo.");var planVersion=await db.ExecuteScalarAsync<string>("SELECT CONVERT(varchar(64),HASHBYTES('SHA2_256',(SELECT p.* FOR JSON PATH,INCLUDE_NULL_VALUES)),2) FROM dbo.FloorPlans p WHERE FloorPlanID=@plan",new{plan},tx);var reassociated=await Change("plan",ids[2],plan,planVersion??throw new Exception("Plan version missing."),replace:true);await Change("plan",ids[2],plan,reassociated.Version,restore:true,previous:reassociated.Previous,replace:true);if(await db.ExecuteScalarAsync<int>("SELECT LocationID FROM dbo.FloorPlans WHERE FloorPlanID=@plan",new{plan},tx)!=ids[0])throw new Exception("Plan association Undo failed.");
Console.WriteLine("PASS explicit scene assignment, map placement/reposition, room/plan association and exact Undo; geometry unchanged");
var deep=await db.ExecuteScalarAsync<int>("DECLARE @i int=0,@parent int=@root;WHILE @i<500 BEGIN INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@ProjectID,CONCAT(N'Spatial deep ',@i),@parent);SET @parent=SCOPE_IDENTITY();SET @i+=1;END;SET @i=0;WHILE @i<1000 BEGIN INSERT dbo.Locations(ProjectID,LocationName) VALUES(@ProjectID,CONCAT(N'Spatial unrelated root ',@i));SET @i+=1;END;SELECT @parent;",new{fixture.ProjectID,root=ids[0]},tx);await db.ExecuteAsync("UPDATE dbo.Scenes SET PrimaryLocationID=@deep WHERE SceneID=@SceneID",new{deep,fixture.SceneID},tx);var deepTime=Stopwatch.StartNew();using(var rows=await db.QueryMultipleAsync("dbo.SpatialContext_Read",args,tx,commandType:CommandType.StoredProcedure)){await rows.ReadAsync();await rows.ReadAsync();await rows.ReadAsync();var relevant=(await rows.ReadAsync<SpatialLocation>()).ToArray();if(relevant.Length>550||relevant.Length<501||relevant.Any(l=>l.LocationName.StartsWith("Spatial unrelated root")))throw new Exception("Deep context loaded unrelated directory data.");while(!rows.IsConsumed)await rows.ReadAsync();Console.WriteLine($"PASS 500-level hierarchy plus 1000 unrelated roots: {relevant.Length} relevant locations, {deepTime.Elapsed.TotalMilliseconds:F1} ms, no full directory load");}tx.Rollback();}
foreach(var scenario in new[]{"duplicate-map","stale-room","connected-room","room-confirmation"}){
using var tx=db.BeginTransaction();try{
var a=await db.ExecuteScalarAsync<int>("INSERT dbo.Locations(ProjectID,LocationName) VALUES(@ProjectID,N'Spatial negative fixture');SELECT CONVERT(int,SCOPE_IDENTITY());",fixture,tx);
var b=await db.ExecuteScalarAsync<int>("INSERT dbo.Locations(ProjectID,LocationName) VALUES(@ProjectID,N'Spatial negative target');SELECT CONVERT(int,SCOPE_IDENTITY());",fixture,tx);
if(scenario=="duplicate-map"){
var map=await db.ExecuteScalarAsync<int>("INSERT dbo.StoryMaps(ProjectID,Name,Kind) VALUES(@ProjectID,N'Spatial duplicate fixture',N'Region');SELECT CONVERT(int,SCOPE_IDENTITY());",fixture,tx);
var version=await db.ExecuteScalarAsync<int>("SELECT Revision FROM dbo.StoryMaps WHERE MapID=@map",new{map},tx);
var first=await db.QuerySingleAsync<SpatialMutationResult>("dbo.SpatialContext_Mutate",new{fixture.UserID,fixture.BookID,fixture.SceneID,Kind="map",LocationID=a,ResourceID=map,Expected=version.ToString(),X=10,Y=20},tx,commandType:CommandType.StoredProcedure);
await db.QuerySingleAsync<SpatialMutationResult>("dbo.SpatialContext_Mutate",new{fixture.UserID,fixture.BookID,fixture.SceneID,Kind="map",LocationID=a,ResourceID=map,Expected=first.Version,X=20,Y=30},tx,commandType:CommandType.StoredProcedure);
}else{
var plan=await db.ExecuteScalarAsync<int>("INSERT dbo.FloorPlans(ProjectID,Name) VALUES(@ProjectID,N'Spatial negative plan');SELECT CONVERT(int,SCOPE_IDENTITY());",fixture,tx);
var floor=await db.ExecuteScalarAsync<int>("INSERT dbo.FloorPlanFloors(FloorPlanID,Name) VALUES(@plan,N'Ground');SELECT CONVERT(int,SCOPE_IDENTITY());",new{plan},tx);
var block=await db.ExecuteScalarAsync<int>("INSERT dbo.FloorPlanBlocks(FloorPlanFloorID,LocationID,X,Y,WidthCells,HeightCells) VALUES(@floor,@a,2,3,4,5);SELECT CONVERT(int,SCOPE_IDENTITY());",new{floor,a},tx);
var version=(await db.QueryAsync<SpatialVersion>("dbo.SpatialContext_RoomVersions",new{fixture.UserID,fixture.BookID,fixture.SceneID,PlanID=plan},tx,commandType:CommandType.StoredProcedure)).Single();
if(scenario=="stale-room")await db.ExecuteAsync("UPDATE dbo.FloorPlanBlocks SET X=4 WHERE FloorPlanBlockID=@block",new{block},tx);
if(scenario=="connected-room")await db.ExecuteAsync("INSERT dbo.FloorPlanTransitions(FloorPlanFloorID,FromLocationID,ToLocationID,TransitionType) VALUES(@floor,@a,@b,N'Door')",new{floor,a,b},tx);
await db.QuerySingleAsync<SpatialMutationResult>("dbo.SpatialContext_Mutate",new{fixture.UserID,fixture.BookID,fixture.SceneID,Kind="room",LocationID=b,ResourceID=plan,GeometryID=block.ToString(),Expected=version.Version,Replace=scenario!="room-confirmation"},tx,commandType:CommandType.StoredProcedure);
}
throw new Exception("Invalid operation accepted: "+scenario);
}catch(SqlException e)when(e.Number==(scenario=="stale-room"?51011:51012)){Console.WriteLine("PASS server rejection: "+scenario);}
}
var sequence=(await db.QueryAsync<int>("SELECT TOP(5) n.SceneID FROM dbo.NarrativeSceneOrder n LEFT JOIN dbo.NarrativeSceneOrder p ON p.BookID=n.BookID AND p.BookSceneIndex=n.BookSceneIndex-1 WHERE n.BookID=@BookID AND(p.SceneID IS NULL OR p.ChapterID<>n.ChapterID) ORDER BY n.BookSceneIndex",fixture)).ToList();sequence.Add(await db.ExecuteScalarAsync<int>("SELECT TOP(1) SceneID FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID ORDER BY BookSceneIndex DESC",fixture));var samples=new List<double>();
foreach(var scene in sequence.Distinct())for(var repeat=0;repeat<3;repeat++){var watch=Stopwatch.StartNew();using var rows=await db.QueryMultipleAsync("dbo.SpatialContext_Read",new{fixture.UserID,fixture.BookID,SceneID=scene},commandType:CommandType.StoredProcedure);var scope=await rows.ReadSingleAsync<SpatialScope>();var actual=(await rows.ReadAsync<SpatialScene>()).ToArray();while(!rows.IsConsumed)await rows.ReadAsync();var expected=(await db.QueryAsync<int>("SELECT n.SceneID FROM dbo.NarrativeSceneOrder n WHERE n.BookID=@BookID AND ABS(n.BookSceneIndex-(SELECT BookSceneIndex FROM dbo.NarrativeSceneOrder WHERE SceneID=@scene))<=1 ORDER BY n.BookSceneIndex",new{fixture.BookID,scene})).ToArray();if(!actual.Select(s=>s.SceneID).SequenceEqual(expected))throw new Exception("Boundary scene order mismatch.");while(!rows.IsConsumed)await rows.ReadAsync();samples.Add(watch.Elapsed.TotalMilliseconds);}
samples.Sort();Console.WriteLine($"PASS first/last and chapter-boundary scene ordering; {samples.Count} reads, median {samples[samples.Count/2]:F1} ms, maximum {samples[^1]:F1} ms");
// Expected rejections run outside the fixture transaction, which each proc owns and rolls back.
foreach(var pair in new[]{(User:0,Kind:"scene",Expected:"2026-01-01"),(User:fixture.UserID,Kind:"scene",Expected:"2020-01-01"),(User:fixture.UserID,Kind:"map",Expected:"invalid")}){try{await db.QueryAsync<SpatialMutationResult>("dbo.SpatialContext_Mutate",new{UserID=pair.User,fixture.BookID,fixture.SceneID,Kind=pair.Kind,Expected=pair.Expected,LocationID=(int?)null,ResourceID=-1},commandType:CommandType.StoredProcedure);throw new Exception("Unsafe mutation was accepted.");}catch(SqlException e)when(e.Number is 51010 or 51011 or 51012){Console.WriteLine("PASS server rejection: "+pair.Kind+"/"+e.Number);}}
}
}

View File

@ -401,6 +401,14 @@ internal static class ToolbarBrowserHost
if(step=="Preview")model.Preview=new(new(upload,[12,13],0,"Recovered harbour","",Guid.NewGuid(),DateTime.UtcNow.AddMinutes(20)),"fixture-confirmation",snapshot,12,5,context.Request.Query.ContainsKey("full")?0:4,package.Warnings);
await RenderFullAsync(context,"BookRecovery",step,step=="Complete"?new BookRecoveryReceipt{ProjectID=7,BooksCreated=2}:model);
});
app.MapGet("/Writing/Context/{spatial}", async (HttpContext context,string spatial)=>{
if(!new[]{"Locations","Maps","FloorPlans"}.Contains(spatial)){context.Response.StatusCode=404;return;}
var scene=int.TryParse(context.Request.Query["sceneId"],out var n)?n:22;
await RenderFullAsync(context,"Writing","_ContextSpatial",new PlotLine.Services.Context.SpatialFragment(spatial.ToLowerInvariant(),SpatialContextBrowserFixture.Scope(scene)));
}).WithOrder(-1);
app.MapGet("/SpatialContext/State",(HttpContext context)=>Results.Json(SpatialContextBrowserFixture.Data(int.TryParse(context.Request.Query["sceneId"],out var n)?n:22))).WithOrder(-1);
app.MapGet("/SpatialContext/Map",async (HttpContext context)=>await RenderFullAsync(context,"Maps","Index",SpatialContextBrowserFixture.Map(),new(){["SpatialRenderer"]=true,["DetachedWorkspace"]=true})).WithOrder(-1);
app.MapGet("/SpatialContext/Floor",async (HttpContext context)=>await RenderFullAsync(context,"Writing","_SpatialFloorCanvas",SpatialContextBrowserFixture.Floor())).WithOrder(-1);
app.MapGet("/Writing/Context", async context =>
{
context.Request.RouteValues["controller"] = "Writing";

View File

@ -11,7 +11,7 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec
IFloorPlanRepository floorPlans, IProjectAccessService access, ICurrentUserService currentUser) : Controller
{
private int UserID => currentUser.UserId!.Value;
public async Task<IActionResult> Index(int projectId, int? id, bool detached = false)
public async Task<IActionResult> Index(int projectId, int? id, bool detached = false, Guid? featureId = null)
{
if (projectId == 0) return View("ChooseProject", await projects.ListActiveForUserAsync(UserID));
if (!await access.CanAccessProjectAsync(projectId)) return NotFound();
@ -19,6 +19,7 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec
if (project is null) return NotFound();
var document = id.HasValue ? await maps.GetAsync(projectId, id.Value, UserID) : null;
if (id.HasValue && document is null) return NotFound();
if(featureId.HasValue&&(document==null||!document.Features.Any(f=>f.FeatureID==featureId.Value)))return NotFound();
if (detached) ViewData["DetachedWorkspace"] = true;
return View(new MapsViewModel { Project = project, Maps = await maps.ListAsync(projectId, UserID), Document = document,
ReferenceImages = await maps.ListImagesAsync(projectId, UserID),

View File

@ -0,0 +1,30 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.Context;
namespace PlotLine.Controllers;
[Authorize,ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public sealed class SpatialContextController(ContextSpatial spatial,MapRepository maps,ICurrentUserService user):Controller
{
private async Task<IActionResult> Guard(Func<Task<IActionResult>> action)
{
try{return await action();}catch(UnauthorizedAccessException){return Forbid();}
catch(SqlException e)when(e.Number is 51010 or 51011 or 51012){return StatusCode(e.Number==51010?403:409,new{message=e.Message});}
catch(ArgumentException e){return BadRequest(new{message=e.Message});}
}
[HttpGet] public Task<IActionResult> State(int bookId,int sceneId,int? locationId)=>Guard(async()=>Json(await spatial.Read(bookId,sceneId,locationId)));
[HttpPost,ValidateAntiForgeryToken] public Task<IActionResult> Mutate([FromBody] SpatialMutation input)=>Guard(async()=>ModelState.IsValid&&input!=null?Json(await spatial.Mutate(input)):BadRequest(new{message="Check the spatial operation."}));
public sealed record UndoInput(string Token);
[HttpPost,ValidateAntiForgeryToken] public Task<IActionResult> Undo([FromBody] UndoInput input)=>Guard(async()=>input!=null&&!string.IsNullOrWhiteSpace(input.Token)&&input.Token.Length<=16000?Json(await spatial.Undo(input.Token)):BadRequest(new{message="Undo is unavailable."}));
[HttpPost,ValidateAntiForgeryToken] public Task<IActionResult> Create([FromBody] SpatialCreation input)=>Guard(async()=>ModelState.IsValid&&input!=null?Json(await spatial.Create(input)):BadRequest(new{message="Check the location details."}));
[HttpGet] public Task<IActionResult> Map(int bookId,int sceneId,int id)=>Guard(async()=>{
var scope=await spatial.Scope(bookId,sceneId);var document=await maps.GetAsync(scope.ProjectID,id,user.UserId!.Value);if(document==null)return NotFound();
ViewData["SpatialRenderer"]=true;ViewData["DetachedWorkspace"]=true;
return View("~/Views/Maps/Index.cshtml",new MapsViewModel{Project=new(){ProjectID=scope.ProjectID},Maps=[document.Map],Document=document});
});
[HttpGet] public Task<IActionResult> Floor(int bookId,int sceneId,int id)=>Guard(async()=>PartialView("~/Views/Writing/_SpatialFloorCanvas.cshtml",await spatial.Floor(bookId,sceneId,id)));
}

View File

@ -119,6 +119,28 @@ public sealed class WritingController(
ViewData["ContextTabPartial"]="_ContextNames";return PartialView("_ContextTab",model);
}
[HttpGet("Context/Locations")]
public Task<IActionResult> ContextLocations(int? projectId,int? bookId,int? chapterId,int? sceneId,Guid? instanceId,Guid? sessionId,[FromServices] PlotLine.Services.Context.ContextSpatial spatial)
=>RenderSpatial("locations",projectId,bookId,chapterId,sceneId,instanceId,sessionId,spatial);
[HttpGet("Context/Maps")]
public Task<IActionResult> ContextMaps(int? projectId,int? bookId,int? chapterId,int? sceneId,Guid? instanceId,Guid? sessionId,[FromServices] PlotLine.Services.Context.ContextSpatial spatial)
=>RenderSpatial("maps",projectId,bookId,chapterId,sceneId,instanceId,sessionId,spatial);
[HttpGet("Context/FloorPlans")]
public Task<IActionResult> ContextFloorPlans(int? projectId,int? bookId,int? chapterId,int? sceneId,Guid? instanceId,Guid? sessionId,[FromServices] PlotLine.Services.Context.ContextSpatial spatial)
=>RenderSpatial("floorplans",projectId,bookId,chapterId,sceneId,instanceId,sessionId,spatial);
private async Task<IActionResult> RenderSpatial(string kind,int? projectId,int? bookId,int? chapterId,int? sceneId,Guid? instanceId,Guid? sessionId,PlotLine.Services.Context.ContextSpatial spatial)
{
if(!ModelState.IsValid||bookId is not >0||sceneId is not >0||InvalidNativeSelection(instanceId,sessionId))return BadRequest();
var native=instanceId.HasValue?await NativeTarget(bookId,instanceId,sessionId):null;
if(instanceId.HasValue&&(native==null||native.SceneId!=sceneId||chapterId.HasValue&&native.ChapterId!=chapterId))return Conflict();
try{
var scope=await spatial.Scope(bookId.Value,sceneId.Value);
if(projectId.HasValue&&scope.ProjectID!=projectId||chapterId.HasValue&&scope.ChapterID!=chapterId)return BadRequest();
if(instanceId.HasValue&&!SameNativeTarget(native,await NativeTarget(bookId,instanceId,sessionId)))return Conflict();
return PartialView("_ContextSpatial",new PlotLine.Services.Context.SpatialFragment(kind,scope));
}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51010){return Forbid();}
}
private async Task<IActionResult> RenderContextTab(string partial, int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? instanceId, Guid? sessionId)
{
if (!ModelState.IsValid || sceneId is not > 0 || InvalidNativeSelection(instanceId, sessionId)) return BadRequest();

View File

@ -37,3 +37,21 @@ Revision Status is the scene's workflow stage. Completing a checklist objective,
# Audio Review
Choose the intended chapter before starting. Live controls require compatible Windows Companion and a supported media source. End review stops tracking. Use Pause first if you also want external playback to stop. Resume is always explicit.
# Locations, Maps and Floor Plans whilst writing
Choose **Locations**, **Maps** or **Floor Plans** from either Context pane's Tool selector. Use Side by side or Stacked to combine them with each other or an existing reference tool. Showing a spatial resource asks where to open it when the appropriate tool is not already visible; it does not silently replace another tool or open another window.
Locations shows the previous, current and next scenes in manuscript order, including chapter boundaries. Click an adjacent location to inspect it without moving the manuscript. The current scene remains identified. Consecutive scenes at the same location receive a Same location indicator. A scene without an assignment stays unassigned until you explicitly choose or create a location, or choose to use an adjacent scene's location.
Click a containing location in the ancestral path or an immediate child to inspect nearby spaces. **Return to scene location** restores the current scene's location. Inspection is separate from assignment: **Change current scene location** identifies the scene being changed and opens the hierarchical picker. Inspecting a previous scene's room never changes that scene's assignment.
Descriptions, names, types and classifications can be corrected directly. Description edits have Save and Cancel. Create child starts with the inspected location as parent. A new location for the current scene lets you review its parent before creation. Finish or cancel an operation before changing tools or closing its pane; manuscript movement cannot silently retarget it.
Maps shows the surrounding world using the existing map renderer. Blue **P**, amber **C** and green **N** identify previous, current and next scene positions; repeated positions share their indicators. A caption explains when a room is represented through a containing building rather than its own exact position. Choose another existing map, pan, wheel-zoom, fit scene locations or centre on the selection. These indicators show manuscript order, not a journey or route.
Choose **Place on map** in Locations, or **Place location** in Maps, to position an existing location. You can also drag a location from Locations onto a visible map. Placement identifies the location, requires an explicit map click or confirmation and offers Cancel. An existing marker requires explicit repositioning; duplicate markers are not silently created. Use Undo for a supported recent spatial change, and Open in Maps for complex geometry.
Floor Plans shows explicitly associated plans, floors and rooms. Select a level, zoom, pan or fit the plan. Selecting an associated room updates the Locations pane without moving manuscript focus. Select a room and choose **Associate existing location**, or drag a location onto it. Replacing an association requires confirmation and does not reparent the location or change geometry. Rooms with recorded connecting transitions must have their identity changes reviewed in the main Floor Plans editor. You may also explicitly associate an existing plan with a location.
Hold and Release retain their usual window-wide meaning. Paragraph movement within the same scene preserves inspection, zoom and pan. Other Context windows keep their own spatial selection. Permanent containment (a bedroom within a house) remains distinct from a temporary story circumstance (a vehicle parked nearby).

View File

@ -313,6 +313,7 @@ public class Program
builder.Services.AddSingleton<PlotLine.Services.Context.ContextWindows>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextCharacterPanels>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextNames>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextSpatial>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextRelationshipEditing>();
builder.Services.AddScoped<PlotLine.Data.IContextRelationshipReader,PlotLine.Data.ContextRelationshipReader>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextRelationshipLenses>();

View File

@ -0,0 +1,89 @@
using System.Data;
using System.Text.Json;
using Dapper;
using Microsoft.AspNetCore.DataProtection;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.ViewModels;
namespace PlotLine.Services.Context;
public sealed class SpatialScope
{
public int ProjectID{get;set;}public int BookID{get;set;}public int ChapterID{get;set;}public int SceneID{get;set;}
public string SceneTitle{get;set;}="";public string ChapterTitle{get;set;}="";public decimal ChapterNumber{get;set;}public decimal SceneNumber{get;set;}
public int? PrimaryLocationID{get;set;}public DateTime Version{get;set;}public bool CanEdit{get;set;}
public string Label=>$"Ch {ChapterNumber:0.##}: {ChapterTitle} · Scene {SceneNumber:0.##}: {SceneTitle}";
}
public sealed class SpatialScene
{
public int Position{get;set;}public int SceneID{get;set;}public int ChapterID{get;set;}public decimal ChapterNumber{get;set;}public string ChapterTitle{get;set;}="";public decimal SceneNumber{get;set;}public string SceneTitle{get;set;}="";public int? LocationID{get;set;}public DateTime Version{get;set;}
public string Label=>$"Ch {ChapterNumber:0.##}: {ChapterTitle} · Scene {SceneNumber:0.##}: {SceneTitle}";
}
public sealed class SpatialLocation:LocationWorkspaceRecord {public int ChildCount{get;set;}}
public sealed record SpatialAssignment(int SceneID,int LocationID,string Kind,int Position);
public sealed record SpatialMapLink(int LocationID,int ResourceID,string Name,Guid FeatureID,bool IsPlaced,string GeometryClass,bool IsLocked);
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 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 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)
{
private int Author=>user.UserId??throw new UnauthorizedAccessException();
private IDataProtector Protector=>protection.CreateProtector("Context.Spatial.Undo.v1");
public async Task<SpatialScope> Scope(int book,int scene)
{
using var db=connections.CreateConnection();return await db.QuerySingleAsync<SpatialScope>("dbo.SpatialContext_Scope",new{UserID=Author,BookID=book,SceneID=scene},commandType:CommandType.StoredProcedure);
}
public async Task<SpatialDocument> Read(int book,int scene,int? inspect)
{
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<SpatialScope>();var scenes=(await data.ReadAsync<SpatialScene>()).ToArray();var assignments=(await data.ReadAsync<SpatialAssignment>()).ToArray();var locations=(await data.ReadAsync<SpatialLocation>()).ToArray();var maps=(await data.ReadAsync<SpatialMapLink>()).ToArray();var plans=(await data.ReadAsync<SpatialPlanLink>()).ToArray();var mapCatalog=(await data.ReadAsync<SpatialCatalog>()).ToArray();var planCatalog=(await data.ReadAsync<SpatialCatalog>()).ToArray();var relationships=(await data.ReadAsync<SpatialRelation>()).ToArray();var types=(await data.ReadAsync<LocationTypeTaxonomyEntry>()).Select(LocationWorkspaceIcons.Presentation).ToArray();
return new(scope,scenes,assignments,locations,maps,plans,mapCatalog,planCatalog,relationships,types);
}
private async Task<SpatialMutationResult> Apply(IDbConnection db,SpatialMutation input,IDbTransaction? transaction=null,string? previous=null)
{
if(input.Kind is not("scene" or "map" or "room" or "plan")||input.Expected?.Length is not(>0 and <=80)||input.GeometryID?.Length>50||input.X.HasValue&&!double.IsFinite(input.X.Value)||input.Y.HasValue&&!double.IsFinite(input.Y.Value))throw new ArgumentException("Choose a valid spatial operation.");
return await db.QuerySingleAsync<SpatialMutationResult>("dbo.SpatialContext_Mutate",new{UserID=Author,input.BookID,input.SceneID,input.Kind,input.LocationID,input.ResourceID,input.GeometryID,input.Expected,input.X,input.Y,input.Replace,Restore=previous!=null,Previous=previous},transaction,commandType:CommandType.StoredProcedure);
}
public async Task<object> Mutate(SpatialMutation input)
{
using var db=connections.CreateConnection();var result=await Apply(db,input);return await Accepted(input,result);
}
private async Task<object> Accepted(SpatialMutation input,SpatialMutationResult result)
{
string? undo=null;if(result.Changed&&result.Previous!=null)undo=Protector.Protect(JsonSerializer.Serialize(new SpatialReceipt(Author,input with{Expected=result.Version,GeometryID=result.GeometryID},result.Previous,DateTime.UtcNow.AddMinutes(10))));
if(result.Changed){await notifications.Invalidate(Author,projectId:result.ProjectID,bookId:input.BookID,kind:input.Kind is "map"?"maps":input.Kind is "room" or "plan"?"floorplans":"locations");}
return new{saved=true,result,undoToken=undo};
}
public async Task<object> Undo(string token)
{
SpatialReceipt receipt;try{receipt=JsonSerializer.Deserialize<SpatialReceipt>(Protector.Unprotect(token))??throw new Exception();}catch{throw new ArgumentException("Undo is unavailable.");}
if(receipt.User!=Author||receipt.Expires<DateTime.UtcNow)throw new ArgumentException("Undo expired. Existing work is unchanged.");
using var db=connections.CreateConnection();var result=await Apply(db,receipt.Target,previous:receipt.Previous);if(result.Changed){await notifications.Invalidate(Author,projectId:result.ProjectID,bookId:receipt.Target.BookID,kind:receipt.Target.Kind=="map"?"maps":receipt.Target.Kind=="scene"?"locations":"floorplans");}return new{saved=true,result};
}
public async Task<object> Create(SpatialCreation input)
{
var scope=await Scope(input.BookID,input.SceneID);if(!scope.CanEdit)throw new UnauthorizedAccessException();if(string.IsNullOrWhiteSpace(input.Name)||input.Name.Length>200)throw new ArgumentException("Enter a location name of up to 200 characters.");
using var db=connections.CreateConnection();db.Open();using var tx=db.BeginTransaction();
var id=await db.QuerySingleAsync<int>("dbo.Location_WorkspaceCreate",new{scope.ProjectID,UserID=Author,input.Name,ParentID=input.ParentID},tx,commandType:CommandType.StoredProcedure);
SpatialMutationResult? changed=null;SpatialMutation? target=null;
if(input.Expected!=null){target=new(input.BookID,input.SceneID,input.BlockID!=null?"room":"scene",id,input.PlanID,input.BlockID,input.Expected,Replace:input.Replace);changed=await Apply(db,target,tx);}
tx.Commit();await notifications.Invalidate(Author,projectId:scope.ProjectID,bookId:scope.BookID,kind:"locations");
return new{id,assignment=changed==null?null:await Accepted(target!,changed)};
}
public async Task<SpatialFloorCanvas> Floor(int book,int scene,int plan)
{
var scope=await Scope(book,scene);using var db=connections.CreateConnection();db.Open();using var tx=db.BeginTransaction(IsolationLevel.RepeatableRead);using var rows=await db.QueryMultipleAsync("dbo.FloorPlan_GetEditor",new{FloorPlanID=plan},tx,commandType:CommandType.StoredProcedure);
var header=await rows.ReadSingleOrDefaultAsync<FloorPlanEditViewModel>();if(header==null||header.ProjectID!=scope.ProjectID)throw new UnauthorizedAccessException();
var model=new FloorPlanEditorViewModel{Project=new(){ProjectID=scope.ProjectID},FloorPlan=header,Floors=(await rows.ReadAsync<FloorPlanFloorEditViewModel>()).ToList(),Blocks=(await rows.ReadAsync<FloorPlanBlockEditViewModel>()).ToList(),Transitions=(await rows.ReadAsync<FloorPlanTransitionEditViewModel>()).ToList()};rows.Dispose();
var versions=(await db.QueryAsync<SpatialVersion>("dbo.SpatialContext_RoomVersions",new{UserID=Author,BookID=book,SceneID=scene,PlanID=plan},tx,commandType:CommandType.StoredProcedure)).ToArray();tx.Commit();return new(model,versions);
}
}

View File

@ -0,0 +1,59 @@
using PlotLine.ViewModels;
namespace PlotLine.Services;
// Shared original floor-plan presentation, used by the editor and focused Context canvas.
public static class FloorPlanPresentation
{
public static string BlockClass(string blockType) => $"floor-plan-block floor-plan-block--{blockType.ToLowerInvariant()}";
public static string CssNumber(decimal value) => value.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture);
public static string TransitionDetails(FloorPlanTransitionEditViewModel transition)
{
var details = $"{transition.FromLocationName} -> {transition.ToLocationName}\n{transition.TransitionType}";
return string.IsNullOrWhiteSpace(transition.DisplayLabel) ? details : $"{details}\n{transition.DisplayLabel}";
}
public static string TransitionMarkerType(string? transitionType)
{
var normalized = (transitionType ?? string.Empty)
.Trim()
.Replace(" ", string.Empty, StringComparison.OrdinalIgnoreCase)
.Replace("-", string.Empty, StringComparison.OrdinalIgnoreCase)
.ToLowerInvariant();
return normalized switch
{
"door" => "door",
"doubledoor" => "double-door",
"frenchdoor" or "frenchdoors" => "french-door",
"slidingdoor" or "slidingdoors" => "sliding-door",
"window" => "window",
"archway" or "opening" => "archway",
"secretdoor" or "hiddendoor" => "secret-door",
"blockeddoor" => "blocked-door",
"exteriordoor" => "exterior-door",
"stairs" or "stair" or "stairsup" or "stairsdown" => "stairs",
"ladder" or "ladders" => "ladder",
"passage" or "openpassage" => "passage",
"hiddenpassage" or "secretpassage" => "secret-route",
_ => "other"
};
}
public static string TransitionMarkerSvg(string markerType) => markerType switch
{
"door" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M2 9h6""/><path class=""marker-line"" d=""M10 9h6""/><path class=""marker-arc"" d=""M8 9a6 6 0 0 1 6-6""/></svg>",
"double-door" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M2 9h4""/><path class=""marker-line"" d=""M12 9h4""/><path class=""marker-arc"" d=""M6 9a4 4 0 0 1 4-4""/><path class=""marker-arc"" d=""M12 9a4 4 0 0 0-4-4""/></svg>",
"french-door" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line marker-strong"" d=""M2 9h3""/><path class=""marker-line marker-strong"" d=""M13 9h3""/><path class=""marker-arc"" d=""M5 9a4 4 0 0 1 4-4""/><path class=""marker-arc"" d=""M13 9a4 4 0 0 0-4-4""/><path class=""marker-line"" d=""M9 5v8""/></svg>",
"sliding-door" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M2 9h14""/><path class=""marker-line marker-track"" d=""M4 6h10""/><path class=""marker-line marker-track"" d=""M9 6l3 3""/></svg>",
"window" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-window"" d=""M3 7h12""/><path class=""marker-window"" d=""M3 11h12""/><path class=""marker-line"" d=""M5 9h8""/></svg>",
"archway" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M2 14h4""/><path class=""marker-line"" d=""M12 14h4""/><path class=""marker-arc"" d=""M6 14a3 3 0 0 1 6 0""/></svg>",
"secret-door" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line marker-dotted"" d=""M2 9h6""/><path class=""marker-line marker-dotted"" d=""M10 9h6""/><path class=""marker-arc marker-dotted"" d=""M8 9a6 6 0 0 1 6-6""/></svg>",
"blocked-door" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M2 9h14""/><path class=""marker-blocked"" d=""M6 5l6 8""/><path class=""marker-blocked"" d=""M12 5l-6 8""/></svg>",
"exterior-door" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line marker-strong"" d=""M2 9h6""/><path class=""marker-line marker-strong"" d=""M10 9h6""/><path class=""marker-arc marker-strong"" d=""M8 9a6 6 0 0 1 6-6""/></svg>",
"stairs" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M4 13h10""/><path class=""marker-line"" d=""M5 10h8""/><path class=""marker-line"" d=""M6 7h6""/><path class=""marker-line"" d=""M7 4h4""/></svg>",
"ladder" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M6 3v12""/><path class=""marker-line"" d=""M12 3v12""/><path class=""marker-line"" d=""M6 5h6""/><path class=""marker-line"" d=""M6 8h6""/><path class=""marker-line"" d=""M6 11h6""/><path class=""marker-line"" d=""M6 14h6""/></svg>",
"passage" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M3 7h12""/><path class=""marker-line"" d=""M3 11h12""/><path class=""marker-line"" d=""M11 5l4 4-4 4""/><path class=""marker-line"" d=""M7 5L3 9l4 4""/></svg>",
_ => @"<span aria-hidden=""true"">x</span>"
};
}

View File

@ -0,0 +1,175 @@
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Read-only scene scope. Never initialise/write NarrativeFocus or infer scene locations.
CREATE OR ALTER PROCEDURE dbo.SpatialContext_Scope @UserID int,@BookID int,@SceneID int,@Emit bit=1
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID JOIN dbo.Projects p ON p.ProjectID=b.ProjectID JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE s.SceneID=@SceneID AND b.BookID=@BookID AND s.IsArchived=0 AND c.IsArchived=0 AND b.IsArchived=0 AND p.IsArchived=0) THROW 51010,'This manuscript position is unavailable.',1;
IF @Emit=1 SELECT b.ProjectID,b.BookID,c.ChapterID,s.SceneID,s.SceneTitle,c.ChapterTitle,c.ChapterNumber,s.SceneNumber,s.PrimaryLocationID,s.UpdatedDate AS Version,CONVERT(bit,CASE WHEN a.AccessRole IN(N'Owner',N'Collaborator') THEN 1 ELSE 0 END) CanEdit FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE s.SceneID=@SceneID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.SpatialContext_Read @UserID int,@BookID int,@SceneID int,@InspectID int=NULL
AS
BEGIN
SET NOCOUNT ON;
EXEC dbo.SpatialContext_Scope @UserID,@BookID,@SceneID;
DECLARE @ProjectID int=(SELECT b.ProjectID FROM dbo.Books b WHERE b.BookID=@BookID),@index bigint=(SELECT BookSceneIndex FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID AND SceneID=@SceneID);
IF @index IS NULL THROW 51012,'Scene order is unavailable.',1;
IF @InspectID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@InspectID AND ProjectID=@ProjectID AND IsArchived=0) THROW 51012,'The inspected location is unavailable.',1;
SELECT CONVERT(int,n.BookSceneIndex-@index) Position,n.SceneID,n.ChapterID,c.ChapterNumber,c.ChapterTitle,n.SceneNumber,n.SceneTitle,s.PrimaryLocationID AS LocationID,s.UpdatedDate Version INTO #scenes FROM dbo.NarrativeSceneOrder n JOIN dbo.Chapters c ON c.ChapterID=n.ChapterID JOIN dbo.Scenes s ON s.SceneID=n.SceneID WHERE n.BookID=@BookID AND n.BookSceneIndex BETWEEN @index-1 AND @index+1;
SELECT * FROM #scenes ORDER BY Position;
SELECT DISTINCT SceneID,LocationID,Kind INTO #refs FROM(
SELECT SceneID,LocationID,N'Scene location' Kind FROM #scenes WHERE LocationID IS NOT NULL
UNION ALL SELECT sc.SceneID,v.ID,v.Kind FROM dbo.SceneCharacters sc JOIN #scenes s ON s.SceneID=sc.SceneID CROSS APPLY(VALUES(sc.LocationID,N'Recorded character position'),(sc.EntryLocationID,N'Recorded entry position'),(sc.ExitLocationID,N'Recorded exit position'))v(ID,Kind) WHERE v.ID IS NOT NULL
UNION ALL SELECT a.SceneID,a.LocationID,N'Recorded asset position' FROM dbo.SceneAssetLocations a JOIN #scenes s ON s.SceneID=a.SceneID
UNION ALL SELECT o.SceneID,o.LocationID,N'Recorded floor-plan occupancy' FROM dbo.SceneFloorPlanOccupancy o JOIN #scenes s ON s.SceneID=o.SceneID
)x;
SELECT r.*,s.Position FROM #refs r JOIN #scenes s ON s.SceneID=r.SceneID;
CREATE TABLE #seed(ID int PRIMARY KEY);
INSERT #seed SELECT DISTINCT l.LocationID FROM dbo.Locations l WHERE l.ProjectID=@ProjectID AND l.IsArchived=0 AND(l.LocationID=@InspectID OR EXISTS(SELECT 1 FROM #refs r WHERE r.LocationID=l.LocationID));
CREATE TABLE #anc(ID int PRIMARY KEY);
;WITH walk AS(
SELECT l.LocationID ID,l.ParentLocationID,CONVERT(varchar(max),'|'+CONVERT(varchar(20),l.LocationID)+'|') Seen FROM #seed s JOIN dbo.Locations l ON l.LocationID=s.ID
UNION ALL
SELECT p.LocationID,p.ParentLocationID,w.Seen+CONVERT(varchar(20),p.LocationID)+'|' FROM walk w JOIN dbo.Locations p ON p.LocationID=w.ParentLocationID WHERE p.ProjectID=@ProjectID AND p.IsArchived=0 AND CHARINDEX('|'+CONVERT(varchar(20),p.LocationID)+'|',w.Seen)=0
) INSERT #anc SELECT DISTINCT ID FROM walk OPTION(MAXRECURSION 0);
DECLARE @selected int=COALESCE(@InspectID,(SELECT LocationID FROM #scenes WHERE Position=0));
CREATE TABLE #shown(ID int PRIMARY KEY);INSERT #shown SELECT ID FROM #anc;
INSERT #shown SELECT TOP(40) l.LocationID FROM dbo.Locations l WHERE l.ParentLocationID=@selected AND l.ProjectID=@ProjectID AND l.IsArchived=0 AND NOT EXISTS(SELECT 1 FROM #shown x WHERE x.ID=l.LocationID) ORDER BY l.LocationName,l.LocationID;
SELECT l.*,t.TypeName LocationTypeName,(SELECT COUNT(*) FROM dbo.Locations ch WHERE ch.ParentLocationID=l.LocationID AND ch.ProjectID=@ProjectID AND ch.IsArchived=0) ChildCount FROM #shown x JOIN dbo.Locations l ON l.LocationID=x.ID LEFT JOIN dbo.LocationTypes t ON t.LocationTypeID=l.LocationTypeID;
SELECT f.LocationID,m.MapID ResourceID,m.Name,f.FeatureID,f.IsPlaced,f.GeometryClass,f.IsLocked FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID JOIN #anc a ON a.ID=f.LocationID WHERE m.ProjectID=@ProjectID;
SELECT p.FloorPlanID ResourceID,p.Name,p.LocationID,CONVERT(int,NULL) FloorID,CONVERT(int,NULL) BlockID FROM dbo.FloorPlans p JOIN #anc a ON a.ID=p.LocationID WHERE p.ProjectID=@ProjectID
UNION SELECT p.FloorPlanID,p.Name,f.LocationID,f.FloorPlanFloorID,NULL FROM dbo.FloorPlanFloors f JOIN dbo.FloorPlans p ON p.FloorPlanID=f.FloorPlanID JOIN #anc a ON a.ID=f.LocationID WHERE p.ProjectID=@ProjectID
UNION SELECT p.FloorPlanID,p.Name,b.LocationID,f.FloorPlanFloorID,b.FloorPlanBlockID FROM dbo.FloorPlanBlocks b JOIN dbo.FloorPlanFloors f ON f.FloorPlanFloorID=b.FloorPlanFloorID JOIN dbo.FloorPlans p ON p.FloorPlanID=f.FloorPlanID JOIN #anc a ON a.ID=b.LocationID WHERE p.ProjectID=@ProjectID
UNION SELECT p.FloorPlanID,p.Name,m.LocationID,NULL,NULL FROM dbo.MapFeatures m JOIN dbo.StoryMaps sm ON sm.MapID=m.MapID JOIN dbo.FloorPlans p ON p.FloorPlanID=m.FloorPlanID JOIN #anc a ON a.ID=m.LocationID WHERE p.ProjectID=@ProjectID AND sm.ProjectID=@ProjectID;
SELECT MapID ID,Name,Kind,Revision,ModifiedDate FROM dbo.StoryMaps WHERE ProjectID=@ProjectID ORDER BY Name,MapID;
;WITH dates AS(
SELECT FloorPlanID,COALESCE(ModifiedDate,CreatedDate) Stamp FROM dbo.FloorPlans WHERE ProjectID=@ProjectID
UNION ALL SELECT f.FloorPlanID,COALESCE(f.ModifiedDate,f.CreatedDate) FROM dbo.FloorPlanFloors f JOIN dbo.FloorPlans p ON p.FloorPlanID=f.FloorPlanID WHERE p.ProjectID=@ProjectID
UNION ALL SELECT f.FloorPlanID,COALESCE(b.ModifiedDate,b.CreatedDate) FROM dbo.FloorPlanBlocks b JOIN dbo.FloorPlanFloors f ON f.FloorPlanFloorID=b.FloorPlanFloorID JOIN dbo.FloorPlans p ON p.FloorPlanID=f.FloorPlanID WHERE p.ProjectID=@ProjectID
UNION ALL SELECT f.FloorPlanID,COALESCE(t.ModifiedDate,t.CreatedDate) FROM dbo.FloorPlanTransitions t JOIN dbo.FloorPlanFloors f ON f.FloorPlanFloorID=t.FloorPlanFloorID JOIN dbo.FloorPlans p ON p.FloorPlanID=f.FloorPlanID WHERE p.ProjectID=@ProjectID
) SELECT p.FloorPlanID ID,p.Name,p.LocationID,(SELECT MAX(d.Stamp) FROM dates d WHERE d.FloorPlanID=p.FloorPlanID) ModifiedDate,CONVERT(varchar(64),HASHBYTES('SHA2_256',(SELECT p.* FOR JSON PATH,INCLUDE_NULL_VALUES)),2) Version FROM dbo.FloorPlans p WHERE p.ProjectID=@ProjectID ORDER BY p.Name,p.FloorPlanID;
SELECT TOP(40) r.LocationRelationshipID ID,r.FromLocationID,r.ToLocationID,a.LocationName FromName,b.LocationName ToName,t.TypeName,r.Notes FROM dbo.LocationRelationships r JOIN dbo.Locations a ON a.LocationID=r.FromLocationID JOIN dbo.Locations b ON b.LocationID=r.ToLocationID JOIN dbo.LocationRelationshipTypes t ON t.LocationRelationshipTypeID=r.LocationRelationshipTypeID WHERE(r.FromLocationID=@selected OR r.ToLocationID=@selected) AND r.IsArchived=0 AND a.ProjectID=@ProjectID AND b.ProjectID=@ProjectID AND a.IsArchived=0 AND b.IsArchived=0 ORDER BY r.LocationRelationshipID;
EXEC dbo.LocationTypeTaxonomy_Read;
END;
GO
CREATE OR ALTER PROCEDURE dbo.SpatialContext_RoomVersions @UserID int,@BookID int,@SceneID int,@PlanID int
AS
BEGIN
SET NOCOUNT ON;EXEC dbo.SpatialContext_Scope @UserID,@BookID,@SceneID,0;
IF NOT EXISTS(SELECT 1 FROM dbo.FloorPlans p JOIN dbo.Books b ON b.ProjectID=p.ProjectID WHERE p.FloorPlanID=@PlanID AND b.BookID=@BookID) THROW 51010,'Plan unavailable.',1;
SELECT b.FloorPlanBlockID ID,CONVERT(varchar(64),HASHBYTES('SHA2_256',(SELECT b.* FOR JSON PATH,INCLUDE_NULL_VALUES)),2) Version FROM dbo.FloorPlanBlocks b JOIN dbo.FloorPlanFloors f ON f.FloorPlanFloorID=b.FloorPlanFloorID WHERE f.FloorPlanID=@PlanID;
END;
GO
-- A targeted mutation/Undo envelope over canonical records. No Context-only geometry or association store.
CREATE OR ALTER PROCEDURE dbo.SpatialContext_Mutate
@UserID int,@BookID int,@SceneID int,@Kind nvarchar(20),@LocationID int=NULL,@ResourceID int=NULL,@GeometryID nvarchar(50)=NULL,@Expected nvarchar(80),@X float=NULL,@Y float=NULL,@Replace bit=0,@Restore bit=0,@Previous nvarchar(max)=NULL
AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
EXEC dbo.SpatialContext_Scope @UserID,@BookID,@SceneID,0;
DECLARE @project int=(SELECT ProjectID FROM dbo.Books WHERE BookID=@BookID),@old nvarchar(max),@version nvarchar(80),@changed bit=1,@now datetime2=SYSUTCDATETIME();
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@project AND UserID=@UserID AND IsActive=1 AND AccessRole IN(N'Owner',N'Collaborator')) THROW 51010,'Editing is unavailable.',1;
IF @LocationID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@LocationID AND ProjectID=@project AND IsArchived=0) THROW 51012,'Choose an active location in this project.',1;
IF @Restore=1 AND ISJSON(@Previous)<>1 THROW 51012,'Undo unavailable.',1;
IF @Kind=N'scene'
BEGIN
DECLARE @sceneStamp datetime2,@oldLocation int;
SELECT @sceneStamp=s.UpdatedDate,@oldLocation=s.PrimaryLocationID FROM dbo.Scenes s WITH(UPDLOCK,HOLDLOCK) JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE s.SceneID=@SceneID AND c.BookID=@BookID AND s.IsArchived=0 AND c.IsArchived=0;
IF @sceneStamp IS NULL OR @sceneStamp<>TRY_CONVERT(datetime2,@Expected) OR TRY_CONVERT(datetime2,@Expected) IS NULL THROW 51011,'Scene location changed. Review the scene before saving.',1;
IF @Restore=1 SET @LocationID=TRY_CONVERT(int,JSON_VALUE(@Previous,'$.locationId'));
IF @LocationID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@LocationID AND ProjectID=@project AND IsArchived=0) THROW 51012,'The original location is unavailable.',1;
SET @old=(SELECT @oldLocation locationId FOR JSON PATH,WITHOUT_ARRAY_WRAPPER,INCLUDE_NULL_VALUES);
IF ISNULL(@oldLocation,0)=ISNULL(@LocationID,0) SET @changed=0;
ELSE UPDATE dbo.Scenes SET PrimaryLocationID=@LocationID,UpdatedDate=CASE WHEN @now<=UpdatedDate THEN DATEADD(NANOSECOND,100,UpdatedDate) ELSE @now END WHERE SceneID=@SceneID;
SELECT @version=CONVERT(nvarchar(50),UpdatedDate,126) FROM dbo.Scenes WHERE SceneID=@SceneID;
END
ELSE IF @Kind=N'map'
BEGIN
DECLARE @revision int,@feature uniqueidentifier=TRY_CONVERT(uniqueidentifier,@GeometryID),@created bit=0;
SELECT @revision=Revision FROM dbo.StoryMaps WITH(UPDLOCK,HOLDLOCK) WHERE MapID=@ResourceID AND ProjectID=@project;
IF @revision IS NULL THROW 51010,'Map unavailable.',1;
IF @revision<>TRY_CONVERT(int,@Expected) OR TRY_CONVERT(int,@Expected) IS NULL THROW 51011,'The map changed. Review placement again.',1;
IF @LocationID IS NULL THROW 51012,'Choose a location to place.',1;
IF @Restore=1
BEGIN
IF NOT EXISTS(SELECT 1 FROM dbo.MapFeatures WHERE MapID=@ResourceID AND FeatureID=@feature AND LocationID=@LocationID) THROW 51011,'The placed feature changed.',1;
IF JSON_VALUE(@Previous,'$.created')=N'true' DELETE dbo.MapFeatures WHERE MapID=@ResourceID AND FeatureID=@feature;
ELSE UPDATE dbo.MapFeatures SET X=TRY_CONVERT(float,JSON_VALUE(@Previous,'$.x')),Y=TRY_CONVERT(float,JSON_VALUE(@Previous,'$.y')),IsPlaced=CONVERT(bit,JSON_VALUE(@Previous,'$.isPlaced')) WHERE MapID=@ResourceID AND FeatureID=@feature;
END
ELSE
BEGIN
IF @X IS NULL OR @Y IS NULL OR ABS(@X)>100000 OR ABS(@Y)>100000 THROW 51012,'Choose a valid map position.',1;
IF @GeometryID IS NOT NULL AND @feature IS NULL THROW 51012,'Choose an existing map feature.',1;
IF @feature IS NULL
BEGIN
IF EXISTS(SELECT 1 FROM dbo.MapFeatures WHERE MapID=@ResourceID AND LocationID=@LocationID) THROW 51012,'This location already has a representation on the map. Reveal or explicitly reposition it.',1;
SET @feature=NEWID();SET @created=1;SET @old=N'{"created":true}';
INSERT dbo.MapFeatures(MapID,FeatureID,Name,Type,GeometryClass,Layer,X,Y,Width,Height,Rotation,ZOrder,IsPlaced,IsProvisional,IsLocked,ShowLabel,LabelX,LabelY,LocationID,GeometryJson)
SELECT @ResourceID,@feature,LocationName,N'Custom',N'Marker',N'Places',@X,@Y,48,48,0,40,1,0,0,1,0,0,@LocationID,N'{}' FROM dbo.Locations WHERE LocationID=@LocationID;
END
ELSE
BEGIN
IF @Replace=0 THROW 51012,'Confirm explicit repositioning.',1;
IF NOT EXISTS(SELECT 1 FROM dbo.MapFeatures WHERE MapID=@ResourceID AND FeatureID=@feature AND LocationID=@LocationID AND GeometryClass=N'Marker' AND IsLocked=0) THROW 51012,'Only an unlocked marker can be repositioned here. Use Maps for complex geometry.',1;
SELECT @old=(SELECT CONVERT(bit,0) created,X x,Y y,IsPlaced isPlaced FROM dbo.MapFeatures WHERE MapID=@ResourceID AND FeatureID=@feature FOR JSON PATH,WITHOUT_ARRAY_WRAPPER) FROM dbo.MapFeatures WHERE MapID=@ResourceID AND FeatureID=@feature;
UPDATE dbo.MapFeatures SET X=@X,Y=@Y,IsPlaced=1 WHERE MapID=@ResourceID AND FeatureID=@feature;
END;
END;
UPDATE dbo.StoryMaps SET Revision=Revision+1,ModifiedDate=@now WHERE MapID=@ResourceID;
SET @version=CONVERT(nvarchar(20),@revision+1);SET @GeometryID=CONVERT(nvarchar(50),@feature);
END
ELSE IF @Kind=N'room'
BEGIN
DECLARE @block int=TRY_CONVERT(int,@GeometryID),@floor int,@existing int,@stamp datetime2;
SELECT @floor=b.FloorPlanFloorID,@existing=b.LocationID,@stamp=COALESCE(b.ModifiedDate,b.CreatedDate),@version=CONVERT(varchar(64),HASHBYTES('SHA2_256',(SELECT b.* FOR JSON PATH,INCLUDE_NULL_VALUES)),2) FROM dbo.FloorPlanBlocks b WITH(UPDLOCK,HOLDLOCK) JOIN dbo.FloorPlanFloors f ON f.FloorPlanFloorID=b.FloorPlanFloorID JOIN dbo.FloorPlans p ON p.FloorPlanID=f.FloorPlanID WHERE b.FloorPlanBlockID=@block AND p.FloorPlanID=@ResourceID AND p.ProjectID=@project;
IF @floor IS NULL THROW 51010,'Room geometry unavailable.',1;
IF @version<>@Expected THROW 51011,'The room changed. Review its association again.',1;
IF @Restore=1 SET @LocationID=TRY_CONVERT(int,JSON_VALUE(@Previous,'$.locationId'));
IF @LocationID IS NULL OR NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@LocationID AND ProjectID=@project AND IsArchived=0) THROW 51012,'Choose an available room location.',1;
IF @existing<>@LocationID
BEGIN
IF @Replace=0 AND @Restore=0 THROW 51012,'Confirm replacement of the existing room association.',1;
IF EXISTS(SELECT 1 FROM dbo.FloorPlanTransitions WHERE FloorPlanFloorID=@floor AND(FromLocationID IN(@existing,@LocationID) OR ToLocationID IN(@existing,@LocationID))) THROW 51012,'This room has recorded transitions. Review its connected doors/windows in Floor Plans before changing its location identity.',1;
SET @old=(SELECT @existing locationId FOR JSON PATH,WITHOUT_ARRAY_WRAPPER);
UPDATE dbo.FloorPlanBlocks SET LocationID=@LocationID,ModifiedDate=CASE WHEN @now<=@stamp THEN DATEADD(NANOSECOND,100,@stamp) ELSE @now END WHERE FloorPlanBlockID=@block;
UPDATE dbo.FloorPlans SET ModifiedDate=@now WHERE FloorPlanID=@ResourceID;
END ELSE SET @changed=0;
SELECT @version=CONVERT(varchar(64),HASHBYTES('SHA2_256',(SELECT b.* FOR JSON PATH,INCLUDE_NULL_VALUES)),2) FROM dbo.FloorPlanBlocks b WHERE b.FloorPlanBlockID=@block;
END
ELSE IF @Kind=N'plan'
BEGIN
DECLARE @prior int;
SELECT @prior=p.LocationID,@version=CONVERT(varchar(64),HASHBYTES('SHA2_256',(SELECT p.* FOR JSON PATH,INCLUDE_NULL_VALUES)),2) FROM dbo.FloorPlans p WITH(UPDLOCK,HOLDLOCK) WHERE p.FloorPlanID=@ResourceID AND p.ProjectID=@project;
IF @version IS NULL THROW 51010,'Floor plan unavailable.',1;
IF @version<>@Expected THROW 51011,'The plan changed. Review its association again.',1;
IF @Restore=1 SET @LocationID=TRY_CONVERT(int,JSON_VALUE(@Previous,'$.locationId'));
IF @LocationID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@LocationID AND ProjectID=@project AND IsArchived=0) THROW 51012,'The original location is unavailable.',1;
IF @Restore=0 AND @LocationID IS NULL THROW 51012,'Choose a location.',1;
IF ISNULL(@prior,0)<>ISNULL(@LocationID,0)
BEGIN
IF @prior IS NOT NULL AND @Replace=0 AND @Restore=0 THROW 51012,'Confirm replacing the existing plan association.',1;
SET @old=(SELECT @prior locationId FOR JSON PATH,WITHOUT_ARRAY_WRAPPER,INCLUDE_NULL_VALUES);
UPDATE dbo.FloorPlans SET LocationID=@LocationID,ModifiedDate=CASE WHEN @now<=COALESCE(ModifiedDate,CreatedDate) THEN DATEADD(NANOSECOND,100,COALESCE(ModifiedDate,CreatedDate)) ELSE @now END WHERE FloorPlanID=@ResourceID;
END ELSE SET @changed=0;
SELECT @version=CONVERT(varchar(64),HASHBYTES('SHA2_256',(SELECT p.* FOR JSON PATH,INCLUDE_NULL_VALUES)),2) FROM dbo.FloorPlans p WHERE p.FloorPlanID=@ResourceID;
END ELSE THROW 51012,'Unknown spatial operation.',1;
IF @changed=1
BEGIN
DECLARE @audit TABLE(ID bigint);DECLARE @description nvarchar(500)=CONCAT(N'Spatial Context ',@Kind,CASE WHEN @Restore=1 THEN N' restored.' ELSE N' explicitly updated.' END);
INSERT @audit EXEC dbo.ProjectAudit_Record @ProjectID=@project,@UserID=@UserID,@ActivityType=N'Updated',@EntityType=N'Location',@EntityID=@LocationID,@EntityName=N'Spatial Context',@Description=@description;
END;
COMMIT;
SELECT @project ProjectID,@Kind Kind,@ResourceID ResourceID,@GeometryID GeometryID,@version Version,@old Previous,@changed Changed;
END TRY
BEGIN CATCH
IF XACT_STATE()<>0 ROLLBACK;
THROW;
END CATCH;
END;
GO

View File

@ -1,4 +1,5 @@
@model FloorPlanEditorViewModel
@using static PlotLine.Services.FloorPlanPresentation
@{
ViewData["Title"] = Model.FloorPlan.FloorPlanID == 0 ? "New Floor Plan" : Model.FloorPlan.Name;
ViewData["ProjectSection"] = "Floor Plans";
@ -21,58 +22,6 @@
.ToDictionary(x => x.Key, x => x.Count());
var activeOccupancyScene = Model.OccupancyScenes.FirstOrDefault();
var selectedBlockId = int.TryParse(Context.Request.Query["selectedBlockId"], out var parsedSelectedBlockId) ? parsedSelectedBlockId : 0;
string BlockClass(string blockType) => $"floor-plan-block floor-plan-block--{blockType.ToLowerInvariant()}";
string CssNumber(decimal value) => value.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture);
string TransitionDetails(FloorPlanTransitionEditViewModel transition)
{
var details = $"{transition.FromLocationName} -> {transition.ToLocationName}\n{transition.TransitionType}";
return string.IsNullOrWhiteSpace(transition.DisplayLabel) ? details : $"{details}\n{transition.DisplayLabel}";
}
string TransitionMarkerType(string? transitionType)
{
var normalized = (transitionType ?? string.Empty)
.Trim()
.Replace(" ", string.Empty, StringComparison.OrdinalIgnoreCase)
.Replace("-", string.Empty, StringComparison.OrdinalIgnoreCase)
.ToLowerInvariant();
return normalized switch
{
"door" => "door",
"doubledoor" => "double-door",
"frenchdoor" or "frenchdoors" => "french-door",
"slidingdoor" or "slidingdoors" => "sliding-door",
"window" => "window",
"archway" or "opening" => "archway",
"secretdoor" or "hiddendoor" => "secret-door",
"blockeddoor" => "blocked-door",
"exteriordoor" => "exterior-door",
"stairs" or "stair" or "stairsup" or "stairsdown" => "stairs",
"ladder" or "ladders" => "ladder",
"passage" or "openpassage" => "passage",
"hiddenpassage" or "secretpassage" => "secret-route",
_ => "other"
};
}
string TransitionMarkerSvg(string markerType) => markerType switch
{
"door" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M2 9h6""/><path class=""marker-line"" d=""M10 9h6""/><path class=""marker-arc"" d=""M8 9a6 6 0 0 1 6-6""/></svg>",
"double-door" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M2 9h4""/><path class=""marker-line"" d=""M12 9h4""/><path class=""marker-arc"" d=""M6 9a4 4 0 0 1 4-4""/><path class=""marker-arc"" d=""M12 9a4 4 0 0 0-4-4""/></svg>",
"french-door" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line marker-strong"" d=""M2 9h3""/><path class=""marker-line marker-strong"" d=""M13 9h3""/><path class=""marker-arc"" d=""M5 9a4 4 0 0 1 4-4""/><path class=""marker-arc"" d=""M13 9a4 4 0 0 0-4-4""/><path class=""marker-line"" d=""M9 5v8""/></svg>",
"sliding-door" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M2 9h14""/><path class=""marker-line marker-track"" d=""M4 6h10""/><path class=""marker-line marker-track"" d=""M9 6l3 3""/></svg>",
"window" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-window"" d=""M3 7h12""/><path class=""marker-window"" d=""M3 11h12""/><path class=""marker-line"" d=""M5 9h8""/></svg>",
"archway" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M2 14h4""/><path class=""marker-line"" d=""M12 14h4""/><path class=""marker-arc"" d=""M6 14a3 3 0 0 1 6 0""/></svg>",
"secret-door" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line marker-dotted"" d=""M2 9h6""/><path class=""marker-line marker-dotted"" d=""M10 9h6""/><path class=""marker-arc marker-dotted"" d=""M8 9a6 6 0 0 1 6-6""/></svg>",
"blocked-door" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M2 9h14""/><path class=""marker-blocked"" d=""M6 5l6 8""/><path class=""marker-blocked"" d=""M12 5l-6 8""/></svg>",
"exterior-door" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line marker-strong"" d=""M2 9h6""/><path class=""marker-line marker-strong"" d=""M10 9h6""/><path class=""marker-arc marker-strong"" d=""M8 9a6 6 0 0 1 6-6""/></svg>",
"stairs" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M4 13h10""/><path class=""marker-line"" d=""M5 10h8""/><path class=""marker-line"" d=""M6 7h6""/><path class=""marker-line"" d=""M7 4h4""/></svg>",
"ladder" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M6 3v12""/><path class=""marker-line"" d=""M12 3v12""/><path class=""marker-line"" d=""M6 5h6""/><path class=""marker-line"" d=""M6 8h6""/><path class=""marker-line"" d=""M6 11h6""/><path class=""marker-line"" d=""M6 14h6""/></svg>",
"passage" => @"<svg viewBox=""0 0 18 18"" aria-hidden=""true"" focusable=""false""><path class=""marker-line"" d=""M3 7h12""/><path class=""marker-line"" d=""M3 11h12""/><path class=""marker-line"" d=""M11 5l4 4-4 4""/><path class=""marker-line"" d=""M7 5L3 9l4 4""/></svg>",
_ => @"<span aria-hidden=""true"">x</span>"
};
var transitionPositions = FloorPlanTransitionPositions.All
.Select(x => new SelectListItem(x, x))
.ToList();
@ -426,125 +375,7 @@
</div>
</aside>
<section class="floor-plan-stage">
@for (var i = 0; i < Model.Floors.Count; i++)
{
var floor = Model.Floors[i];
var isActive = floor.FloorPlanFloorID == activeFloor?.FloorPlanFloorID;
var floorBlocks = blocksByFloor.GetValueOrDefault(floor.FloorPlanFloorID) ?? [];
var floorTransitions = transitionsByFloor.GetValueOrDefault(floor.FloorPlanFloorID) ?? [];
<div class="floor-plan-floor @(isActive ? "active" : string.Empty)" data-floor-panel="@floor.FloorPlanFloorID" data-floor-order="@floor.SortOrder">
<div class="floor-plan-grid-wrap">
<div class="floor-plan-grid"
style="--grid-width:@floor.GridWidth;--grid-height:@floor.GridHeight;"
data-floor-grid="@floor.FloorPlanFloorID"
data-grid-width="@floor.GridWidth"
data-grid-height="@floor.GridHeight">
@if (!string.IsNullOrWhiteSpace(floor.BackgroundImagePath))
{
<img class="floor-plan-background-image @(floor.BackgroundLocked ? "is-locked" : string.Empty)"
src="@floor.BackgroundImagePath"
alt=""
style="--bg-opacity:@CssNumber(floor.BackgroundOpacity);--bg-scale:@CssNumber(floor.BackgroundScale);--bg-offset-x:@CssNumber(floor.BackgroundOffsetX)px;--bg-offset-y:@CssNumber(floor.BackgroundOffsetY)px;"
data-background-image="@floor.FloorPlanFloorID" />
}
@foreach (var block in floorBlocks)
{
var blockIndex = Model.Blocks.FindIndex(x => x.FloorPlanBlockID == block.FloorPlanBlockID);
<button type="button"
class="@BlockClass(block.BlockType)"
style="--x:@block.X;--y:@block.Y;--w:@block.WidthCells;--h:@block.HeightCells;"
data-block="@block.FloorPlanBlockID"
data-block-index="@blockIndex"
data-floor-id="@block.FloorPlanFloorID"
data-location-id="@block.LocationID"
data-location-name="@block.LocationName"
data-location-path="@block.LocationPath"
data-location-title="@block.LocationPath"
title="@block.LocationPath">
<span class="floor-plan-block-label"><svg aria-hidden="true" class="floor-plan-location-pin" width="12" height="14" viewBox="0 0 16 20" fill="none" stroke="currentColor"><path d="M8 19S1 11 1 7a7 7 0 0 1 14 0c0 4-7 12-7 12Z"/><circle cx="8" cy="7" r="2.5"/></svg> @block.DisplayLabel</span>
<span class="floor-plan-resize-handle" data-resize-handle aria-hidden="true"></span>
</button>
if (block.LocationID.HasValue && firstBlockIdByFloorLocation.GetValueOrDefault($"{block.FloorPlanFloorID}:{block.LocationID.Value}") == block.FloorPlanBlockID)
{
var locationTokens = Model.OccupancyScenes
.SelectMany(scene => occupancyTokensByFloorLocation.GetValueOrDefault($"{scene.SceneID}:{block.FloorPlanFloorID}:{block.LocationID.Value}") ?? [])
.ToList();
if (locationTokens.Any())
{
foreach (var group in locationTokens.GroupBy(x => x.SceneID))
{
var tokens = group.ToList();
var tokenTitle = string.Join(", ", tokens.Select(x => x.DisplayName));
<div class="floor-plan-occupancy-tray"
style="--x:@block.X;--y:@block.Y;--w:@block.WidthCells;--h:@block.HeightCells;"
data-occupancy-tray
data-occupancy-floor="@block.FloorPlanFloorID"
data-occupancy-location="@block.LocationID"
data-occupancy-scene="@group.Key"
title="@tokenTitle">
@foreach (var token in tokens.Take(3))
{
var imagePath = !string.IsNullOrWhiteSpace(token.ThumbnailPath) ? token.ThumbnailPath : token.ImagePath;
<span class="floor-plan-occupancy-token floor-plan-occupancy-token--@token.EntityType.ToLowerInvariant()" title="@token.DisplayName">
@if (!string.IsNullOrWhiteSpace(imagePath))
{
<img src="@imagePath" alt="@token.DisplayName" loading="lazy" />
}
else
{
<span>@AvatarHelper.Initials(token.DisplayName)</span>
}
</span>
}
@if (tokens.Count > 3)
{
<span class="floor-plan-occupancy-more">+@(tokens.Count - 3)</span>
}
<span class="visually-hidden">Occupancy tokens help: characters and assets placed in this scene.</span>
</div>
}
}
}
}
@foreach (var scene in Model.OccupancyScenes)
{
var totalTokens = occupancyTokenCountByScene.GetValueOrDefault(scene.SceneID);
var floorTokens = occupancyTokenCountBySceneFloor.GetValueOrDefault($"{scene.SceneID}:{floor.FloorPlanFloorID}");
if (totalTokens == 0)
{
<div class="floor-plan-occupancy-message" data-occupancy-message data-occupancy-scene="@scene.SceneID" data-occupancy-floor="@floor.FloorPlanFloorID" hidden>No occupancy has been set for this scene.</div>
}
else if (floorTokens == 0)
{
<div class="floor-plan-occupancy-message" data-occupancy-message data-occupancy-scene="@scene.SceneID" data-occupancy-floor="@floor.FloorPlanFloorID" hidden>Scene has occupancy, but none of the assigned locations are placed on this floor.</div>
}
else if (floorTokens < totalTokens)
{
<div class="floor-plan-occupancy-message" data-occupancy-message data-occupancy-scene="@scene.SceneID" data-occupancy-floor="@floor.FloorPlanFloorID" hidden>Some occupants are on other floors. <help-icon key="floorPlans.occupancy.otherFloors" mode="inline" /></div>
}
}
@foreach (var transition in floorTransitions)
{
var transitionDetails = TransitionDetails(transition);
var markerType = TransitionMarkerType(transition.TransitionType);
<div class="floor-plan-transition-marker floor-plan-transition-marker--@markerType"
data-transition-marker="@transition.FloorPlanTransitionID"
data-from-location-id="@transition.FromLocationID"
data-to-location-id="@transition.ToLocationID"
data-transition-type="@markerType"
data-transition-kind="@transition.TransitionType"
data-position-within-location="@transition.PositionWithinLocation"
title="@transitionDetails"
aria-label="@transitionDetails">
@Html.Raw(TransitionMarkerSvg(markerType))
</div>
}
</div>
</div>
</div>
}
</section>
<partial name="_FloorPlanStage" model="Model" />
<aside class="floor-plan-side-panel floor-plan-inspector" aria-label="Inspector">
<div class="floor-plan-toolbox">
@ -1029,10 +860,13 @@
@section Scripts {
<partial name="_ValidationScriptsPartial" />
<script src="~/js/floor-plan-renderer.js" asp-append-version="true"></script>
<script src="~/js/workspace-surface.js" asp-append-version="true"></script>
<script>
window.initializeFloorPlanEditor = (options = {}) => {
const editor = document.querySelector("[data-floor-plan-editor]");
const {normalizeTransitionType,isStairTransition,isLadderTransition,isInsideLocationTransition,isUnrestrictedTransition,isSecretRouteTransition,isVisibleEntranceTransition}=window.PlotDirectorFloorPlanRenderer;
const {refreshSharedWalls,refreshHiddenLocationStyles,positionTransitions,locationCenter}=window.PlotDirectorFloorPlanRenderer.create(editor,{readBlock});
if (!editor) return;
if (editor.dataset.floorPlanInitialized === "true") return;
editor.dataset.floorPlanInitialized = "true";
@ -1993,46 +1827,6 @@
return aStart < bStart + bLength && bStart < aStart + aLength;
}
function normalizeTransitionType(type) {
return (type || "").toLowerCase().replace(/[^a-z0-9]/g, "");
}
function isStairTransition(type) {
return normalizeTransitionType(type) === "stairsup" || normalizeTransitionType(type) === "stairsdown";
}
function isLadderTransition(type) {
return ["ladder", "ladders"].includes(normalizeTransitionType(type));
}
function isInsideLocationTransition(type) {
return isStairTransition(type) || isLadderTransition(type);
}
function isUnrestrictedTransition(type) {
return ["hiddenpassage", "openpassage", "secretpassage"].includes(normalizeTransitionType(type));
}
function isSecretRouteTransition(type) {
return ["hiddenpassage", "secretpassage"].includes(normalizeTransitionType(type));
}
function isVisibleEntranceTransition(type) {
return [
"door",
"doubledoor",
"frenchdoor",
"frenchdoors",
"slidingdoor",
"slidingdoors",
"exteriordoor",
"archway",
"openpassage",
"stairsup",
"stairsdown"
].includes(normalizeTransitionType(type));
}
function blocksTouchAlongEdge(a, b) {
const verticalTouch = a.x + a.w === b.x || b.x + b.w === a.x;
const verticalOverlap = a.y < b.y + b.h && b.y < a.y + a.h;
@ -2211,259 +2005,6 @@
setTransitionOptions(toSelect, options, message, emptyMessage);
}
function subtractRange(segments, start, end) {
return segments.flatMap(segment => {
const clippedStart = Math.max(segment.start, start);
const clippedEnd = Math.min(segment.end, end);
if (clippedStart >= clippedEnd) return [segment];
return [
{ start: segment.start, end: clippedStart },
{ start: clippedEnd, end: segment.end }
].filter(next => next.end > next.start);
});
}
function renderWallSegment(block, side, start, end, total) {
if (end <= start || total <= 0) return;
const segment = document.createElement("span");
segment.dataset.wallSegment = side;
segment.className = `floor-plan-wall-segment floor-plan-wall-segment--${side}`;
segment.style.setProperty("--wall-start", `${(start / total) * 100}%`);
segment.style.setProperty("--wall-length", `${((end - start) / total) * 100}%`);
block.append(segment);
}
function visibleEdgeSegments(item, visibleBlocks, side) {
const axisStart = side === "east" || side === "west" ? item.y : item.x;
const axisLength = side === "east" || side === "west" ? item.h : item.w;
let segments = [{ start: 0, end: axisLength }];
visibleBlocks.forEach(other => {
if (item === other || !item.block.dataset.locationId || item.block.dataset.locationId !== other.block.dataset.locationId) return;
let touches = false;
let overlapStart = 0;
let overlapEnd = 0;
if (side === "east" && item.x + item.w === other.x) {
touches = true;
overlapStart = Math.max(item.y, other.y) - axisStart;
overlapEnd = Math.min(item.y + item.h, other.y + other.h) - axisStart;
} else if (side === "west" && other.x + other.w === item.x) {
touches = true;
overlapStart = Math.max(item.y, other.y) - axisStart;
overlapEnd = Math.min(item.y + item.h, other.y + other.h) - axisStart;
} else if (side === "south" && item.y + item.h === other.y) {
touches = true;
overlapStart = Math.max(item.x, other.x) - axisStart;
overlapEnd = Math.min(item.x + item.w, other.x + other.w) - axisStart;
} else if (side === "north" && other.y + other.h === item.y) {
touches = true;
overlapStart = Math.max(item.x, other.x) - axisStart;
overlapEnd = Math.min(item.x + item.w, other.x + other.w) - axisStart;
}
if (touches && overlapStart < overlapEnd) {
segments = subtractRange(segments, overlapStart, overlapEnd);
}
});
return segments;
}
function refreshWallSegments(visibleBlocks) {
visibleBlocks.forEach(item => {
item.block.querySelectorAll("[data-wall-segment]").forEach(segment => segment.remove());
["north", "east", "south", "west"].forEach(side => {
const total = side === "east" || side === "west" ? item.h : item.w;
visibleEdgeSegments(item, visibleBlocks, side).forEach(segment => {
renderWallSegment(item.block, side, segment.start, segment.end, total);
});
});
});
}
function refreshSharedWalls(activePanel) {
const visibleBlocks = [...activePanel.querySelectorAll("[data-block]")].map(block => ({ block, ...readBlock(block) }));
refreshWallSegments(visibleBlocks);
return visibleBlocks;
}
function locationCenter(blocksForLocation) {
if (blocksForLocation.length === 0) return null;
const minX = Math.min(...blocksForLocation.map(item => item.x));
const minY = Math.min(...blocksForLocation.map(item => item.y));
const maxX = Math.max(...blocksForLocation.map(item => item.x + item.w));
const maxY = Math.max(...blocksForLocation.map(item => item.y + item.h));
return { x: (minX + maxX) / 2, y: (minY + maxY) / 2 };
}
function refreshHiddenLocationStyles(visibleBlocks) {
const visibleEntranceLocationIds = new Set();
editor.querySelectorAll("[data-transition-marker]").forEach(marker => {
if (!isVisibleEntranceTransition(marker.dataset.transitionKind)) return;
if (marker.dataset.fromLocationId) visibleEntranceLocationIds.add(marker.dataset.fromLocationId);
if (marker.dataset.toLocationId) visibleEntranceLocationIds.add(marker.dataset.toLocationId);
});
visibleBlocks.forEach(item => {
const locationId = item.block.dataset.locationId;
const isHidden = !!locationId && !visibleEntranceLocationIds.has(locationId);
item.block.classList.toggle("is-hidden-location", isHidden);
const baseTitle = item.block.dataset.locationTitle || item.block.dataset.locationPath || item.block.dataset.locationName || "";
item.block.title = isHidden
? `${baseTitle}${baseTitle ? "\n" : ""}Hidden location: no visible entrance`
: baseTitle;
});
}
function renderSecretRoute(activePanel, marker, fromCenter, toCenter) {
if (!fromCenter || !toCenter) return;
const dx = toCenter.x - fromCenter.x;
const dy = toCenter.y - fromCenter.y;
const length = Math.sqrt(dx * dx + dy * dy);
if (length <= 0) return;
const route = document.createElement("span");
route.className = "floor-plan-secret-route";
route.dataset.secretRoute = marker.dataset.transitionMarker || "";
route.style.setProperty("--route-x", fromCenter.x);
route.style.setProperty("--route-y", fromCenter.y);
route.style.setProperty("--route-length", length);
route.style.setProperty("--route-angle", `${Math.atan2(dy, dx)}rad`);
route.title = marker.title || "";
route.setAttribute("aria-hidden", "true");
activePanel.querySelector("[data-floor-grid]")?.append(route);
}
function sharedTransitionEdge(fromBlocks, toBlocks) {
let best = null;
fromBlocks.forEach(from => {
toBlocks.forEach(to => {
if (from.x + from.w === to.x || to.x + to.w === from.x) {
const start = Math.max(from.y, to.y);
const end = Math.min(from.y + from.h, to.y + to.h);
const length = end - start;
if (length > 0 && (!best || length > best.length)) {
best = {
length,
orientation: "vertical",
start,
end,
x: from.x + from.w === to.x ? to.x : from.x,
y: start + length / 2
};
}
}
if (from.y + from.h === to.y || to.y + to.h === from.y) {
const start = Math.max(from.x, to.x);
const end = Math.min(from.x + from.w, to.x + to.w);
const length = end - start;
if (length > 0 && (!best || length > best.length)) {
best = {
length,
orientation: "horizontal",
start,
end,
x: start + length / 2,
y: from.y + from.h === to.y ? to.y : from.y
};
}
}
});
});
return best;
}
function positionWithinLocation(blocksForLocation, position) {
const center = locationCenter(blocksForLocation);
if (!center) return null;
const minX = Math.min(...blocksForLocation.map(item => item.x));
const minY = Math.min(...blocksForLocation.map(item => item.y));
const maxX = Math.max(...blocksForLocation.map(item => item.x + item.w));
const maxY = Math.max(...blocksForLocation.map(item => item.y + item.h));
const inset = 0.35;
const normalized = (position || "Centre").toLowerCase().replace(/\s+/g, "");
const x = normalized.includes("west") ? minX + inset : normalized.includes("east") ? maxX - inset : center.x;
const y = normalized.includes("north") ? minY + inset : normalized.includes("south") ? maxY - inset : center.y;
return { x, y };
}
function positionTransitions(activePanel, visibleBlocks) {
const markerPositions = [];
activePanel.querySelectorAll("[data-secret-route]").forEach(route => route.remove());
activePanel.querySelectorAll("[data-transition-marker]").forEach(marker => {
const fromBlocks = visibleBlocks.filter(item => item.block.dataset.locationId === marker.dataset.fromLocationId);
const toBlocks = visibleBlocks.filter(item => item.block.dataset.locationId === marker.dataset.toLocationId);
const fromCenter = locationCenter(fromBlocks);
const toCenter = locationCenter(toBlocks);
if (isSecretRouteTransition(marker.dataset.transitionKind)) {
marker.hidden = true;
if (fromCenter && toCenter) {
renderSecretRoute(activePanel, marker, fromCenter, toCenter);
}
return;
}
if (fromBlocks.length === 0 || (!isInsideLocationTransition(marker.dataset.transitionKind) && toBlocks.length === 0)) {
marker.hidden = true;
return;
}
const insidePlacement = isInsideLocationTransition(marker.dataset.transitionKind)
? positionWithinLocation(fromBlocks, marker.dataset.positionWithinLocation)
: null;
const sharedEdge = insidePlacement ? null : sharedTransitionEdge(fromBlocks, toBlocks);
marker.hidden = false;
marker.classList.toggle("is-shared-edge", !!sharedEdge);
marker.classList.toggle("is-inside-location", !!insidePlacement);
marker.classList.toggle("is-horizontal", sharedEdge?.orientation === "horizontal");
marker.classList.toggle("is-vertical", sharedEdge?.orientation === "vertical");
const pairKey = [marker.dataset.fromLocationId, marker.dataset.toLocationId].sort().join("-");
const key = insidePlacement
? `${pairKey}:inside:${normalizeTransitionType(marker.dataset.transitionKind)}:${marker.dataset.positionWithinLocation || "Centre"}:${insidePlacement.x}:${insidePlacement.y}`
: sharedEdge
? `${pairKey}:${sharedEdge.orientation}:${sharedEdge.x}:${sharedEdge.y}:${sharedEdge.start}:${sharedEdge.end}`
: `${pairKey}:fallback`;
markerPositions.push({ marker, insidePlacement, sharedEdge, fromCenter, toCenter, key });
});
const groups = markerPositions.reduce((map, item) => {
if (!map.has(item.key)) map.set(item.key, []);
map.get(item.key).push(item);
return map;
}, new Map());
groups.forEach(group => {
group.forEach((item, index) => {
const fraction = (index + 1) / (group.length + 1);
let x;
let y;
if (item.insidePlacement) {
x = item.insidePlacement.x;
y = item.insidePlacement.y;
} else if (item.sharedEdge?.orientation === "vertical") {
x = item.sharedEdge.x;
y = item.sharedEdge.start + item.sharedEdge.length * fraction;
} else if (item.sharedEdge?.orientation === "horizontal") {
x = item.sharedEdge.start + item.sharedEdge.length * fraction;
y = item.sharedEdge.y;
} else {
x = item.fromCenter.x + (item.toCenter.x - item.fromCenter.x) * fraction;
y = item.fromCenter.y + (item.toCenter.y - item.fromCenter.y) * fraction;
}
item.marker.style.setProperty("--transition-x", x);
item.marker.style.setProperty("--transition-y", y);
});
});
}
function cellFromPointer(grid, event) {
const rect = grid.getBoundingClientRect();
const gridWidth = Number(grid.dataset.gridWidth || 24);

View File

@ -0,0 +1,141 @@
@model FloorPlanEditorViewModel
@using static PlotLine.Services.FloorPlanPresentation
@{
var activeFloor = Model.Floors.OrderBy(x => x.SortOrder).ThenBy(x => x.Name).FirstOrDefault();
var blocksByFloor = Model.Blocks.GroupBy(x => x.FloorPlanFloorID).ToDictionary(x => x.Key, x => x.ToList());
var transitionsByFloor = Model.Transitions.GroupBy(x => x.FloorPlanFloorID).ToDictionary(x => x.Key, x => x.ToList());
var firstBlockIdByFloorLocation = Model.Blocks
.Where(x => x.LocationID.HasValue)
.GroupBy(x => $"{x.FloorPlanFloorID}:{x.LocationID!.Value}")
.ToDictionary(x => x.Key, x => x.OrderBy(block => block.Y).ThenBy(block => block.X).First().FloorPlanBlockID);
var occupancyTokensByFloorLocation = Model.OccupancyTokens
.GroupBy(x => $"{x.SceneID}:{x.FloorPlanFloorID}:{x.LocationID}")
.ToDictionary(x => x.Key, x => x.OrderBy(token => token.EntityType == "Character" ? 0 : 1).ThenBy(token => token.DisplayName).ToList());
var occupancyTokenCountByScene = Model.OccupancyTokens
.GroupBy(x => x.SceneID)
.ToDictionary(x => x.Key, x => x.Count());
var occupancyTokenCountBySceneFloor = Model.OccupancyTokens
.GroupBy(x => $"{x.SceneID}:{x.FloorPlanFloorID}")
.ToDictionary(x => x.Key, x => x.Count());
var activeOccupancyScene = Model.OccupancyScenes.FirstOrDefault();
}
<section class="floor-plan-stage">
@for (var i = 0; i < Model.Floors.Count; i++)
{
var floor = Model.Floors[i];
var isActive = floor.FloorPlanFloorID == activeFloor?.FloorPlanFloorID;
var floorBlocks = blocksByFloor.GetValueOrDefault(floor.FloorPlanFloorID) ?? [];
var floorTransitions = transitionsByFloor.GetValueOrDefault(floor.FloorPlanFloorID) ?? [];
<div class="floor-plan-floor @(isActive ? "active" : string.Empty)" data-floor-panel="@floor.FloorPlanFloorID" data-floor-order="@floor.SortOrder">
<div class="floor-plan-grid-wrap">
<div class="floor-plan-grid"
style="--grid-width:@floor.GridWidth;--grid-height:@floor.GridHeight;"
data-floor-grid="@floor.FloorPlanFloorID"
data-grid-width="@floor.GridWidth"
data-grid-height="@floor.GridHeight">
@if (!string.IsNullOrWhiteSpace(floor.BackgroundImagePath))
{
<img class="floor-plan-background-image @(floor.BackgroundLocked ? "is-locked" : string.Empty)"
src="@floor.BackgroundImagePath"
alt=""
style="--bg-opacity:@CssNumber(floor.BackgroundOpacity);--bg-scale:@CssNumber(floor.BackgroundScale);--bg-offset-x:@CssNumber(floor.BackgroundOffsetX)px;--bg-offset-y:@CssNumber(floor.BackgroundOffsetY)px;"
data-background-image="@floor.FloorPlanFloorID" />
}
@foreach (var block in floorBlocks)
{
var blockIndex = Model.Blocks.FindIndex(x => x.FloorPlanBlockID == block.FloorPlanBlockID);
<button type="button"
class="@BlockClass(block.BlockType)"
style="--x:@block.X;--y:@block.Y;--w:@block.WidthCells;--h:@block.HeightCells;"
data-block="@block.FloorPlanBlockID"
data-block-index="@blockIndex"
data-floor-id="@block.FloorPlanFloorID"
data-location-id="@block.LocationID"
data-location-name="@block.LocationName"
data-location-path="@block.LocationPath"
data-location-title="@block.LocationPath"
title="@block.LocationPath">
<span class="floor-plan-block-label"><svg aria-hidden="true" class="floor-plan-location-pin" width="12" height="14" viewBox="0 0 16 20" fill="none" stroke="currentColor"><path d="M8 19S1 11 1 7a7 7 0 0 1 14 0c0 4-7 12-7 12Z"/><circle cx="8" cy="7" r="2.5"/></svg> @block.DisplayLabel</span>
<span class="floor-plan-resize-handle" data-resize-handle aria-hidden="true"></span>
</button>
if (block.LocationID.HasValue && firstBlockIdByFloorLocation.GetValueOrDefault($"{block.FloorPlanFloorID}:{block.LocationID.Value}") == block.FloorPlanBlockID)
{
var locationTokens = Model.OccupancyScenes
.SelectMany(scene => occupancyTokensByFloorLocation.GetValueOrDefault($"{scene.SceneID}:{block.FloorPlanFloorID}:{block.LocationID.Value}") ?? [])
.ToList();
if (locationTokens.Any())
{
foreach (var group in locationTokens.GroupBy(x => x.SceneID))
{
var tokens = group.ToList();
var tokenTitle = string.Join(", ", tokens.Select(x => x.DisplayName));
<div class="floor-plan-occupancy-tray"
style="--x:@block.X;--y:@block.Y;--w:@block.WidthCells;--h:@block.HeightCells;"
data-occupancy-tray
data-occupancy-floor="@block.FloorPlanFloorID"
data-occupancy-location="@block.LocationID"
data-occupancy-scene="@group.Key"
title="@tokenTitle">
@foreach (var token in tokens.Take(3))
{
var imagePath = !string.IsNullOrWhiteSpace(token.ThumbnailPath) ? token.ThumbnailPath : token.ImagePath;
<span class="floor-plan-occupancy-token floor-plan-occupancy-token--@token.EntityType.ToLowerInvariant()" title="@token.DisplayName">
@if (!string.IsNullOrWhiteSpace(imagePath))
{
<img src="@imagePath" alt="@token.DisplayName" loading="lazy" />
}
else
{
<span>@AvatarHelper.Initials(token.DisplayName)</span>
}
</span>
}
@if (tokens.Count > 3)
{
<span class="floor-plan-occupancy-more">+@(tokens.Count - 3)</span>
}
<span class="visually-hidden">Occupancy tokens help: characters and assets placed in this scene.</span>
</div>
}
}
}
}
@foreach (var scene in Model.OccupancyScenes)
{
var totalTokens = occupancyTokenCountByScene.GetValueOrDefault(scene.SceneID);
var floorTokens = occupancyTokenCountBySceneFloor.GetValueOrDefault($"{scene.SceneID}:{floor.FloorPlanFloorID}");
if (totalTokens == 0)
{
<div class="floor-plan-occupancy-message" data-occupancy-message data-occupancy-scene="@scene.SceneID" data-occupancy-floor="@floor.FloorPlanFloorID" hidden>No occupancy has been set for this scene.</div>
}
else if (floorTokens == 0)
{
<div class="floor-plan-occupancy-message" data-occupancy-message data-occupancy-scene="@scene.SceneID" data-occupancy-floor="@floor.FloorPlanFloorID" hidden>Scene has occupancy, but none of the assigned locations are placed on this floor.</div>
}
else if (floorTokens < totalTokens)
{
<div class="floor-plan-occupancy-message" data-occupancy-message data-occupancy-scene="@scene.SceneID" data-occupancy-floor="@floor.FloorPlanFloorID" hidden>Some occupants are on other floors. <help-icon key="floorPlans.occupancy.otherFloors" mode="inline" /></div>
}
}
@foreach (var transition in floorTransitions)
{
var transitionDetails = TransitionDetails(transition);
var markerType = TransitionMarkerType(transition.TransitionType);
<div class="floor-plan-transition-marker floor-plan-transition-marker--@markerType"
data-transition-marker="@transition.FloorPlanTransitionID"
data-from-location-id="@transition.FromLocationID"
data-to-location-id="@transition.ToLocationID"
data-transition-type="@markerType"
data-transition-kind="@transition.TransitionType"
data-position-within-location="@transition.PositionWithinLocation"
title="@transitionDetails"
aria-label="@transitionDetails">
@Html.Raw(TransitionMarkerSvg(markerType))
</div>
}
</div>
</div>
</div>
}
</section>

View File

@ -2,6 +2,7 @@
@using System.Text.Json
@{
if (ViewData["DetachedWorkspace"] is true) Layout = "_WorkspaceLayout";
if (ViewData["SpatialRenderer"] is true) Layout = "_SpatialRendererLayout";
ViewData["Title"] = Model.Document?.Map.Name ?? "Maps";
ViewData["ProjectSection"] = "Maps";
ViewData["ShellClass"] = "plotline-shell-wide maps-shell";
@ -94,6 +95,8 @@
<script src="~/js/maps-geography-engine.js" asp-append-version="true"></script>
<script src="~/js/maps-workspace.js" asp-append-version="true"></script>
<script src="~/js/maps-appearance.js" asp-append-version="true"></script>
@if(ViewData["SpatialRenderer"] is not true){
<script src="~/js/maps-story-engine.js" asp-append-version="true"></script>
<script src="~/js/maps-story.js" asp-append-version="true"></script>
}
}

View File

@ -0,0 +1,4 @@
@using System.Security.Claims
@inject PlotLine.Data.IAppearanceRepository AppearancePreferences
@{ var userID=int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var author)?author:0; var appearance=userID>0?await AppearancePreferences.GetAsync(userID):new ApplicationAppearance(); }
<!DOCTYPE html><html lang="en" data-theme="light" data-bs-theme="light"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>Spatial reference · PlotDirector</title><partial name="_ApplicationThemeBootstrap" model="appearance"/><link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css"/><link rel="stylesheet" href="~/css/site.css" asp-append-version="true"/><link rel="stylesheet" href="~/css/plotline-theme.css" asp-append-version="true"/><link rel="stylesheet" href="~/css/application-shell.css" asp-append-version="true"/><link rel="stylesheet" href="~/css/context-spatial.css" asp-append-version="true"/></head><body class="app-layout spatial-renderer-page">@RenderBody()<script src="~/js/application-theme-sync.js" asp-append-version="true"></script>@await RenderSectionAsync("Scripts",required:false)<script src="~/js/context-map-renderer.js" asp-append-version="true"></script></body></html>

View File

@ -8,10 +8,15 @@
new { id = "overview", displayName = "Overview", endpoint = Url.Action("ContextScene", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "reference", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "scene.focus" } },
new { id = "characters", displayName = "Characters in Scene", endpoint = Url.Action("ContextCharacters", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "characters", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "character.focus" } },
new { id = "names", displayName = "Names", endpoint = Url.Action("ContextNamesTab", "Writing"), scope = "Book", contentRefresh = "relevant-scope", lifecycle = "names", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty<string>() },
new { id = "relationships", displayName = "Relationships", endpoint = Url.Action("ContextRelationships", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "relationships", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "relationship.focus" } }
new { id = "relationships", displayName = "Relationships", endpoint = Url.Action("ContextRelationships", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "relationships", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "relationship.focus" } },
new { id = "locations", displayName = "Locations", endpoint = Url.Action("ContextLocations", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "spatial", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty<string>() },
new { id = "maps", displayName = "Maps", endpoint = Url.Action("ContextMaps", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "spatial", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty<string>() },
new { id = "floorplans", displayName = "Floor Plans", endpoint = Url.Action("ContextFloorPlans", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "spatial", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty<string>() }
};
}
<link rel="stylesheet" href="~/css/context-workspace.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/location-picker.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/context-spatial.css" asp-append-version="true" />
<main class="context-workspace" data-context-workspace data-user="@User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value"
data-scope-project-id="@Model.ProjectID" data-scope-book-id="@Model.BookID"
data-chapter-id="@(position?.ChapterId ?? Model.ChapterID)" data-scene-id="@(position?.SceneId ?? Model.SceneID)"
@ -60,6 +65,10 @@
<script src="~/js/context-names.js" asp-append-version="true"></script>
<script src="~/js/context-relationship-layout.js" asp-append-version="true"></script>
<script src="~/js/context-relationships.js" asp-append-version="true"></script>
<script src="~/js/location-picker.js" asp-append-version="true"></script>
<script src="~/js/location-types.js" asp-append-version="true"></script>
<script src="~/js/floor-plan-renderer.js" asp-append-version="true"></script>
<script src="~/js/context-spatial.js" asp-append-version="true"></script>
<script src="~/js/context-workspace.js" asp-append-version="true"></script>
<script src="~/js/context-environment.js" asp-append-version="true"></script>
<script src="~/js/context-windows.js" asp-append-version="true"></script>

View File

@ -0,0 +1,16 @@
@{ Layout = null; }
@model PlotLine.Services.Context.SpatialFragment
<div data-context-tab-fragment data-spatial-context="@Model.Kind" data-project-id="@Model.Scope.ProjectID" data-book-id="@Model.Scope.BookID" data-chapter-id="@Model.Scope.ChapterID" data-scene-id="@Model.Scope.SceneID" class="context-spatial">
<form hidden data-spatial-token>@Html.AntiForgeryToken()</form>
<div class="spatial-toolbar"><button type="button" data-spatial-return>Return to scene location</button><span data-spatial-status role="status"></span></div>
<p data-spatial-error class="text-danger" role="alert"></p>
@if(Model.Kind=="locations"){
<div class="spatial-location-layout"><nav data-spatial-scenes aria-label="Previous, current and next scene locations"></nav><section data-spatial-details aria-label="Inspected location"><p>Loading recorded locations…</p></section></div>
}else{
<div data-spatial-scenes class="spatial-scene-strip" aria-label="Scene locations"></div>
<div class="spatial-toolbar"><label>@(Model.Kind=="maps"?"Map":"Floor plan") <select data-spatial-resource aria-label="@(Model.Kind=="maps"?"Map":"Floor plan")"></select></label><button type="button" data-spatial-zoom="in" aria-label="Zoom in">+</button><button type="button" data-spatial-zoom="out" aria-label="Zoom out">−</button><button type="button" data-spatial-fit>@(Model.Kind=="maps"?"Fit scene locations":"Fit plan")</button><button type="button" data-spatial-centre>Centre on selection</button><button type="button" data-spatial-place>@(Model.Kind=="maps"?"Place location":"Associate room")</button><a data-spatial-advanced>Open in @(Model.Kind=="maps"?"Maps":"Floor Plans")</a></div>
<p data-spatial-resolution class="small muted"></p><div data-spatial-canvas class="spatial-canvas"></div><div data-spatial-feature></div>
}
<div data-spatial-operation class="spatial-operation" hidden></div>
<button type="button" data-spatial-undo hidden>Undo spatial change</button>
</div>

View File

@ -0,0 +1,8 @@
@{ Layout = null; }
@model PlotLine.Services.Context.SpatialFloorCanvas
@using System.Text.Json
<div data-spatial-floor-canvas>
<script type="application/json" data-room-versions>@Html.Raw(JsonSerializer.Serialize(Model.Versions,new JsonSerializerOptions(JsonSerializerDefaults.Web)))</script>
<div class="spatial-levels"><label>Floor / level <select class="form-select form-select-sm" data-spatial-floor>@foreach(var floor in Model.Model.Floors.OrderBy(x=>x.SortOrder).ThenBy(x=>x.Name)){<option value="@floor.FloorPlanFloorID">@floor.Name</option>}</select></label></div>
<div class="spatial-floor-viewport" tabindex="0" aria-label="Floor plan; drag blank space to pan, mouse wheel to zoom"><div data-spatial-floor-world><partial name="~/Views/FloorPlans/_FloorPlanStage.cshtml" model="Model.Model" /></div></div>
</div>

View File

@ -0,0 +1,8 @@
/* Shared contextual positions never replace taxonomy colours. */
.context-spatial,.spatial-renderer-page{--spatial-previous:var(--plotline-spatial-previous,#3685d9);--spatial-current:var(--plotline-spatial-current,#d69e20);--spatial-next:var(--plotline-spatial-next,#389b6c)}
.context-spatial{height:100%;min-height:0;min-width:0;display:flex;flex-direction:column;gap:.35rem;container-type:inline-size;color:var(--plotline-ink);padding:.35rem}
.spatial-toolbar{display:flex;flex-wrap:wrap;gap:.3rem;align-items:center;flex:none}.spatial-toolbar label{display:flex;gap:.35rem;align-items:center;min-width:0}.spatial-toolbar select{max-width:22rem;min-width:6rem}.context-spatial button,.context-spatial select,.context-spatial input,.context-spatial textarea,.pd-location-picker-dialog button{font:inherit;color:var(--plotline-ink);background:var(--plotline-surface);border:1px solid var(--plotline-border-soft);border-radius:.2rem;padding:.22rem .45rem}.context-spatial button:hover,.context-spatial button.active{background:var(--plotline-hover, var(--bs-secondary-bg));color:var(--plotline-ink)}.context-spatial button:disabled{opacity:.5}.context-spatial a{color:var(--bs-link-color)}.context-spatial p{margin:.2rem 0}.context-spatial h2{font-size:1.1rem;margin:.4rem 0;display:flex;align-items:center;gap:.35rem}.context-spatial small{display:block;color:var(--plotline-text-muted);overflow-wrap:anywhere}.context-spatial [data-spatial-error]:empty{display:none}.spatial-location-layout{display:grid;grid-template-columns:minmax(10rem,30%) minmax(0,1fr);flex:1;min-height:0;gap:.75rem}.spatial-location-layout>nav,.spatial-location-layout>section{overflow:auto;min-width:0;padding:.25rem}.spatial-scene{border-left:3px solid var(--spatial-indicator);padding:.35rem .5rem;margin-bottom:.4rem;min-width:0}.spatial-position-0{--spatial-indicator:var(--spatial-previous)}.spatial-position-1{--spatial-indicator:var(--spatial-current)}.spatial-position-2{--spatial-indicator:var(--spatial-next)}.spatial-scene>strong{display:block;font-size:.8rem}.spatial-scene button{display:flex;align-items:center;gap:.25rem;text-align:left;border:0;width:100%;overflow-wrap:anywhere}.spatial-type{display:inline-flex;flex:none}.spatial-type svg{width:1.15rem;height:1.15rem;stroke:currentColor;stroke-width:1.7;stroke-linejoin:round}.spatial-description{white-space:pre-wrap;overflow-wrap:anywhere;padding:.35rem 0;line-height:1.5}.spatial-path{display:flex;flex-wrap:wrap;gap:.2rem}.spatial-path button{border:0;font-size:.85rem}.spatial-path button+button:before{content:'› ';color:var(--plotline-text-muted)}.spatial-scene-strip{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));flex:none}.spatial-scene-strip small{font-size:.72rem}.spatial-canvas{flex:1;min-height:12rem;position:relative;overflow:hidden;background:var(--plotline-surface)}.spatial-canvas iframe{width:100%;height:100%;border:0;position:absolute;inset:0}.spatial-operation{border-top:2px solid var(--spatial-current);padding:.5rem;flex:none;max-height:65%;overflow:auto}.spatial-operation input,.spatial-operation textarea{display:block;width:100%;margin:.4rem 0}.spatial-operation button{margin-right:.4rem}.spatial-operation[hidden]{display:none}.spatial-floor-viewport{position:relative;overflow:hidden;flex:1;min-height:0;touch-action:none}.spatial-canvas [data-spatial-floor-canvas]{height:100%;display:flex;flex-direction:column}.spatial-levels{padding:.25rem}.spatial-levels select{width:auto;display:inline-block}.spatial-floor-viewport [data-spatial-floor-world]{position:absolute;transform-origin:0 0;left:0;top:0}.spatial-floor-viewport .floor-plan-stage{padding:0;border:0}.spatial-floor-viewport .floor-plan-grid-wrap{overflow:visible}.spatial-floor-viewport .floor-plan-block{cursor:pointer}.spatial-floor-viewport .spatial-selected{outline:3px solid var(--bs-primary);outline-offset:3px}.spatial-floor-viewport .spatial-drop{outline:4px dashed var(--spatial-next)}.spatial-room-badge{position:absolute;left:0;bottom:0;background:var(--plotline-surface);border-bottom:4px solid var(--spatial-indicator);font-size:11px;padding:1px 4px;z-index:8;color:var(--plotline-ink);white-space:nowrap}.spatial-floor-viewport .spatial-position-1{box-shadow:inset 0 0 0 4px var(--spatial-current)}.spatial-floor-viewport .spatial-position-0{outline:3px solid var(--spatial-previous)}.spatial-floor-viewport .spatial-position-2{border-bottom:4px solid var(--spatial-next)}
.spatial-renderer-page{height:100dvh;overflow:hidden;margin:0;padding:0}.spatial-renderer-page #mapsApp,.spatial-renderer-page .maps-body,.spatial-renderer-page .maps-centre{height:100%;width:100%;margin:0;padding:0;display:block;max-width:none;min-height:0}.spatial-renderer-page .maps-toolbar,.spatial-renderer-page .maps-status,.spatial-renderer-page .maps-library,.spatial-renderer-page .maps-details,.spatial-renderer-page .maps-story-toolbar,.spatial-renderer-page .maps-canvas-tools,.spatial-renderer-page #mapsBreadcrumbs,.spatial-renderer-page #mapsStory,.spatial-renderer-page #mapsSearchResults,.spatial-renderer-page #mapStoryScrubberRow,.spatial-renderer-page #mapsWelcome{display:none!important}.spatial-renderer-page #mapsCanvas{width:100%;height:100%;min-height:0}.spatial-renderer-page #mapsHandles{display:none}.spatial-map-ring{stroke:var(--spatial-indicator)}.spatial-map-badge{fill:var(--plotline-ink);stroke:var(--plotline-surface);stroke-width:3px;paint-order:stroke;pointer-events:none}.spatial-placing{cursor:crosshair!important}
@container(max-width:580px){.spatial-location-layout{grid-template-columns:minmax(0,1fr);grid-template-rows:auto minmax(0,1fr)}.spatial-location-layout>nav{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));max-height:13rem;gap:.2rem}.spatial-scene{padding:.2rem}.spatial-scene-strip small{display:none}.spatial-toolbar{font-size:.8rem}.spatial-toolbar select{max-width:12rem}}
.spatial-floor-viewport .floor-plan-resize-handle{display:none}

View File

@ -0,0 +1,26 @@
/* Read-only Context adapter around the canonical Maps workspace renderer. No SignalR or geometry saves. */
(() => {
if(!document.body.classList.contains('spatial-renderer-page'))return;
const api=window.PlotDirectorMapWorkspace,canvas=document.querySelector('#mapsCanvas'),app=document.querySelector('#mapsApp');if(!api||!canvas)return;
const origin=location.origin;let channel=null,highlights=[],placement=false,pointer=null;
const send=(action,extra={})=>{if(channel)parent.postMessage({type:'plotdirector.spatial.renderer',channel,action,...extra},origin);};
const ns='http://www.w3.org/2000/svg',layer=document.createElementNS(ns,'g');layer.dataset.spatialOverlay='';layer.setAttribute('pointer-events','none');canvas.append(layer);
function paint(){layer.replaceChildren();const scale=api.view.w/Math.max(canvas.clientWidth,1);for(const item of highlights){const f=api.document.features.find(f=>f.featureID===item.featureID);if(!f||!f.isPlaced)continue;const g=document.createElementNS(ns,'g');g.setAttribute('transform',`translate(${f.x} ${f.y})`);g.setAttribute('role','img');g.setAttribute('aria-label',item.label);const roles=[...new Set(item.roles)].sort((a,b)=>a-b);for(let i=0;i<roles.length;i++){const c=document.createElementNS(ns,'circle');c.setAttribute('r',String((15+i*5)*scale));c.setAttribute('class',`spatial-map-ring spatial-position-${roles[i]+1}`);c.setAttribute('fill','none');c.setAttribute('stroke-width',String(3*scale));g.append(c);}const text=document.createElementNS(ns,'text');text.textContent=roles.map(r=>['P','C','N'][r+1]).join(' · ');text.setAttribute('x',String(24*scale));text.setAttribute('y',String(-18*scale));text.setAttribute('font-size',String(13*scale));text.setAttribute('class','spatial-map-badge');g.append(text);const title=document.createElementNS(ns,'title');title.textContent=item.label;g.append(title);layer.append(g);}}
app.addEventListener('map-rendered',()=>{paint();send('viewport',{view:api.view});});
window.addEventListener('message',async e=>{if(e.origin!==origin||e.source!==parent||e.data?.type!=='plotdirector.spatial.command')return;const m=e.data;if(channel&&m.channel!==channel)return;channel=m.channel;
if(m.action==='init'){if(m.view)api.setView(m.view);send('ready',{map:api.document.map,features:api.document.features,view:api.view});}
if(m.action==='highlight'){highlights=m.highlights||[];paint();}
if(m.action==='zoom')api.zoom(1/m.factor);
if(m.action==='fit')api.fit(m.ids?.length?api.document.features.filter(f=>m.ids.includes(f.featureID)):api.document.features);
if(m.action==='centre'){const f=api.document.features.find(f=>f.featureID===m.id);if(f&&(m.force||f.x<api.view.x||f.x>api.view.x+api.view.w||f.y<api.view.y||f.y>api.view.y+api.view.h))api.focus(f.featureID);if(f)api.select(f.featureID);}
if(m.action==='placement'){placement=!!m.active;canvas.classList.toggle('spatial-placing',placement);}
if(m.action==='reload'){try{const r=await fetch(`/Maps/State?projectId=${api.document.map.projectID}&id=${api.document.map.mapID}`,{cache:'no-store'});if(!r.ok||r.redirected)throw Error('Map unavailable');api.replaceDocument(await r.json());send('ready',{map:api.document.map,features:api.document.features,view:api.view});}catch(error){send('error',{message:error.message});}}
});
canvas.addEventListener('pointerdown',e=>{pointer={x:e.clientX,y:e.clientY,id:e.target.closest('[data-feature-id],[data-boundary-feature-id]')?.dataset.featureId||e.target.closest('[data-boundary-feature-id]')?.dataset.boundaryFeatureId};if(placement){e.preventDefault();e.stopImmediatePropagation();canvas.setPointerCapture(e.pointerId);}},true);
canvas.addEventListener('pointerup',e=>{if(!pointer)return;const start=pointer;pointer=null;if(Math.hypot(start.x-e.clientX,start.y-e.clientY)>5)return;if(placement){e.preventDefault();e.stopImmediatePropagation();send('place',{point:{x:api.world(e)[0],y:api.world(e)[1]}});if(canvas.hasPointerCapture(e.pointerId))canvas.releasePointerCapture(e.pointerId);}else if(start.id){const f=api.document.features.find(f=>f.featureID===start.id);send('select',{feature:f});}},true);
canvas.addEventListener('dblclick',e=>{e.preventDefault();e.stopImmediatePropagation();},true);
canvas.addEventListener('dragover',e=>{if(e.dataTransfer.types.includes('application/x-plotdirector-spatial-location')){e.preventDefault();e.stopImmediatePropagation();e.dataTransfer.dropEffect='copy';}},true);
canvas.addEventListener('drop',e=>{e.preventDefault();e.stopImmediatePropagation();try{const payload=JSON.parse(e.dataTransfer.getData('application/x-plotdirector-spatial-location'));send('drop',{payload,point:{x:api.world(e)[0],y:api.world(e)[1]}});}catch{}},true);
window.addEventListener('keydown',e=>{if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'){e.preventDefault();e.stopImmediatePropagation();}if(e.key==='Escape'&&placement){e.preventDefault();e.stopImmediatePropagation();send('cancel');}},true);
canvas.addEventListener('keyup',e=>{if(['Enter',' '].includes(e.key)){const id=e.target.closest('[data-feature-id]')?.dataset.featureId;if(id)send('select',{feature:api.document.features.find(f=>f.featureID===id)});}});
})();

View File

@ -0,0 +1,67 @@
/* Spatial inspection is window-local. Persisted edits exclusively use authorised canonical services. */
(() => {
'use strict';
const instances=new WeakMap(),requests=new Map(),sessions=new WeakMap(),mime='application/x-plotdirector-spatial-location';
const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!=null)n.textContent=text;if(cls)n.className=cls;return n;};
const btn=(text,fn)=>{const b=el('button',text);b.type='button';b.onclick=()=>Promise.resolve().then(fn).catch(error=>window.PlotDirector?.toast?.error(error.message));return b;};
const same=(a,b)=>a?.bookId===b?.bookId&&a?.sceneId===b?.sceneId;
const id=l=>l?.locationID;
let invalidating=false;
function state(position,location,refresh=false){const url=`/SpatialContext/State?bookId=${position.bookId}&sceneId=${position.sceneId}${location?`&locationId=${location}`:''}`;if(refresh)requests.delete(url);if(requests.size>40)requests.delete(requests.keys().next().value);if(!requests.has(url))requests.set(url,fetch(url,{cache:'no-store'}).then(async r=>{if(!r.ok||r.redirected)throw Error('Spatial context is unavailable. Check book access and refresh.');const result=await r.json();if(!location&&result.scope.primaryLocationID)requests.set(`${url}&locationId=${result.scope.primaryLocationID}`,Promise.resolve(result));return result;}).catch(e=>{requests.delete(url);throw e;}));return requests.get(url);}
function session(root){if(!sessions.has(root))sessions.set(root,{location:null,scene:null,listeners:new Set(),revision:0,select(location,source,force=false){if(!force&&this.location===location)return;this.location=location;this.revision++;for(const fn of this.listeners)fn({version:1,location,source,revision:this.revision,windowId:root.contextController?.windowId,projectId:Number(root.dataset.scopeProjectId),bookId:Number(root.dataset.scopeBookId)});}});return sessions.get(root);}
function ancestors(data,location){const result=[],seen=new Set();while(location&&!seen.has(location)){seen.add(location);const r=data.locations.find(l=>id(l)===location);if(!r)break;result.push(r);location=r.parentLocationID;}return result;}
function path(data,location){return ancestors(data,location).reverse().map(l=>l.locationName).join(' / ');}
function resolution(data,location,kind){const links=kind==='maps'?data.maps:data.plans;for(const [depth,l]of ancestors(data,location).entries()){const found=links.filter(x=>x.locationID===id(l)&&(kind!=='maps'||x.isPlaced));if(found.length)return found.map(link=>({...link,depth,represented:id(l)})).sort((a,b)=>Number(!!b.blockID)-Number(!!a.blockID)||Number(!!b.floorID)-Number(!!a.floorID));}return [];}
function icon(data,location){const t=data.types.find(t=>t.assignable!==false&&String(t.value)===String(location?.locationTypeID??''));const n=el('span',null,`spatial-type text-${t?.tone||'secondary'}`);if(t?.path){const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('aria-hidden','true');const p=document.createElementNS(svg.namespaceURI,'path');p.setAttribute('d',t.path);p.setAttribute('fill',t.filled?'currentColor':'none');svg.append(p);n.append(svg);}n.title=t?.label||'Unclassified';return n;}
function mount(node,context){if(instances.has(node))return;const root=node.closest('[data-context-workspace]'),bus=session(root),kind=node.dataset.spatialContext,abort=new AbortController();let position=context.position,data,selection,loadedInspection,epoch=0,disposed=false,busy=false,resource=null,renderer=null,operation=null,undo=null;
const q=s=>node.querySelector(s),status=q('[data-spatial-status]'),error=q('[data-spatial-error]'),canvas=q('[data-spatial-canvas]');
const pref=`plotdirector.spatial.v1.${root.dataset.user}.${context.windowId}.${position.projectId}.${kind}`;let preferences={};try{preferences=JSON.parse(localStorage.getItem(pref))||{};}catch{}
const save=()=>{try{localStorage.setItem(pref,JSON.stringify(preferences));}catch{}};
const guard=(value,deferRefresh=false)=>{busy=value;node.dispatchEvent(new CustomEvent('context-panel-state',{bubbles:true,detail:{dirty:value,busy:false,deferRefresh}}));};
const fail=e=>{if(!disposed)error.textContent=e.message;};
async function post(route,body){const r=await fetch(route,{method:'POST',headers:{'Content-Type':'application/json','RequestVerificationToken':q('[name="__RequestVerificationToken"]').value},body:JSON.stringify(body)});const result=await r.json();if(!r.ok)throw Error(result.message||'The change could not be saved. Existing work is unchanged.');return result;}
async function reload(refresh=false){const current=++epoch,p={...position},location=bus.location;try{status.textContent='Loading spatial context…';const result=await state(p,location,refresh);if(disposed||current!==epoch||!same(position,p))return;data=result;loadedInspection=location??result.scope.primaryLocationID;if(bus.scene!==`${p.bookId}/${p.sceneId}`){bus.scene=`${p.bookId}/${p.sceneId}`;bus.select(data.scope.primaryLocationID,context.paneId);}selection=bus.location;status.textContent='';draw();}catch(e){if(current===epoch)fail(e);}}
async function select(location){bus.select(location,context.paneId);if(selection===location)return;selection=location;if(data?.locations.some(l=>id(l)===location)&&loadedInspection===location)draw();else await reload();}
const listener=message=>{if(disposed||busy||message.source===context.paneId)return;selection=message.location;if(data?.locations.some(l=>id(l)===selection)&&loadedInspection===selection)draw();else void reload();};bus.listeners.add(listener);
async function finish(result,route='/SpatialContext/Undo',inspection){if(result.assignment){if(result.assignment.result?.kind==='scene')inspection=result.id;result=result.assignment;}undo=result.undoToken?{token:result.undoToken,route}:null;q('[data-spatial-undo]').hidden=!undo;window.PlotDirector?.toast?.success('Spatial information saved.');guard(false,true);if(inspection!==undefined&&root.contextController.position.sceneId===position.sceneId){bus.location=inspection;bus.revision++;}root.contextController.invalidate({projectId:position.projectId,bookId:position.bookId,kind:'spatial'});}
q('[data-spatial-undo]').onclick=async()=>{try{const saved=undo;if(!saved)return;if(busy)throw Error('Finish or cancel the current operation before Undo.');await post(saved.route,{token:saved.token});undo=null;q('[data-spatial-undo]').hidden=true;root.contextController.invalidate({kind:'spatial',projectId:position.projectId,bookId:position.bookId});}catch(e){fail(e);}};
function clearOperation(){operation=null;q('[data-spatial-operation]').replaceChildren();q('[data-spatial-operation]').hidden=true;renderer?.command?.('placement',{active:false});guard(false);}
async function form(title,build,commit){if(busy)throw Error('Finish or cancel the current operation first.');const panel=q('[data-spatial-operation]');panel.hidden=false;panel.replaceChildren(el('strong',title));guard(true);const controls=await build(panel);panel.append(btn('Save',async()=>{try{const result=await commit(controls);clearOperation();await finish(result,result.attribute?'/LocationWorkspace/Undo':'/SpatialContext/Undo');}catch(e){fail(e);}}),btn('Cancel',clearOperation));controls?.focus?.();}
async function picker(title,selected,allowRoot=false){const content=el('div'),dialog=el('dialog',null,'pd-location-picker-dialog');dialog.append(el('h2',title),content);document.body.append(dialog);const wasBusy=busy;guard(true);try{const result=await window.PlotDirectorLocationPicker.data(position.projectId);const picker=window.PlotDirectorLocationPicker.mount(content,{...result,selected: selected==null?undefined:String(selected),allowRoot,rootLabel:allowRoot?'No assigned location':undefined});return await new Promise(resolve=>{let value;dialog.append(btn('Choose',()=>{if(picker.value===undefined)return;value=picker.value===''?null:Number(picker.value);dialog.close();}),btn('Cancel',()=>dialog.close()));dialog.addEventListener('close',()=>resolve(value),{once:true});dialog.showModal();picker.focus();});}finally{dialog.remove();guard(wasBusy);}}
function payload(location=selection){return {version:1,windowId:context.windowId,projectId:position.projectId,bookId:position.bookId,locationId:location};}
function validDrop(p){return p?.version===1&&p.windowId===context.windowId&&p.projectId===position.projectId&&p.bookId===position.bookId&&Number.isSafeInteger(p.locationId);}
function draggable(n,location){if(!location)return;n.draggable=true;n.addEventListener('dragstart',e=>{e.dataTransfer.setData(mime,JSON.stringify(payload(location)));e.dataTransfer.effectAllowed='copy';});}
function scenes(){const host=q('[data-spatial-scenes]');host.replaceChildren();for(const index of [-1,0,1]){const scene=data.scenes.find(s=>s.position===index),label=['Previous','Current','Next'][index+1],row=el('div',null,`spatial-scene spatial-position-${index+1}`);row.dataset.scenePosition=index;row.append(el('strong',`${label} scene`));if(!scene){row.append(el('small',index<0?'Start of manuscript':'End of manuscript'));host.append(row);continue;}const location=data.locations.find(l=>id(l)===scene.locationID);row.title=scene.label;const pick=btn(location?.locationName||'No location assigned',()=>select(scene.locationID));if(location)pick.prepend(icon(data,location));pick.classList.toggle('active',selection===scene.locationID&&!!selection);row.append(pick,el('small',scene.label));if(location){row.append(el('small',path(data,id(location))));const repeated=data.scenes.some(s=>s.position<index&&s.locationID===id(location));if(repeated)row.append(el('small','Same location'));const mapped=resolution(data,id(location),'maps'),plans=resolution(data,id(location),'floorplans');row.append(el('small',`${mapped.length?'◉ Map available':''}${mapped.length&&plans.length?' · ':''}${plans.length?'▣ Floor plan available':''}`));draggable(pick,id(location));}const recorded=data.assignments.filter(a=>a.sceneID===scene.sceneID&&a.kind!=='Scene location');if(recorded.length){const extra=el('details');extra.append(el('summary','Other recorded positions'));for(const a of recorded){const r=data.locations.find(l=>id(l)===a.locationID);if(r)extra.append(btn(`${r.locationName} · ${a.kind}`,()=>select(a.locationID)));}row.append(extra);}host.append(row);}}
async function assign(location){const target={bookID:position.bookId,sceneID:data.scope.sceneID,kind:'scene',expected:data.scope.version,locationID:location};await finish(await post('/SpatialContext/Mutate',target),'/SpatialContext/Undo',location);}
async function chooseAssignment(){const current=data.scope;const target={...position};const chosen=await picker(`Assign location to ${current.label}`,current.primaryLocationID,true);if(chosen===undefined)return;if(!same(position,target))throw Error('Scene changed. Choose the current scene location again.');await assign(chosen);}
async function edit(attribute,location){const fixed={...location},name=fixed.locationName;await form(`${attribute==='description'?'Edit description':'Rename'}: ${name}`,panel=>{const input=el(attribute==='description'?'textarea':'input');input.value=attribute==='description'?(fixed.description||''):name;input.setAttribute('aria-label',attribute);if(attribute==='description')input.rows=9;panel.append(input);return input;},input=>post('/LocationWorkspace/Assign',{projectId:position.projectId,attribute,changes:[{id:id(fixed),value:input.value,version:fixed.updatedDate}]}));}
async function discrete(attribute,location){const fixed={...location};let value;if(attribute==='type'){guard(true);try{value=await window.PlotDirectorLocationTypes.choose({taxonomy:data.types,selected:String(fixed.locationTypeID??'')});}finally{guard(false);}if(value===null)return;}else{await form(`Classification: ${fixed.locationName}`,panel=>{const input=el('select');for(const v of ['Unclassified','Real','Fictional','Fictionalised'])input.add(new Option(v,v==='Unclassified'?'':v));input.value=fixed.classification||'';panel.append(input);return input;},input=>post('/LocationWorkspace/Assign',{projectId:position.projectId,attribute,changes:[{id:id(fixed),value:input.value,version:fixed.updatedDate}]}));return;}await finish(await post('/LocationWorkspace/Assign',{projectId:position.projectId,attribute,changes:[{id:id(fixed),value,version:fixed.updatedDate}]}),'/LocationWorkspace/Undo');}
async function createLocation(assignScene=false,parent=selection,block=null){const target={...position},scope={...data.scope},plan=resource;await form(assignScene?`Create location for ${scope.label}`:block?'Create and associate location':'Create child location',panel=>{const name=el('input');name.placeholder='Location name';name.setAttribute('aria-label','Location name');let parentId=parent;const parentLabel=el('small',parent?`Parent: ${path(data,parent)}`:'Parent: Root level');panel.append(name,parentLabel,btn('Choose parent',async()=>{const chosen=await picker('Review containing location',parentId,true);if(chosen!==undefined){parentId=chosen;parentLabel.textContent=chosen?`Parent location ${chosen}`:'Parent: Root level';}}));return {name,parent:()=>parentId};},controls=>post('/SpatialContext/Create',{bookID:target.bookId,sceneID:scope.sceneID,name:controls.name.value,parentID:controls.parent(),expected:assignScene?scope.version:block?.version,planID:block?plan:null,blockID:block?String(block.id):null,replace:!!block}));}
async function showTool(tool){bus.select(selection,context.paneId,true);const visible=[...root.querySelectorAll('[data-context-pane]:not([hidden]) [data-context-tab]')].some(s=>s.value===tool);if(visible){root.contextController.openTool(tool,context.paneId,'other');return;}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))fail(Error('Finish or cancel editing in the destination pane first.'));}));dialog.append(btn('Cancel',()=>dialog.close()));dialog.onclose=()=>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));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'&&current.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;}
function sceneHighlights(){const grouped=new Map();for(const s of data.scenes){const found=resolution(data,s.locationID,kind).filter(l=>l.resourceID===resource);for(const f of found){const key=kind==='maps'?f.featureID:f.blockID;if(!key)continue;if(!grouped.has(key))grouped.set(key,{featureID:key,roles:[],label:[]});const value=grouped.get(key);value.roles.push(s.position);value.label.push(`${['Previous','Current','Next'][s.position+1]}: ${path(data,s.locationID)}${f.depth?' (containing location)':''}`);}}return [...grouped.values()].map(x=>({...x,label:x.label.join(' · ')}));}
function annotate(){if(kind==='locations'||!data)return;for(const scene of data.scenes){const row=q(`[data-scene-position="${scene.position}"]`);if(!row)continue;row.querySelector('.spatial-elsewhere')?.remove();const resolved=resolution(data,scene.locationID,kind),here=resolved.filter(l=>l.resourceID===resource);let label='';if(scene.locationID){if(!resolved.length)label=kind==='maps'?'No mapped representation':'No associated plan';else if(!here.length)label=kind==='maps'?'On another map':'On another plan';else if(kind==='floorplans'&&here.every(l=>l.floorID&&l.floorID!==renderer?.getFloor?.()))label='On another level';else if(kind==='floorplans'&&!here.some(l=>l.blockID))label='Plan available; no associated room';else if(here.some(l=>l.depth))label='Containing location represented';}if(label)row.append(el('small',label,'spatial-elsewhere'));}}
function highlight(){if(!renderer)return;annotate();renderer.highlight(sceneHighlights());const target=resolution(data,selection,kind).find(x=>x.resourceID===resource);if(renderer.selection!==selection){renderer.selection=selection;if(target){if(kind==='floorplans'&&!target.blockID&&target.floorID)renderer.floor?.(target.floorID);else renderer.centre(kind==='maps'?target.featureID:target.blockID,false);}}if(kind==='maps'&&bus.pendingPlacement&&renderer.map?.()){const target=bus.pendingPlacement;bus.pendingPlacement=null;void startPlacement(target).catch(fail);}}
async function renderResource(){if(!canvas)return;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;}renderer?.dispose();renderer=null;canvas.replaceChildren();const target=resource,scope={...position};if(kind==='maps'){const frame=el('iframe');frame.title='Context map';frame.src=`/SpatialContext/Map?bookId=${scope.bookId}&sceneId=${scope.sceneId}&id=${target}`;const channel=crypto.randomUUID();let features=[],map,ready=false;const command=(action,args={})=>frame.contentWindow?.postMessage({type:'plotdirector.spatial.command',channel,action,...args},location.origin);const receive=e=>{if(e.origin!==location.origin||e.source!==frame.contentWindow||e.data?.channel!==channel||e.data.type!=='plotdirector.spatial.renderer')return;const m=e.data;if(m.action==='ready'){features=m.features;map=m.map;ready=true;highlight();if(bus.pendingPlacement){const target=bus.pendingPlacement;bus.pendingPlacement=null;void startPlacement(target).catch(fail);}}if(m.action==='viewport'){preferences.views??={};preferences.views[target]=m.view;save();}if(m.action==='select'&&m.feature?.locationID)void select(m.feature.locationID);if(m.action==='cancel'&&operation)clearOperation();if(m.action==='place'&&operation)void savePlacement(m.point);if(m.action==='drop'&&validDrop(m.payload))void dropPlacement(m.payload.locationId,m.point);if(m.action==='error')fail(Error(m.message));};window.addEventListener('message',receive);renderer={id:target,revision:String(item.modifiedDate),command,highlight:items=>command('highlight',{highlights:items}),centre:(id,force)=>{if(ready)command('centre',{id,force});},fit:()=>command('fit',{ids:sceneHighlights().map(h=>h.featureID)}),zoom:factor=>command('zoom',{factor}),features:()=>features,map:()=>map,dispose:()=>window.removeEventListener('message',receive)};frame.onload=()=>command('init',{view:preferences.views?.[target]});canvas.append(frame);}else{const request=++epoch;try{const response=await fetch(`/SpatialContext/Floor?bookId=${scope.bookId}&sceneId=${scope.sceneId}&id=${target}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error('Floor plan unavailable.');const html=await response.text();if(disposed||request!==epoch||resource!==target)return;canvas.innerHTML=html;renderer=floorRenderer(canvas,item);highlight();}catch(e){fail(e);}}}
function floorRenderer(host,item){const container=host.querySelector('[data-spatial-floor-canvas]'),world=container.querySelector('[data-spatial-floor-world]'),viewport=container.querySelector('.spatial-floor-viewport'),level=container.querySelector('[data-spatial-floor]'),versions=JSON.parse(container.querySelector('[data-room-versions]').textContent);const engine=window.PlotDirectorFloorPlanRenderer.create(container);let view={x:0,y:0,scale:1},drag=null;const panels=[...container.querySelectorAll('[data-floor-panel]')],blocks=[...container.querySelectorAll('[data-block]')];const signal=new AbortController();function current(){return panels.find(p=>p.dataset.floorPanel===level.value);}function transform(){world.style.transform=`translate(${view.x}px,${view.y}px) scale(${view.scale})`;preferences.floorViews??={};preferences.floorViews[`${item.id}/${level.value}`]={...view};save();}function fit(){const grid=current()?.querySelector('[data-floor-grid]');if(!grid)return;const w=grid.offsetWidth||Number(grid.dataset.gridWidth)*34,h=grid.offsetHeight||Number(grid.dataset.gridHeight)*34;view={scale:Math.min((viewport.clientWidth-24)/w,(viewport.clientHeight-24)/h,1.5),x:12,y:12};transform();}function change(){queueMicrotask(annotate);if(!current()){viewport.replaceChildren(el('p','This plan has no floors yet. Open Floor Plans to add a level.'));return;}for(const p of panels)p.classList.toggle('active',p===current());const visibleBlocks=engine.refreshSharedWalls(current());engine.refreshHiddenLocationStyles(visibleBlocks);engine.positionTransitions(current(),visibleBlocks);view=preferences.floorViews?.[`${item.id}/${level.value}`]||{x:0,y:0,scale:1};transform();if(!preferences.floorViews?.[`${item.id}/${level.value}`])fit();}level.onchange=change;function centre(blockId,force){const block=blocks.find(b=>Number(b.dataset.block)===Number(blockId));if(!block)return;const panel=block.closest('[data-floor-panel]');if(level.value!==panel.dataset.floorPanel){level.value=panel.dataset.floorPanel;change();}blocks.forEach(b=>b.classList.toggle('spatial-selected',b===block));if(force){const x=block.offsetLeft,y=block.offsetTop;view.x=viewport.clientWidth/2-(x+block.offsetWidth/2)*view.scale;view.y=viewport.clientHeight/2-(y+block.offsetHeight/2)*view.scale;transform();}}
for(const b of blocks){b.tabIndex=0;b.setAttribute('role','button');b.setAttribute('aria-label',b.textContent.trim());b.addEventListener('click',()=>{if(drag?.moved)return;const location=Number(b.dataset.locationId);if(location)void select(location);showRoom(b);},{signal:signal.signal});b.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();b.click();}},{signal:signal.signal});b.addEventListener('dragover',e=>{if(e.dataTransfer.types.includes(mime)){e.preventDefault();b.classList.add('spatial-drop');}},{signal:signal.signal});b.addEventListener('dragleave',()=>b.classList.remove('spatial-drop'),{signal:signal.signal});b.addEventListener('drop',e=>{e.preventDefault();b.classList.remove('spatial-drop');try{const p=JSON.parse(e.dataTransfer.getData(mime));if(validDrop(p))void associateRoom(b,p.locationId);}catch(error){fail(error);}},{signal:signal.signal});}
viewport.addEventListener('wheel',e=>{e.preventDefault();const r=viewport.getBoundingClientRect(),x=e.clientX-r.left,y=e.clientY-r.top,scale=Math.max(.08,Math.min(4,view.scale*Math.exp(-e.deltaY*.001)));view.x=x-(x-view.x)*scale/view.scale;view.y=y-(y-view.y)*scale/view.scale;view.scale=scale;transform();},{passive:false,signal:signal.signal});viewport.addEventListener('pointerdown',e=>{if(e.button!==0)return;drag={x:e.clientX,y:e.clientY,vx:view.x,vy:view.y,moved:false};if(!e.target.closest('[data-block]'))viewport.setPointerCapture(e.pointerId);},{signal:signal.signal});viewport.addEventListener('pointermove',e=>{if(!drag||!viewport.hasPointerCapture(e.pointerId))return;drag.moved=Math.hypot(e.clientX-drag.x,e.clientY-drag.y)>4;view.x=drag.vx+e.clientX-drag.x;view.y=drag.vy+e.clientY-drag.y;transform();},{signal:signal.signal});viewport.addEventListener('pointerup',e=>{if(viewport.hasPointerCapture(e.pointerId))viewport.releasePointerCapture(e.pointerId);setTimeout(()=>drag=null,0);},{signal:signal.signal});
function showRoom(b){const feature=q('[data-spatial-feature]');feature.replaceChildren(el('span',`Room: ${b.textContent.trim()}`));if(data.scope.canEdit)feature.append(btn('Associate existing location',async()=>{const chosen=await picker('Associate existing location with this room',Number(b.dataset.locationId));if(chosen!==undefined&&chosen!==null)await associateRoom(b,chosen);}),btn('Create location and associate',()=>{const version=versions.find(v=>v.id===Number(b.dataset.block));return createLocation(false,data.planCatalog.find(p=>p.id===resource)?.locationID,{id:Number(b.dataset.block),version:version.version});}));}
async function associateRoom(b,location){if(busy)throw Error('Finish or cancel the current operation first.');if(Number(b.dataset.locationId)===location)return;const version=versions.find(v=>v.id===Number(b.dataset.block));const old=Number(b.dataset.locationId);const target={bookID:position.bookId,sceneID:position.sceneId,kind:'room',locationID:location,resourceID:item.id,geometryID:b.dataset.block,expected:version.version,replace:!!old};await confirmOperation(`Replace the recorded room association? Geometry and location parents will stay unchanged. Connected transition identities must be reviewed in the main editor.`,async()=>finish(await post('/SpatialContext/Mutate',target)));}
change();return {id:item.id,revision:String(item.modifiedDate),blocks,showRoom,highlight:items=>{for(const b of blocks){b.querySelectorAll('.spatial-room-badge').forEach(n=>n.remove());b.classList.remove('spatial-position-0','spatial-position-1','spatial-position-2');const h=items.find(h=>Number(h.featureID)===Number(b.dataset.block));if(h){h.roles.forEach(r=>b.classList.add(`spatial-position-${r+1}`));b.append(el('span',h.roles.map(r=>['Previous','Current','Next'][r+1]).join(' · '),'spatial-room-badge'));b.title=h.label;b.setAttribute('aria-description',h.label);}}},centre,fit,getFloor:()=>Number(level.value),floor:id=>{if(panels.some(p=>Number(p.dataset.floorPanel)===id)){level.value=String(id);change();}},zoom:factor=>{view.scale=Math.max(.08,Math.min(4,view.scale*factor));transform();},dispose:()=>signal.abort()};
}
async function confirmOperation(message,commit){if(busy)throw Error('Finish or cancel the current operation first.');const target={...position};const panel=q('[data-spatial-operation]');panel.hidden=false;panel.replaceChildren(el('p',message));guard(true);panel.append(btn('Confirm',async()=>{try{if(await commit(target)!=='continue')clearOperation();}catch(e){fail(e);}}),btn('Cancel',clearOperation));}
async function startPlacement(location){if(!renderer?.map?.())throw Error('Choose and load a map first.');const existing=renderer.features().find(f=>f.locationID===location);if(existing&&(!existing.isLocked&&existing.geometryClass==='Marker')){await confirmOperation('This location already has a marker on this map. Reposition it explicitly?',()=>beginPlacement(location,existing));return;}if(existing){renderer.centre(existing.featureID,true);throw Error('A representation already exists. Edit complex or locked geometry in Maps.');}beginPlacement(location);}
function beginPlacement(location,existing){const map=renderer.map();const target={bookID:position.bookId,sceneID:position.sceneId,kind:'map',locationID:location,resourceID:resource,geometryID:existing?.featureID,expected:String(map.revision),replace:!!existing};operation=target;const panel=q('[data-spatial-operation]');panel.hidden=false;panel.replaceChildren(el('strong',`Place existing location: ${data.locations.find(l=>id(l)===location)?.locationName||location}`),el('p','Click a map position to save. The location record and its parent will stay unchanged.'),btn('Cancel',clearOperation));guard(true);renderer.command('placement',{active:true});return 'continue';}
async function savePlacement(point){const target=operation;if(!target)return;try{const result=await post('/SpatialContext/Mutate',{...target,x:point.x,y:point.y});clearOperation();await finish(result);}catch(e){fail(e);}}
async function dropPlacement(location,point){try{const existing=renderer?.features().find(f=>f.locationID===location);if(existing)throw Error('This location already has a representation on this map. Use Place location to reveal or explicitly reposition it.');const map=renderer.map(),target={bookID:position.bookId,sceneID:position.sceneId,kind:'map',locationID:location,resourceID:resource,expected:String(map.revision),x:point.x,y:point.y};await confirmOperation('Place this existing location at the dropped map position?',async()=>finish(await post('/SpatialContext/Mutate',target)));}catch(e){fail(e);}}
function chooseRoom(){if(!renderer?.blocks)return;const feature=q('[data-spatial-feature]');feature.replaceChildren(el('p','Select a room to associate an existing location. No geometry or parent location will be changed.'));const plan=data.planCatalog.find(p=>p.id===resource);if(plan)feature.append(btn('Associate this plan with a location',async()=>{const chosen=await picker('Associate floor plan with existing location',plan.locationID);if(chosen===undefined||chosen===null||chosen===plan.locationID)return;const target={bookID:position.bookId,sceneID:position.sceneId,kind:'plan',locationID:chosen,resourceID:resource,expected:plan.version,replace:!!plan.locationID};await confirmOperation('Associate this plan with the selected existing location?',async()=>finish(await post('/SpatialContext/Mutate',target)));}));}
for(const b of node.querySelectorAll('[data-spatial-zoom]'))b.onclick=()=>renderer?.zoom(b.dataset.spatialZoom==='in'?1.25:.8);q('[data-spatial-fit]')?.addEventListener('click',()=>renderer?.fit());q('[data-spatial-centre]')?.addEventListener('click',()=>{const found=resolution(data,selection,kind).find(l=>l.resourceID===resource);if(found)renderer?.centre(kind==='maps'?found.featureID:found.blockID,true);});
instances.set(node,{position(next){if(busy)return false;position=next;void reload();return true;},invalidate(hint){if(busy)return false;if(!['locations','maps','floorplans','spatial','structure','characters','relationships','assets',undefined].includes(hint.kind))return true;if(!invalidating){invalidating=true;requests.clear();queueMicrotask(()=>invalidating=false);}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,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);}});
})();

View File

@ -128,6 +128,8 @@
generation++;cancelRequests();
for(const pane of panes){for(const record of pane.records.values()){
if(record.tab.contentRefresh==='none')continue;
const customInvalidation=lifecycles[record.tab.lifecycle]?.onInvalidation;
if(customInvalidation){if(record.mounted&&visible(pane)&&!guarded(record)&&!scopeChanged(record.tab,record.position||position,position)&&customInvalidation(record.node,hint)===true){record.stale=false;continue;}record.stale=true;continue;}
if(hint.kind==='names'&&record.tab.id!=='names')continue;
if(hint.kind==='relationships'&&!['overview','characters','relationships'].includes(record.tab.id))continue;
if(hint.kind==='characters'&&!['overview','characters','relationships','names'].includes(record.tab.id))continue;
@ -144,7 +146,7 @@
sceneSelect.value=position.sceneId||'';
root.querySelector('[data-context-editor]').dataset.contextEntity=position.sceneId||'';
root.querySelector('[data-context-editor]').href=position.sceneId?`/Scenes/Edit/${position.sceneId}`:'/Writer';
for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');for(const record of pane.records.values())if(force||scopeChanged(record.tab,before,position))record.stale=true;void refreshPane(pane);}
for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');for(const record of pane.records.values())if(force||scopeChanged(record.tab,before,position)){if(!force&&record.mounted&&visible(pane)&&!guarded(record)&&lifecycles[record.tab.lifecycle]?.onPosition?.(record.node,{...position},before)===true){record.position={...position};for(const field of fields)record.node.dataset[field]=position[field]||'';}else record.stale=true;}void refreshPane(pane);}
announce();
}
async function recoverOffice(){if(window.PlotDirectorSharedFocus)await window.PlotDirectorSharedFocus.refresh();}
@ -170,7 +172,7 @@
divider.addEventListener('pointermove',event=>{if(!dragging)return;const box=grid.getBoundingClientRect();resize(state.layout==='rows'?(event.clientY-box.top)/box.height:(event.clientX-box.left)/box.width);});
for(const type of ['pointerup','pointercancel','lostpointercapture'])divider.addEventListener(type,()=>dragging=false);
divider.addEventListener('keydown',event=>{const keys=state.layout==='rows'?['ArrowUp','ArrowDown']:['ArrowLeft','ArrowRight'];if(![...keys,'Home','End'].includes(event.key))return;event.preventDefault();resize(event.key==='Home'?.2:event.key==='End'?.8:state.ratio+(event.key===keys[0]?-.05:.05));});
layoutSelect.addEventListener('change',()=>{panes.forEach(remember);state.layout=layoutSelect.value;applyLayout();});
layoutSelect.addEventListener('change',()=>{if(layoutSelect.value==='single'&&guarded(current(panes[1]))){layoutSelect.value=state.layout;panes[1].status.textContent='Finish or cancel editing before closing this pane.';return;}panes.forEach(remember);state.layout=layoutSelect.value;applyLayout();});
for(const pane of panes){
pane.select.value=state.panes[pane.index].tab;
pane.select.addEventListener('change',()=>{
@ -231,7 +233,8 @@
if(message.kind==='occupied'&&message.target===pageToken){windowId=uuid();panes.forEach(pane=>{dispose(current(pane));pane.revision++;pane.records.clear();pane.host.replaceChildren();});state=defaults();selectedDocument=root.dataset.wordInstance&&root.dataset.wordSession?`${root.dataset.wordInstance}/${root.dataset.wordSession}`:'';save();const url=new URL(location.href);url.searchParams.set('contextWindow',windowId);history.replaceState(null,'',url);applyLayout();}
};channel.postMessage({kind:'claim',id:windowId,token:pageToken});}
const observer=new ResizeObserver(()=>applyLayout());observer.observe(grid);
root.contextController={ get windowId(){return windowId;}, get position(){return {...position};}, invalidate,setPosition,get connection(){return connection;},get announcement(){return {version:1,bookID:position.bookId,windowID:windowId,panes:panes.filter(visible).map(pane=>({paneID:String(pane.index),toolID:state.panes[pane.index].tab,actions:registry.get(state.panes[pane.index].tab).actions||[],available:!windowBusy&&!!current(pane)?.node&&!current(pane).stale&&!guarded(current(pane))}))};},receiveInteraction:async delivery=>{if(windowBusy)return 'busy';const pane=panes.find(p=>String(p.index)===delivery.paneID);if(!pane||!visible(pane))return 'not-visible';const record=current(pane);if(guarded(record))return 'busy';if(!record?.node||record.stale)return 'unavailable';record.stale=true;await refreshPane(pane);if(record.stale||guarded(record))return 'unavailable';return await lifecycles[record.tab.lifecycle]?.onInteraction?.(record.node,delivery.command,{position:{...position},pane})||'not-visible';},registerLifecycle:(name,hooks)=>lifecycles[name]=hooks };
window.addEventListener('beforeunload',event=>{if(panes.some(p=>[...p.records.values()].some(guarded))){event.preventDefault();event.returnValue='';}});
root.contextController={openTool:(id,source,destination)=>{if(!registry.has(id))return false;const existing=panes.find(p=>visible(p)&&state.panes[p.index].tab===id);if(existing)return true;const index=destination==='current'?Number(source):1-Number(source);const pane=panes[index];if(!pane||guarded(current(pane)))return false;if(index===1&&state.layout==='single')state.layout='columns';remember(pane);dispose(current(pane));state.panes[index].tab=id;applyLayout();return true;}, get windowId(){return windowId;}, get position(){return {...position};}, invalidate,setPosition,get connection(){return connection;},get announcement(){return {version:1,bookID:position.bookId,windowID:windowId,panes:panes.filter(visible).map(pane=>({paneID:String(pane.index),toolID:state.panes[pane.index].tab,actions:registry.get(state.panes[pane.index].tab).actions||[],available:!windowBusy&&!!current(pane)?.node&&!current(pane).stale&&!guarded(current(pane))}))};},receiveInteraction:async delivery=>{if(windowBusy)return 'busy';const pane=panes.find(p=>String(p.index)===delivery.paneID);if(!pane||!visible(pane))return 'not-visible';const record=current(pane);if(guarded(record))return 'busy';if(!record?.node||record.stale)return 'unavailable';record.stale=true;await refreshPane(pane);if(record.stale||guarded(record))return 'unavailable';return await lifecycles[record.tab.lifecycle]?.onInteraction?.(record.node,delivery.command,{position:{...position},pane})||'not-visible';},registerLifecycle:(name,hooks)=>lifecycles[name]=hooks };
window.addEventListener('pagehide',()=>{stopped=true;panes.forEach(pane=>{remember(pane);dispose(current(pane));});save();cancelRequests();navigationRequest?.abort();clearInterval(timer);observer.disconnect();channel?.close();void connection?.stop();});
save();applyLayout();
status.textContent='';status.hidden=true;

View File

@ -0,0 +1,303 @@
/* Canonical floor-plan wall/transition renderer, shared with the existing editor. */
(() => {
'use strict';
function normalizeTransitionType(type) {
return (type || "").toLowerCase().replace(/[^a-z0-9]/g, "");
}
function isStairTransition(type) {
return normalizeTransitionType(type) === "stairsup" || normalizeTransitionType(type) === "stairsdown";
}
function isLadderTransition(type) {
return ["ladder", "ladders"].includes(normalizeTransitionType(type));
}
function isInsideLocationTransition(type) {
return isStairTransition(type) || isLadderTransition(type);
}
function isUnrestrictedTransition(type) {
return ["hiddenpassage", "openpassage", "secretpassage"].includes(normalizeTransitionType(type));
}
function isSecretRouteTransition(type) {
return ["hiddenpassage", "secretpassage"].includes(normalizeTransitionType(type));
}
function isVisibleEntranceTransition(type) {
return [
"door",
"doubledoor",
"frenchdoor",
"frenchdoors",
"slidingdoor",
"slidingdoors",
"exteriordoor",
"archway",
"openpassage",
"stairsup",
"stairsdown"
].includes(normalizeTransitionType(type));
}
function create(editor,{readBlock=block=>({x:Number(block.style.getPropertyValue('--x')),y:Number(block.style.getPropertyValue('--y')),w:Number(block.style.getPropertyValue('--w')),h:Number(block.style.getPropertyValue('--h'))})}={}) {
function subtractRange(segments, start, end) {
return segments.flatMap(segment => {
const clippedStart = Math.max(segment.start, start);
const clippedEnd = Math.min(segment.end, end);
if (clippedStart >= clippedEnd) return [segment];
return [
{ start: segment.start, end: clippedStart },
{ start: clippedEnd, end: segment.end }
].filter(next => next.end > next.start);
});
}
function renderWallSegment(block, side, start, end, total) {
if (end <= start || total <= 0) return;
const segment = document.createElement("span");
segment.dataset.wallSegment = side;
segment.className = `floor-plan-wall-segment floor-plan-wall-segment--${side}`;
segment.style.setProperty("--wall-start", `${(start / total) * 100}%`);
segment.style.setProperty("--wall-length", `${((end - start) / total) * 100}%`);
block.append(segment);
}
function visibleEdgeSegments(item, visibleBlocks, side) {
const axisStart = side === "east" || side === "west" ? item.y : item.x;
const axisLength = side === "east" || side === "west" ? item.h : item.w;
let segments = [{ start: 0, end: axisLength }];
visibleBlocks.forEach(other => {
if (item === other || !item.block.dataset.locationId || item.block.dataset.locationId !== other.block.dataset.locationId) return;
let touches = false;
let overlapStart = 0;
let overlapEnd = 0;
if (side === "east" && item.x + item.w === other.x) {
touches = true;
overlapStart = Math.max(item.y, other.y) - axisStart;
overlapEnd = Math.min(item.y + item.h, other.y + other.h) - axisStart;
} else if (side === "west" && other.x + other.w === item.x) {
touches = true;
overlapStart = Math.max(item.y, other.y) - axisStart;
overlapEnd = Math.min(item.y + item.h, other.y + other.h) - axisStart;
} else if (side === "south" && item.y + item.h === other.y) {
touches = true;
overlapStart = Math.max(item.x, other.x) - axisStart;
overlapEnd = Math.min(item.x + item.w, other.x + other.w) - axisStart;
} else if (side === "north" && other.y + other.h === item.y) {
touches = true;
overlapStart = Math.max(item.x, other.x) - axisStart;
overlapEnd = Math.min(item.x + item.w, other.x + other.w) - axisStart;
}
if (touches && overlapStart < overlapEnd) {
segments = subtractRange(segments, overlapStart, overlapEnd);
}
});
return segments;
}
function refreshWallSegments(visibleBlocks) {
visibleBlocks.forEach(item => {
item.block.querySelectorAll("[data-wall-segment]").forEach(segment => segment.remove());
["north", "east", "south", "west"].forEach(side => {
const total = side === "east" || side === "west" ? item.h : item.w;
visibleEdgeSegments(item, visibleBlocks, side).forEach(segment => {
renderWallSegment(item.block, side, segment.start, segment.end, total);
});
});
});
}
function refreshSharedWalls(activePanel) {
const visibleBlocks = [...activePanel.querySelectorAll("[data-block]")].map(block => ({ block, ...readBlock(block) }));
refreshWallSegments(visibleBlocks);
return visibleBlocks;
}
function locationCenter(blocksForLocation) {
if (blocksForLocation.length === 0) return null;
const minX = Math.min(...blocksForLocation.map(item => item.x));
const minY = Math.min(...blocksForLocation.map(item => item.y));
const maxX = Math.max(...blocksForLocation.map(item => item.x + item.w));
const maxY = Math.max(...blocksForLocation.map(item => item.y + item.h));
return { x: (minX + maxX) / 2, y: (minY + maxY) / 2 };
}
function refreshHiddenLocationStyles(visibleBlocks) {
const visibleEntranceLocationIds = new Set();
editor.querySelectorAll("[data-transition-marker]").forEach(marker => {
if (!isVisibleEntranceTransition(marker.dataset.transitionKind)) return;
if (marker.dataset.fromLocationId) visibleEntranceLocationIds.add(marker.dataset.fromLocationId);
if (marker.dataset.toLocationId) visibleEntranceLocationIds.add(marker.dataset.toLocationId);
});
visibleBlocks.forEach(item => {
const locationId = item.block.dataset.locationId;
const isHidden = !!locationId && !visibleEntranceLocationIds.has(locationId);
item.block.classList.toggle("is-hidden-location", isHidden);
const baseTitle = item.block.dataset.locationTitle || item.block.dataset.locationPath || item.block.dataset.locationName || "";
item.block.title = isHidden
? `${baseTitle}${baseTitle ? "\n" : ""}Hidden location: no visible entrance`
: baseTitle;
});
}
function renderSecretRoute(activePanel, marker, fromCenter, toCenter) {
if (!fromCenter || !toCenter) return;
const dx = toCenter.x - fromCenter.x;
const dy = toCenter.y - fromCenter.y;
const length = Math.sqrt(dx * dx + dy * dy);
if (length <= 0) return;
const route = document.createElement("span");
route.className = "floor-plan-secret-route";
route.dataset.secretRoute = marker.dataset.transitionMarker || "";
route.style.setProperty("--route-x", fromCenter.x);
route.style.setProperty("--route-y", fromCenter.y);
route.style.setProperty("--route-length", length);
route.style.setProperty("--route-angle", `${Math.atan2(dy, dx)}rad`);
route.title = marker.title || "";
route.setAttribute("aria-hidden", "true");
activePanel.querySelector("[data-floor-grid]")?.append(route);
}
function sharedTransitionEdge(fromBlocks, toBlocks) {
let best = null;
fromBlocks.forEach(from => {
toBlocks.forEach(to => {
if (from.x + from.w === to.x || to.x + to.w === from.x) {
const start = Math.max(from.y, to.y);
const end = Math.min(from.y + from.h, to.y + to.h);
const length = end - start;
if (length > 0 && (!best || length > best.length)) {
best = {
length,
orientation: "vertical",
start,
end,
x: from.x + from.w === to.x ? to.x : from.x,
y: start + length / 2
};
}
}
if (from.y + from.h === to.y || to.y + to.h === from.y) {
const start = Math.max(from.x, to.x);
const end = Math.min(from.x + from.w, to.x + to.w);
const length = end - start;
if (length > 0 && (!best || length > best.length)) {
best = {
length,
orientation: "horizontal",
start,
end,
x: start + length / 2,
y: from.y + from.h === to.y ? to.y : from.y
};
}
}
});
});
return best;
}
function positionWithinLocation(blocksForLocation, position) {
const center = locationCenter(blocksForLocation);
if (!center) return null;
const minX = Math.min(...blocksForLocation.map(item => item.x));
const minY = Math.min(...blocksForLocation.map(item => item.y));
const maxX = Math.max(...blocksForLocation.map(item => item.x + item.w));
const maxY = Math.max(...blocksForLocation.map(item => item.y + item.h));
const inset = 0.35;
const normalized = (position || "Centre").toLowerCase().replace(/\s+/g, "");
const x = normalized.includes("west") ? minX + inset : normalized.includes("east") ? maxX - inset : center.x;
const y = normalized.includes("north") ? minY + inset : normalized.includes("south") ? maxY - inset : center.y;
return { x, y };
}
function positionTransitions(activePanel, visibleBlocks) {
const markerPositions = [];
activePanel.querySelectorAll("[data-secret-route]").forEach(route => route.remove());
activePanel.querySelectorAll("[data-transition-marker]").forEach(marker => {
const fromBlocks = visibleBlocks.filter(item => item.block.dataset.locationId === marker.dataset.fromLocationId);
const toBlocks = visibleBlocks.filter(item => item.block.dataset.locationId === marker.dataset.toLocationId);
const fromCenter = locationCenter(fromBlocks);
const toCenter = locationCenter(toBlocks);
if (isSecretRouteTransition(marker.dataset.transitionKind)) {
marker.hidden = true;
if (fromCenter && toCenter) {
renderSecretRoute(activePanel, marker, fromCenter, toCenter);
}
return;
}
if (fromBlocks.length === 0 || (!isInsideLocationTransition(marker.dataset.transitionKind) && toBlocks.length === 0)) {
marker.hidden = true;
return;
}
const insidePlacement = isInsideLocationTransition(marker.dataset.transitionKind)
? positionWithinLocation(fromBlocks, marker.dataset.positionWithinLocation)
: null;
const sharedEdge = insidePlacement ? null : sharedTransitionEdge(fromBlocks, toBlocks);
marker.hidden = false;
marker.classList.toggle("is-shared-edge", !!sharedEdge);
marker.classList.toggle("is-inside-location", !!insidePlacement);
marker.classList.toggle("is-horizontal", sharedEdge?.orientation === "horizontal");
marker.classList.toggle("is-vertical", sharedEdge?.orientation === "vertical");
const pairKey = [marker.dataset.fromLocationId, marker.dataset.toLocationId].sort().join("-");
const key = insidePlacement
? `${pairKey}:inside:${normalizeTransitionType(marker.dataset.transitionKind)}:${marker.dataset.positionWithinLocation || "Centre"}:${insidePlacement.x}:${insidePlacement.y}`
: sharedEdge
? `${pairKey}:${sharedEdge.orientation}:${sharedEdge.x}:${sharedEdge.y}:${sharedEdge.start}:${sharedEdge.end}`
: `${pairKey}:fallback`;
markerPositions.push({ marker, insidePlacement, sharedEdge, fromCenter, toCenter, key });
});
const groups = markerPositions.reduce((map, item) => {
if (!map.has(item.key)) map.set(item.key, []);
map.get(item.key).push(item);
return map;
}, new Map());
groups.forEach(group => {
group.forEach((item, index) => {
const fraction = (index + 1) / (group.length + 1);
let x;
let y;
if (item.insidePlacement) {
x = item.insidePlacement.x;
y = item.insidePlacement.y;
} else if (item.sharedEdge?.orientation === "vertical") {
x = item.sharedEdge.x;
y = item.sharedEdge.start + item.sharedEdge.length * fraction;
} else if (item.sharedEdge?.orientation === "horizontal") {
x = item.sharedEdge.start + item.sharedEdge.length * fraction;
y = item.sharedEdge.y;
} else {
x = item.fromCenter.x + (item.toCenter.x - item.fromCenter.x) * fraction;
y = item.fromCenter.y + (item.toCenter.y - item.fromCenter.y) * fraction;
}
item.marker.style.setProperty("--transition-x", x);
item.marker.style.setProperty("--transition-y", y);
});
});
}
return {refreshSharedWalls,refreshHiddenLocationStyles,positionTransitions,locationCenter};
}
window.PlotDirectorFloorPlanRenderer={create,normalizeTransitionType,isStairTransition,isLadderTransition,isInsideLocationTransition,isUnrestrictedTransition,isSecretRouteTransition,isVisibleEntranceTransition};
})();

View File

@ -163,7 +163,7 @@
}
updateButtons();renderHandles(scale);
if(snapHint){handles.append(svgNode('circle',{cx:snapHint.point[0],cy:snapHint.point[1],r:10*scale,class:'maps-snap-indicator','pointer-events':'none'}));}
window.PlotDirectorStoryOverlay?.redraw();
window.PlotDirectorStoryOverlay?.redraw();app.dispatchEvent(new Event('map-rendered'));
}
function renderHandles(scale){
const active=handles.contains(document.activeElement)?{type:document.activeElement.dataset.handle,index:document.activeElement.dataset.index}:null;
@ -508,7 +508,7 @@
const workspaceResize=new ResizeObserver(resizeWorkspace);workspaceResize.observe(svg);const chrome=document.querySelector('.pd-application-header');if(chrome)workspaceResize.observe(chrome);
app.dataset.mode=mode;library();locations();crumbs();details();updateButtons();
$('mapsWelcome').hidden=!!doc;svg.style.visibility=doc?'visible':'hidden';$('mapsList').innerHTML=boot.maps.map(m=>`<a href="${url(m.mapID)}">${esc(m.name)} · ${esc(m.kind)}${m.parentMapID?' · detail of '+esc(boot.maps.find(p=>p.mapID===m.parentMapID)?.name||'parent map'):''}</a>`).join('');
if(doc)fit();if(new URLSearchParams(location.search).get('mode')==='explore')document.querySelector('[data-mode=explore]').click();
if(doc)fit();if(new URLSearchParams(location.search).get('featureId')){const id=new URLSearchParams(location.search).get('featureId');if(doc?.features.some(f=>f.featureID===id)){select(id);const f=doc.features.find(f=>f.featureID===id);view.x=f.x-view.w/2;view.y=f.y-view.h/2;applyView();}}if(new URLSearchParams(location.search).get('mode')==='explore'||location.pathname==='/SpatialContext/Map')document.querySelector('[data-mode=explore]').click();
// Expose semantic operations for browser regression fixtures, never credentials or a bypass.
window.PlotDirectorMapWorkspace={get document(){return doc;},get view(){return view;},get mode(){return mode;},get dirty(){return dirty;},get selected(){return [...selected];},setMode(value){document.querySelector(`button[data-mode="${value}"]`)?.click();},refreshDetails:details,clearSelection(){selected.clear();render();details();},focus(id){const f=doc?.features.find(f=>f.featureID===id);if(f){view.x=f.x-view.w/2;view.y=f.y-view.h/2;applyView();}},select,fit,save,requestLeave,edit:safeEdit,render,status,get busy(){return busy;},beginAdjustment(){if(!doc||mode!=='create'||busy||preview)return null;const transaction={before:snapshot(),redo:future.slice(),wasDirty:dirty};checkpoint();updateButtons();return transaction;},commitAdjustment(transaction){if(snapshot()===transaction.before){history.pop();future=transaction.redo;}else changed();render();details();updateButtons();},markAdjustmentChanged(){if(!dirty)changed();},cancelAdjustment(transaction){doc=JSON.parse(transaction.before);dirty=transaction.wasDirty;status(dirty?'Unsaved changes':'Adjustment cancelled');history.pop();future=transaction.redo;render();details();updateButtons();}};
window.PlotDirectorMapWorkspace={get document(){return doc;},get view(){return view;},get mode(){return mode;},get dirty(){return dirty;},get selected(){return [...selected];},setMode(value){document.querySelector(`button[data-mode="${value}"]`)?.click();},refreshDetails:details,clearSelection(){selected.clear();render();details();},focus(id){const f=doc?.features.find(f=>f.featureID===id);if(f){view.x=f.x-view.w/2;view.y=f.y-view.h/2;applyView();}},select,fit,zoom,world,setView(next){if(['x','y','w','h'].every(k=>Number.isFinite(next?.[k]))&&next.w>0&&next.h>0){view={...next};applyView();}},replaceDocument(next){if(next?.map?.mapID!==doc?.map?.mapID)return;doc=clone(next);savedDocument=clone(doc);containmentDirty=true;selected=new Set([...selected].filter(id=>doc.features.some(f=>f.featureID===id)));render();details();},save,requestLeave,edit:safeEdit,render,status,get busy(){return busy;},beginAdjustment(){if(!doc||mode!=='create'||busy||preview)return null;const transaction={before:snapshot(),redo:future.slice(),wasDirty:dirty};checkpoint();updateButtons();return transaction;},commitAdjustment(transaction){if(snapshot()===transaction.before){history.pop();future=transaction.redo;}else changed();render();details();updateButtons();},markAdjustmentChanged(){if(!dirty)changed();},cancelAdjustment(transaction){doc=JSON.parse(transaction.before);dirty=transaction.wasDirty;status(dirty?'Unsaved changes':'Adjustment cancelled');history.pop();future=transaction.redo;render();details();updateButtons();}};
})();