diff --git a/Docs/Writer/Spatial-Context.md b/Docs/Writer/Spatial-Context.md new file mode 100644 index 00000000..281af2e3 --- /dev/null +++ b/Docs/Writer/Spatial-Context.md @@ -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. diff --git a/PlotLine.Tests/Browser/context-spatial-dev-setup.cjs b/PlotLine.Tests/Browser/context-spatial-dev-setup.cjs new file mode 100644 index 00000000..9be5aac7 --- /dev/null +++ b/PlotLine.Tests/Browser/context-spatial-dev-setup.cjs @@ -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;}); diff --git a/PlotLine.Tests/Browser/context-spatial-installed-pwa.cjs b/PlotLine.Tests/Browser/context-spatial-installed-pwa.cjs new file mode 100644 index 00000000..6dc05e21 --- /dev/null +++ b/PlotLine.Tests/Browser/context-spatial-installed-pwa.cjs @@ -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;}); diff --git a/PlotLine.Tests/Browser/context-spatial-resolution.cjs b/PlotLine.Tests/Browser/context-spatial-resolution.cjs new file mode 100644 index 00000000..ec8f1829 --- /dev/null +++ b/PlotLine.Tests/Browser/context-spatial-resolution.cjs @@ -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'); diff --git a/PlotLine.Tests/Browser/context-spatial.cjs b/PlotLine.Tests/Browser/context-spatial.cjs new file mode 100644 index 00000000..12d60e9d --- /dev/null +++ b/PlotLine.Tests/Browser/context-spatial.cjs @@ -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:`
Existing Context tab
`});}); +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;}})(); diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index ad4b1a9e..f3011130 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -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;} diff --git a/PlotLine.Tests/SpatialContextBrowserFixture.cs b/PlotLine.Tests/SpatialContextBrowserFixture.cs new file mode 100644 index 00000000..247c1707 --- /dev/null +++ b/PlotLine.Tests/SpatialContextBrowserFixture.cs @@ -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")]); +} diff --git a/PlotLine.Tests/SpatialContextDatabaseTests.cs b/PlotLine.Tests/SpatialContextDatabaseTests.cs new file mode 100644 index 00000000..f6942162 --- /dev/null +++ b/PlotLine.Tests/SpatialContextDatabaseTests.cs @@ -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("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("INSERT dbo.StoryMaps(ProjectID,Name,Kind) VALUES(@ProjectID,N'Spatial fixture map',N'Region');SELECT CONVERT(int,SCOPE_IDENTITY());",fixture,tx); + async Task 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("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("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();var scenes=(await rows.ReadAsync()).ToArray();var assignments=(await rows.ReadAsync()).ToArray();var locations=(await rows.ReadAsync()).ToArray();var maps=(await rows.ReadAsync()).ToArray();var plans=(await rows.ReadAsync()).ToArray();var mapCatalog=(await rows.ReadAsync()).ToArray();var planCatalog=(await rows.ReadAsync()).ToArray();var relations=(await rows.ReadAsync()).ToArray();var types=(await rows.ReadAsync()).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("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("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("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("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("SELECT PrimaryLocationID FROM dbo.Scenes WHERE SceneID=@SceneID",fixture,tx)!=ids[1])throw new Exception("Scene assignment Undo failed."); + var plan=await db.ExecuteScalarAsync("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("INSERT dbo.FloorPlanFloors(FloorPlanID,Name) VALUES(@plan,N'Ground');SELECT CONVERT(int,SCOPE_IDENTITY());",new{plan},tx);var block=await db.ExecuteScalarAsync("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("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("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("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("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("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()).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("INSERT dbo.Locations(ProjectID,LocationName) VALUES(@ProjectID,N'Spatial negative fixture');SELECT CONVERT(int,SCOPE_IDENTITY());",fixture,tx); + var b=await db.ExecuteScalarAsync("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("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("SELECT Revision FROM dbo.StoryMaps WHERE MapID=@map",new{map},tx); + var first=await db.QuerySingleAsync("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("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("INSERT dbo.FloorPlans(ProjectID,Name) VALUES(@ProjectID,N'Spatial negative plan');SELECT CONVERT(int,SCOPE_IDENTITY());",fixture,tx); + var floor=await db.ExecuteScalarAsync("INSERT dbo.FloorPlanFloors(FloorPlanID,Name) VALUES(@plan,N'Ground');SELECT CONVERT(int,SCOPE_IDENTITY());",new{plan},tx); + var block=await db.ExecuteScalarAsync("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("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("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("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("SELECT TOP(1) SceneID FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID ORDER BY BookSceneIndex DESC",fixture));var samples=new List(); + 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();var actual=(await rows.ReadAsync()).ToArray();while(!rows.IsConsumed)await rows.ReadAsync();var expected=(await db.QueryAsync("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("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);}} + } +} diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index c4349a19..c0c8f6f7 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -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"; diff --git a/PlotLine/Controllers/MapsController.cs b/PlotLine/Controllers/MapsController.cs index dc71b6ad..8b7673c9 100644 --- a/PlotLine/Controllers/MapsController.cs +++ b/PlotLine/Controllers/MapsController.cs @@ -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 Index(int projectId, int? id, bool detached = false) + public async Task 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), diff --git a/PlotLine/Controllers/SpatialContextController.cs b/PlotLine/Controllers/SpatialContextController.cs new file mode 100644 index 00000000..8c000a19 --- /dev/null +++ b/PlotLine/Controllers/SpatialContextController.cs @@ -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 Guard(Func> 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 State(int bookId,int sceneId,int? locationId)=>Guard(async()=>Json(await spatial.Read(bookId,sceneId,locationId))); + [HttpPost,ValidateAntiForgeryToken] public Task 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 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 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 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 Floor(int bookId,int sceneId,int id)=>Guard(async()=>PartialView("~/Views/Writing/_SpatialFloorCanvas.cshtml",await spatial.Floor(bookId,sceneId,id))); +} diff --git a/PlotLine/Controllers/WritingController.cs b/PlotLine/Controllers/WritingController.cs index 488131fa..dc096f23 100644 --- a/PlotLine/Controllers/WritingController.cs +++ b/PlotLine/Controllers/WritingController.cs @@ -119,6 +119,28 @@ public sealed class WritingController( ViewData["ContextTabPartial"]="_ContextNames";return PartialView("_ContextTab",model); } + [HttpGet("Context/Locations")] + public Task 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 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 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 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 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(); diff --git a/PlotLine/Help/Articles/Workspace/WorkingContext.md b/PlotLine/Help/Articles/Workspace/WorkingContext.md index a403cc17..e9927463 100644 --- a/PlotLine/Help/Articles/Workspace/WorkingContext.md +++ b/PlotLine/Help/Articles/Workspace/WorkingContext.md @@ -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). diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 741271d4..e423610d 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -313,6 +313,7 @@ public class Program builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/PlotLine/Services/Context/ContextSpatial.cs b/PlotLine/Services/Context/ContextSpatial.cs new file mode 100644 index 00000000..0642b00b --- /dev/null +++ b/PlotLine/Services/Context/ContextSpatial.cs @@ -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 Scope(int book,int scene) + { + using var db=connections.CreateConnection();return await db.QuerySingleAsync("dbo.SpatialContext_Scope",new{UserID=Author,BookID=book,SceneID=scene},commandType:CommandType.StoredProcedure); + } + public async Task 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();var scenes=(await data.ReadAsync()).ToArray();var assignments=(await data.ReadAsync()).ToArray();var locations=(await data.ReadAsync()).ToArray();var maps=(await data.ReadAsync()).ToArray();var plans=(await data.ReadAsync()).ToArray();var mapCatalog=(await data.ReadAsync()).ToArray();var planCatalog=(await data.ReadAsync()).ToArray();var relationships=(await data.ReadAsync()).ToArray();var types=(await data.ReadAsync()).Select(LocationWorkspaceIcons.Presentation).ToArray(); + return new(scope,scenes,assignments,locations,maps,plans,mapCatalog,planCatalog,relationships,types); + } + private async Task 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("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 Mutate(SpatialMutation input) + { + using var db=connections.CreateConnection();var result=await Apply(db,input);return await Accepted(input,result); + } + private async Task 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 Undo(string token) + { + SpatialReceipt receipt;try{receipt=JsonSerializer.Deserialize(Protector.Unprotect(token))??throw new Exception();}catch{throw new ArgumentException("Undo is unavailable.");} + if(receipt.User!=Author||receipt.Expires 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("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 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();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()).ToList(),Blocks=(await rows.ReadAsync()).ToList(),Transitions=(await rows.ReadAsync()).ToList()};rows.Dispose(); + var versions=(await db.QueryAsync("dbo.SpatialContext_RoomVersions",new{UserID=Author,BookID=book,SceneID=scene,PlanID=plan},tx,commandType:CommandType.StoredProcedure)).ToArray();tx.Commit();return new(model,versions); + } +} diff --git a/PlotLine/Services/FloorPlanPresentation.cs b/PlotLine/Services/FloorPlanPresentation.cs new file mode 100644 index 00000000..aaca7c72 --- /dev/null +++ b/PlotLine/Services/FloorPlanPresentation.cs @@ -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" => @"", + "double-door" => @"", + "french-door" => @"", + "sliding-door" => @"", + "window" => @"", + "archway" => @"", + "secret-door" => @"", + "blocked-door" => @"", + "exterior-door" => @"", + "stairs" => @"", + "ladder" => @"", + "passage" => @"", + _ => @"x" + }; + +} diff --git a/PlotLine/Sql/339_SpatialContext.sql b/PlotLine/Sql/339_SpatialContext.sql new file mode 100644 index 00000000..2ab56c92 --- /dev/null +++ b/PlotLine/Sql/339_SpatialContext.sql @@ -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 diff --git a/PlotLine/Views/FloorPlans/Edit.cshtml b/PlotLine/Views/FloorPlans/Edit.cshtml index 17ecad95..1b699b2e 100644 --- a/PlotLine/Views/FloorPlans/Edit.cshtml +++ b/PlotLine/Views/FloorPlans/Edit.cshtml @@ -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" => @"", - "double-door" => @"", - "french-door" => @"", - "sliding-door" => @"", - "window" => @"", - "archway" => @"", - "secret-door" => @"", - "blocked-door" => @"", - "exterior-door" => @"", - "stairs" => @"", - "ladder" => @"", - "passage" => @"", - _ => @"x" - }; - var transitionPositions = FloorPlanTransitionPositions.All .Select(x => new SelectListItem(x, x)) .ToList(); @@ -426,125 +375,7 @@ -
- @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) ?? []; -
-
-
- @if (!string.IsNullOrWhiteSpace(floor.BackgroundImagePath)) - { - - } - @foreach (var block in floorBlocks) - { - var blockIndex = Model.Blocks.FindIndex(x => x.FloorPlanBlockID == block.FloorPlanBlockID); - - 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)); -
- @foreach (var token in tokens.Take(3)) - { - var imagePath = !string.IsNullOrWhiteSpace(token.ThumbnailPath) ? token.ThumbnailPath : token.ImagePath; - - @if (!string.IsNullOrWhiteSpace(imagePath)) - { - @token.DisplayName - } - else - { - @AvatarHelper.Initials(token.DisplayName) - } - - } - @if (tokens.Count > 3) - { - +@(tokens.Count - 3) - } - Occupancy tokens help: characters and assets placed in this scene. -
- } - } - } - } - @foreach (var scene in Model.OccupancyScenes) - { - var totalTokens = occupancyTokenCountByScene.GetValueOrDefault(scene.SceneID); - var floorTokens = occupancyTokenCountBySceneFloor.GetValueOrDefault($"{scene.SceneID}:{floor.FloorPlanFloorID}"); - if (totalTokens == 0) - { - - } - else if (floorTokens == 0) - { - - } - else if (floorTokens < totalTokens) - { - - } - } - @foreach (var transition in floorTransitions) - { - var transitionDetails = TransitionDetails(transition); - var markerType = TransitionMarkerType(transition.TransitionType); -
- @Html.Raw(TransitionMarkerSvg(markerType)) -
- } -
-
-
- } -
+