From ebc9c2b41389d55372ab1ae1ad3d454b0397b48a Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Fri, 27 Nov 2026 18:12:40 +0000 Subject: [PATCH] fix(context): keep cached spatial views fresh and reveal exact features --- Docs/Writer/Spatial-Context.md | 6 +++--- .../Browser/context-spatial-development.cjs | 2 +- PlotLine.Tests/Browser/context-spatial.cjs | 5 ++++- PlotLine.Tests/SpatialContextBrowserFixture.cs | 4 ++-- PlotLine.Tests/ToolbarBrowserHost.cs | 2 +- PlotLine/Services/Context/ContextSpatial.cs | 6 +++--- PlotLine/wwwroot/js/context-spatial.js | 13 ++++++++----- PlotLine/wwwroot/js/context-workspace.js | 1 + 8 files changed, 23 insertions(+), 16 deletions(-) diff --git a/Docs/Writer/Spatial-Context.md b/Docs/Writer/Spatial-Context.md index 18453687..0f95e1d3 100644 --- a/Docs/Writer/Spatial-Context.md +++ b/Docs/Writer/Spatial-Context.md @@ -14,11 +14,11 @@ Direct associations win. Otherwise the nearest active containing location with a `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. Scene/highlight changes retain renderers when resource revisions are unchanged. Persisted location metadata hints refresh canonical floor markup because room labels depend on location names rather than plan timestamps; this refresh restores the selected floor, inspection and viewport. Resource and viewport preferences use author/window/project/tool/resource keys in local storage. Transient placement and inspection selection are never persisted. +State requests are shared by book, scene and inspected location, with a bounded cache; stale response epochs are ignored. Promise identity guards prevent an obsolete response from repopulating the current cache. Hidden tools invalidate cached projections without requesting resources; reactivation then reads fresh data. Paragraph movement does not invoke Scene-scoped lifecycle updates. Visible tools handle relevant invalidations themselves; inactive tools remain stale without loading. Scene/highlight changes retain renderers when resource revisions are unchanged. Persisted location metadata hints refresh canonical floor markup because room labels depend on location names rather than plan timestamps; this refresh restores the selected floor, inspection and viewport. 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. +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. Context advanced links target the selected feature or explicit room, and unassociated map features can be inspected without inventing a story-location assignment. 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. @@ -28,7 +28,7 @@ Existing `LocationWorkspace` services handle versioned rename, prose, type and c 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. The existing reference invalidation filter also covers successful main Maps/Floor Plans posts. Their shared live-update adapter reuses the established main-window presence connection: clean maps replace their canonical document in place, and clean floor plans reuse the existing workspace replacement/state restoration routine. Active edits are preserved and receive a shared notice; no extra SignalR connection is created. Held windows still receive persisted changes. +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. The existing reference invalidation filter also covers successful main Maps/Floor Plans posts. Their shared live-update adapter reuses the established main-window presence connection: clean maps replace their canonical document in place, and clean floor plans reuse the existing workspace replacement/state restoration routine. Active edits are preserved and receive a shared notice; no extra SignalR connection is created. Held windows still receive persisted changes. Scene assignment hints are book-scoped; shared maps, plans, associations and new locations invalidate the project across its books. 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. diff --git a/PlotLine.Tests/Browser/context-spatial-development.cjs b/PlotLine.Tests/Browser/context-spatial-development.cjs index 2a9e35fa..ee1e0807 100644 --- a/PlotLine.Tests/Browser/context-spatial-development.cjs +++ b/PlotLine.Tests/Browser/context-spatial-development.cjs @@ -10,4 +10,4 @@ console.log('STEP',step='map placement and Undo');const liveMap=await context.ne console.log('STEP',step='room association and Undo');const livePlan=await context.newPage();await livePlan.goto(base+`/FloorPlans/Edit/${f.planId}`);await livePlan.waitForSelector('[data-floor-plan-initialized=true]');await page.bringToFront();await page.selectOption('[data-context-pane="1"] [data-context-tab]','floorplans');await pane(1).locator('[data-spatial-floor-canvas]').waitFor();const room=pane(1).locator(`[data-block][data-location-id="${f.locations[2]}"]`);const block=await room.getAttribute('data-block'),geometry=await room.getAttribute('style');await room.click();await pane(1).getByRole('button',{name:'Associate existing location',exact:true}).click();const picker=page.locator('dialog[open]').last();await picker.locator('input[type=search]').fill('Unmapped valley');await chooseLocation(f.locations[4]);await pane(1).getByRole('button',{name:'Confirm',exact:true}).waitFor();await shot('room-association');await pane(1).getByRole('button',{name:'Confirm',exact:true}).click();await pane(1).locator(`[data-block="${block}"][data-location-id="${f.locations[4]}"]`).waitFor();assert.equal(await pane(1).locator(`[data-block="${block}"]`).getAttribute('style'),geometry);await livePlan.locator(`[data-block="${block}"][data-location-id="${f.locations[4]}"]`).waitFor();data=await state();assert.equal(data.locations.find(l=>l.locationID===f.locations[4])?.parentLocationID??null,null);await undo(1);await pane(1).locator(`[data-block="${block}"][data-location-id="${f.locations[2]}"]`).waitFor();await livePlan.locator(`[data-block="${block}"][data-location-id="${f.locations[2]}"]`).waitFor();await livePlan.close();await shot('locations-floorplans'); console.log('STEP',step='live room labels retain viewport');const beforeLabel=await state(),labelLocation=beforeLabel.locations.find(l=>l.locationID===f.locations[2]);let labelResponse=await page.request.post(base+'/LocationWorkspace/Assign',{headers:{RequestVerificationToken:token},data:{projectId:identity.ProjectID,attribute:'name',changes:[{id:f.locations[2],value:'Lounge live label',version:labelLocation.updatedDate}]}});assert.equal(labelResponse.status(),200);const labelUndo=(await labelResponse.json()).undoToken;await pane(1).locator(`[data-block="${block}"] .floor-plan-block-label`).filter({hasText:'Lounge live label'}).waitFor();labelResponse=await page.request.post(base+'/LocationWorkspace/Undo',{headers:{RequestVerificationToken:token},data:{token:labelUndo}});assert.equal(labelResponse.status(),200);await pane(1).locator(`[data-block="${block}"] .floor-plan-block-label`).filter({hasText:/Lounge$/}).waitFor(); console.log('STEP',step='main workspaces remain available');const checks=[];const verification=await context.newPage();for(const route of [`/Locations?projectId=${identity.ProjectID}`,`/Characters?projectId=${identity.ProjectID}`,`/Names?projectId=${identity.ProjectID}`,`/RelationshipMap?projectId=${identity.ProjectID}`,`/Maps?projectId=${identity.ProjectID}&id=${f.mapId}`,`/FloorPlans/Edit/${f.planId}`,`/StoryAssets?projectId=${identity.ProjectID}`]){const response=await verification.goto(base+route);assert.equal(response.status(),200,route);checks.push(route.split('?')[0]);}await verification.close(); -console.log('STEP',step='single SignalR in following window');const follow=await context.newPage();let connections=0;follow.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))connections++;});await follow.goto(base+`/Writing/Context?projectId=${identity.ProjectID}&bookId=${identity.BookID}&sceneId=${f.scenes[1]}`);await follow.waitForFunction(()=>document.querySelector('[data-context-workspace]')?.contextController?.connection?.state==='Connected');await follow.selectOption('[data-context-pane="0"] [data-context-tab]','maps');await follow.selectOption('[data-context-layout]','columns');await follow.selectOption('[data-context-pane="1"] [data-context-tab]','floorplans');await follow.waitForTimeout(500);assert.equal(connections,1);await follow.selectOption('[data-context-pane="0"] [data-context-tab]','locations');await follow.locator('[data-spatial-details] h2').waitFor();await follow.locator('[data-shared-focus-hold]').click();await follow.waitForFunction(()=>PlotDirectorSharedFocus.held);const heldScene=await follow.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId);const heldResponse=await page.request.get(base+`/SpatialContext/State?bookId=${identity.BookID}&sceneId=${heldScene}`),heldData=await heldResponse.json(),heldLocation=heldData.locations.find(l=>l.locationID===heldData.scope.primaryLocationID);assert(heldLocation);const navigatorPage=await context.newPage();await navigatorPage.goto(base+`/Scenes/Edit/${f.scenes[1]}`);await page.request.post(base+'/LocationWorkspace/Assign',{headers:{RequestVerificationToken:token},data:{projectId:identity.ProjectID,attribute:'description',changes:[{id:heldLocation.locationID,value:'Held spatial acceptance detail',version:heldLocation.updatedDate}]}}).then(async r=>{assert.equal(r.status(),200);identity.HeldUndo=(await r.json()).undoToken;});await follow.getByText('Held spatial acceptance detail',{exact:true}).waitFor();assert.equal(await follow.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),heldScene);await follow.locator('[data-shared-focus-hold]').click();await follow.waitForFunction(()=>!PlotDirectorSharedFocus.held);await page.request.post(base+'/LocationWorkspace/Undo',{headers:{RequestVerificationToken:token},data:{token:identity.HeldUndo}});delete identity.HeldUndo;await navigatorPage.close();await follow.close();assert.deepEqual(errors,[]);fs.writeFileSync(`${out}/development-results.json`,JSON.stringify({passed:true,source:'authenticated Development',fixturesOnly:true,sceneSequence:f.scenes,checks,signalRConnections:connections,errors},null,2));console.log('PASS authenticated Development spatial sequence, targeted description/scene assignment, real protected Undo, map placement/reveal, room association, geometry preservation, main directories, one SignalR connection.');}catch(e){console.error('FAIL',step,e);process.exitCode=1;}finally{await browser.close();}})(); +console.log('STEP',step='single SignalR in following window');const follow=await context.newPage();let connections=0;follow.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))connections++;});await follow.goto(base+`/Writing/Context?projectId=${identity.ProjectID}&bookId=${identity.BookID}&sceneId=${f.scenes[1]}`);await follow.waitForFunction(()=>document.querySelector('[data-context-workspace]')?.contextController?.connection?.state==='Connected');await follow.selectOption('[data-context-pane="0"] [data-context-tab]','maps');await follow.selectOption('[data-context-layout]','columns');await follow.selectOption('[data-context-pane="1"] [data-context-tab]','floorplans');await follow.waitForTimeout(500);assert.equal(connections,1);await follow.selectOption('[data-context-pane="0"] [data-context-tab]','locations');await follow.locator('[data-spatial-details] h2').waitFor();await follow.locator('[data-shared-focus-hold]').click();await follow.waitForFunction(()=>PlotDirectorSharedFocus.held);const heldScene=await follow.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId);const heldResponse=await page.request.get(base+`/SpatialContext/State?bookId=${identity.BookID}&sceneId=${heldScene}`),heldData=await heldResponse.json(),heldLocation=heldData.locations.find(l=>l.locationID===heldData.scope.primaryLocationID);assert(heldLocation);const navigatorPage=await context.newPage();await navigatorPage.goto(base+`/Scenes/Edit/${f.scenes[1]}`);await navigatorPage.waitForFunction(()=>!!window.PlotDirectorSharedFocus);const navScene=heldScene===f.scenes[1]?f.scenes[2]:f.scenes[1];assert(await navigatorPage.evaluate(async p=>{if(PlotDirectorSharedFocus.held)await PlotDirectorSharedFocus.toggle();return await PlotDirectorSharedFocus.navigate(p);},{projectID:identity.ProjectID,bookID:identity.BookID,sceneID:navScene}));await follow.waitForFunction(id=>PlotDirectorSharedFocus.shared?.sceneID===id,navScene);assert.equal(await follow.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),heldScene);await page.request.post(base+'/LocationWorkspace/Assign',{headers:{RequestVerificationToken:token},data:{projectId:identity.ProjectID,attribute:'description',changes:[{id:heldLocation.locationID,value:'Held spatial acceptance detail',version:heldLocation.updatedDate}]}}).then(async r=>{assert.equal(r.status(),200);identity.HeldUndo=(await r.json()).undoToken;});await follow.getByText('Held spatial acceptance detail',{exact:true}).waitFor();assert.equal(await follow.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),heldScene);await follow.locator('[data-shared-focus-hold]').click();await follow.waitForFunction(()=>!PlotDirectorSharedFocus.held);await follow.waitForFunction(id=>document.querySelector('[data-context-workspace]').contextController.position.sceneId===id,navScene);await page.request.post(base+'/LocationWorkspace/Undo',{headers:{RequestVerificationToken:token},data:{token:identity.HeldUndo}});delete identity.HeldUndo;await navigatorPage.close();await follow.close();assert.deepEqual(errors,[]);fs.writeFileSync(`${out}/development-results.json`,JSON.stringify({passed:true,source:'authenticated Development',fixturesOnly:true,sceneSequence:f.scenes,checks,signalRConnections:connections,errors},null,2));console.log('PASS authenticated Development spatial sequence, targeted description/scene assignment, real protected Undo, map placement/reveal, room association, geometry preservation, main directories, one SignalR connection.');}catch(e){console.error('FAIL',step,e);process.exitCode=1;}finally{await browser.close();}})(); diff --git a/PlotLine.Tests/Browser/context-spatial.cjs b/PlotLine.Tests/Browser/context-spatial.cjs index b3cb0ec4..c0b0b447 100644 --- a/PlotLine.Tests/Browser/context-spatial.cjs +++ b/PlotLine.Tests/Browser/context-spatial.cjs @@ -7,10 +7,11 @@ await context.route('**/Writing/Context/Tabs/*',r=>{const u=new URL(r.request(). 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='maps renderer';await page.selectOption(tab(0),'maps');await pane(0).locator('iframe').waitFor();await page.waitForFunction(()=>document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.document.features.length===2);await page.waitForTimeout(150);const frame=page.frames().find(f=>f.url().includes('/SpatialContext/Map'));assert.equal(await frame.locator('.spatial-map-ring').count(),3);await shot('02-maps-single');await frame.locator('[data-feature-id="21111111-2222-4333-8444-555555555555"]').first().click();await pane(0).getByText('No associated location; inspection does not assign this feature to a scene.',{exact:true}).waitFor();assert.match(await pane(0).locator('[data-spatial-advanced]').getAttribute('href'),/featureId=21111111-2222-4333-8444-555555555555/);assert.equal(await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),22);await pane(0).locator('[data-spatial-resource]').selectOption('2');await pane(0).getByText('No authoritative representation of the inspected location on this resource.',{exact:true}).waitFor();assert.match(await pane(0).locator('[data-spatial-advanced]').getAttribute('href'),/id=2$/);await pane(0).locator('[data-spatial-resource]').selectOption('1');await pane(0).getByText('Represented through containing location:',{exact:false}).waitFor(); step='floor renderer';await page.selectOption(tab(0),'floorplans');await pane(0).locator('[data-block="51"]').waitFor();assert.equal(await pane(0).locator('.spatial-room-badge').count(),3);await shot('03-floorplans-single'); step='split dedup and coordination';await page.selectOption('[data-context-layout]','columns');await page.selectOption(tab(0),'locations');await page.selectOption(tab(1),'maps');await pane(1).locator('iframe').waitFor();await page.waitForTimeout(200);await shot('04-locations-maps');await pane(0).locator('.spatial-path button').filter({hasText:'The old house'}).click();await pane(0).getByRole('heading',{name:'The old house',exact:true}).waitFor();await pane(1).locator('[data-spatial-resolution]').filter({hasText:'Directly associated'}).waitFor(); step='locations floor';await page.selectOption(tab(1),'floorplans');await pane(1).locator('[data-block="51"]').waitFor();await shot('05-locations-floorplans');await pane(1).locator('[data-block="52"]').click();await pane(0).getByRole('heading',{name:'Lounge',exact:true}).waitFor(); +step='metadata refresh retains chosen level and viewport';await pane(1).locator('[data-spatial-floor]').selectOption('42');const oldFloorCanvas=await pane(1).locator('[data-spatial-floor-canvas]').elementHandle(),savedTransform=await pane(1).locator('[data-spatial-floor-world]').evaluate(n=>n.style.transform);await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({projectId:7,bookId:12,kind:'locations'}));await page.waitForFunction(node=>!node.isConnected,oldFloorCanvas);assert.equal(await pane(1).locator('[data-spatial-floor]').inputValue(),'42');assert.equal(await pane(1).locator('[data-spatial-floor-world]').evaluate(n=>n.style.transform),savedTransform);await pane(1).locator('[data-spatial-floor]').selectOption('41'); step='maps floor';await page.selectOption(tab(0),'maps');await pane(0).locator('iframe').waitFor();await page.waitForTimeout(100);await shot('06-maps-floorplans');await page.selectOption('[data-context-layout]','rows');await shot('07-stacked'); step='same building retains renderer and viewport';await page.evaluate(()=>{window.spatialFrame=document.querySelector('[data-context-pane="0"] iframe');spatialFrame.contentWindow.PlotDirectorMapWorkspace.setView({x:-250,y:-200,w:900,h:600});document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:24});});await pane(0).locator('[data-scene-position="0"] button').filter({hasText:'Lounge'}).waitFor();assert.equal(await page.evaluate(()=>window.spatialFrame===document.querySelector('[data-context-pane="0"] iframe')),true);assert.equal(await page.evaluate(()=>window.spatialFrame.contentWindow.PlotDirectorMapWorkspace.view.w),900);await shot('10-repeated-location');await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:22}));await pane(0).locator('[data-scene-position="0"] button').filter({hasText:'Bedroom'}).waitFor(); step='paragraph no loading';const before=requests.length;await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:22,paragraphId:'a-paragraph'}));await page.waitForTimeout(100);assert.equal(requests.length,before); @@ -24,4 +25,6 @@ step='unavailable assignment remains recorded';await page.route('**/SpatialConte 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(); +step='hidden cache invalidation without hidden requests';await page.selectOption('[data-context-layout]','single');await pane(0).locator('[data-scene-position="0"] button').first().click();await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor();await page.selectOption(tab(0),'overview');await page.route('**/SpatialContext/State?*',async route=>{const r=await route.fetch(),d=await r.json();for(const l of d.locations)l.description='Fresh hidden location data';await route.fulfill({json:d});});const hiddenReads=requests.length;await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({projectId:7,bookId:12,kind:'locations'}));await page.waitForTimeout(100);assert.equal(requests.length,hiddenReads);await page.selectOption(tab(0),'locations');await pane(0).getByText('Fresh hidden location data',{exact:true}).waitFor(); +step='obsolete base response cannot repopulate cache';const race=await context.newPage();let raceReads=0;await race.route('**/SpatialContext/State?*',async route=>{const n=++raceReads,r=await route.fetch(),d=await r.json();for(const l of d.locations)l.description=n===1?'Obsolete asynchronous data':'Latest asynchronous data';if(n===1)await new Promise(resolve=>setTimeout(resolve,300));await route.fulfill({json:d});});await race.goto(base+'/Writing/Context?pinned=true');const firstRead=race.waitForRequest(r=>r.url().includes('/SpatialContext/State'));await race.selectOption('[data-context-pane="0"] [data-context-tab]','locations');await firstRead;await race.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({projectId:7,bookId:12,kind:'locations'}));await race.getByText('Latest asynchronous data',{exact:true}).waitFor();await race.waitForTimeout(350);await race.locator('[data-scene-position="-1"] button').first().click();await race.getByRole('heading',{name:'Lounge',exact:true}).waitFor();await race.locator('[data-scene-position="0"] button').first().click();await race.getByRole('heading',{name:'Bedroom',exact:true}).waitFor();await race.getByText('Latest asynchronous data',{exact:true}).waitFor();await race.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/SpatialContextBrowserFixture.cs b/PlotLine.Tests/SpatialContextBrowserFixture.cs index 247c1707..fe33bd9e 100644 --- a/PlotLine.Tests/SpatialContextBrowserFixture.cs +++ b/PlotLine.Tests/SpatialContextBrowserFixture.cs @@ -5,8 +5,8 @@ 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")]); + 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=2,Name="Other map",Kind="Region",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 MapsViewModel Map(int id=1){var map=new StoryMap{MapID=id,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=id,Name="The old house",LocationID=id==1?102:null,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=id,Name="Woodland",GeometryClass="Marker",Type="Custom",X=-150,Y=-100,Width=48,Height=48,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/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index c0c8f6f7..7525c122 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -407,7 +407,7 @@ internal static class ToolbarBrowserHost 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/Map",async (HttpContext context)=>await RenderFullAsync(context,"Maps","Index",SpatialContextBrowserFixture.Map(int.TryParse(context.Request.Query["id"],out var map)?map:1),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 => { diff --git a/PlotLine/Services/Context/ContextSpatial.cs b/PlotLine/Services/Context/ContextSpatial.cs index 0642b00b..8146b821 100644 --- a/PlotLine/Services/Context/ContextSpatial.cs +++ b/PlotLine/Services/Context/ContextSpatial.cs @@ -60,14 +60,14 @@ public sealed class ContextSpatial(ISqlConnectionFactory connections,ICurrentUse 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");} + if(result.Changed){await notifications.Invalidate(Author,projectId:result.ProjectID,bookId:input.Kind=="scene"?input.BookID:(int?)null,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) { @@ -76,7 +76,7 @@ public sealed class ContextSpatial(ISqlConnectionFactory connections,ICurrentUse 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"); + tx.Commit();await notifications.Invalidate(Author,projectId:scope.ProjectID,kind:"locations"); return new{id,assignment=changed==null?null:await Accepted(target!,changed)}; } public async Task Floor(int book,int scene,int plan) diff --git a/PlotLine/wwwroot/js/context-spatial.js b/PlotLine/wwwroot/js/context-spatial.js index eae3d6c6..4843ccfe 100644 --- a/PlotLine/wwwroot/js/context-spatial.js +++ b/PlotLine/wwwroot/js/context-spatial.js @@ -7,7 +7,8 @@ const same=(a,b)=>a?.bookId===b?.bookId&&a?.sceneId===b?.sceneId; const id=l=>l?.locationID; let invalidating=false; - function state(position,location,refresh=false){const url=`/SpatialContext/State?bookId=${position.bookId}&sceneId=${position.sceneId}${location?`&locationId=${location}`:''}`;if(refresh)requests.delete(url);if(requests.size>40)requests.delete(requests.keys().next().value);if(!requests.has(url))requests.set(url,fetch(url,{cache:'no-store'}).then(async r=>{if(!r.ok||r.redirected)throw Error('Spatial context is unavailable. Check book access and refresh.');const result=await r.json();if(!location&&result.scope.primaryLocationID)requests.set(`${url}&locationId=${result.scope.primaryLocationID}`,Promise.resolve(result));return result;}).catch(e=>{requests.delete(url);throw e;}));return requests.get(url);} + function invalidateCache(){if(!invalidating){invalidating=true;requests.clear();queueMicrotask(()=>invalidating=false);}} + function state(position,location,refresh=false){const url=`/SpatialContext/State?bookId=${position.bookId}&sceneId=${position.sceneId}${location?`&locationId=${location}`:''}`;if(refresh)requests.delete(url);if(requests.size>40)requests.delete(requests.keys().next().value);if(!requests.has(url)){const promise=fetch(url,{cache:'no-store'}).then(async r=>{if(!r.ok||r.redirected)throw Error('Spatial context is unavailable. Check book access and refresh.');const result=await r.json();if(requests.get(url)===promise&&!location&&result.scope.primaryLocationID)requests.set(`${url}&locationId=${result.scope.primaryLocationID}`,Promise.resolve(result));return result;}).catch(e=>{if(requests.get(url)===promise)requests.delete(url);throw e;});requests.set(url,promise);}return requests.get(url);} function session(root){if(!sessions.has(root))sessions.set(root,{location:null,scene:null,listeners:new Set(),revision:0,select(location,source,force=false){if(!force&&this.location===location)return;this.location=location;this.revision++;for(const fn of this.listeners)fn({version:1,location,source,revision:this.revision,windowId:root.contextController?.windowId,projectId:Number(root.dataset.scopeProjectId),bookId:Number(root.dataset.scopeBookId)});}});return sessions.get(root);} function ancestors(data,location){const result=[],seen=new Set();while(location&&!seen.has(location)){seen.add(location);const r=data.locations.find(l=>id(l)===location);if(!r)break;result.push(r);location=r.parentLocationID;}return result;} function path(data,location){return ancestors(data,location).reverse().map(l=>l.locationName).join(' / ');} @@ -41,11 +42,13 @@ function details(){const host=q('[data-spatial-details]');host.replaceChildren();const current=data.scope,location=data.locations.find(l=>id(l)===selection);const actions=el('div',null,'spatial-toolbar');if(current.canEdit)actions.append(btn(`Change current scene location`,chooseAssignment),btn('New location for current scene',()=>createLocation(true,null)));host.append(actions);if(!location){host.append(el('p',selection?'The assigned or inspected location is unavailable. Choose an active location explicitly; the recorded assignment has not been changed.':'This scene has no assigned location. Inspect adjacent scenes or explicitly choose a location.'));if(current.canEdit){host.append(btn('Create new location for current scene',()=>createLocation(true,null)));for(const adjacent of data.scenes.filter(s=>s.position!==0&&s.locationID))host.append(btn(`Use ${adjacent.position<0?'previous':'next'} scene location`,()=>assign(adjacent.locationID)));}return;}const header=el('h2',location.locationName);header.prepend(icon(data,location));draggable(header,id(location));host.append(header,el('p',`${location.locationTypeName||'Unclassified'} · ${location.classification||'Unclassified'}`));const trail=el('nav',null,'spatial-path');trail.setAttribute('aria-label','Containing locations');for(const a of ancestors(data,id(location)).reverse())trail.append(btn(a.locationName,()=>select(id(a))));host.append(trail);const description=el('div',location.description||'No description recorded.','spatial-description');host.append(description);if(current.canEdit){const tools=el('div',null,'spatial-toolbar');tools.append(btn('Edit description',()=>edit('description',location)),btn('Rename',()=>edit('name',location)),btn('Type',()=>discrete('type',location)),btn('Classification',()=>discrete('classification',location)),btn('Create child',()=>createLocation(false,id(location))));host.append(tools);}const links=el('div',null,'spatial-toolbar');for(const [label,url]of [['Location Details',`/Locations/Details/${id(location)}`],['Edit Location',`/Locations/Edit/${id(location)}`]]){const a=el('a',label);a.href=url;links.append(a);}host.append(links);const children=data.locations.filter(l=>l.parentLocationID===id(location));if(children.length){const section=el('details');section.open=preferences.children!==false;section.append(el('summary',`Contained locations (${location.childCount})`));section.ontoggle=()=>{preferences.children=section.open;save();};for(const child of children)section.append(btn(child.locationName,()=>select(id(child))));if(location.childCount>children.length)section.append(el('small',`Showing ${children.length} immediate locations. Open Locations for the complete directory.`));host.append(section);}if(data.relationships.length){const section=el('details');section.append(el('summary','Recorded relationships'));for(const r of data.relationships)section.append(el('p',`${r.fromName} · ${r.typeName} · ${r.toName}${r.notes?' — '+r.notes:''}`));host.append(section);}const spatial=el('div',null,'spatial-toolbar');for(const tool of ['maps','floorplans']){const found=resolution(data,id(location),tool);spatial.append(btn(`Show ${tool==='maps'?'map':'floor plan'}${found.some(f=>f.depth)?' (containing location)':''}`,()=>showTool(tool)));if(tool==='maps'&¤t.canEdit&&!found.some(f=>f.depth===0))spatial.append(btn('Place on map',()=>{bus.pendingPlacement=selection;return showTool('maps');}));}host.append(spatial);} function catalog(){return kind==='maps'?data.mapCatalog:data.planCatalog;} function relevant(){const found=resolution(data,selection,kind);if(found.length)return found.sort((a,b)=>data.scenes.filter(s=>resolution(data,s.locationID,kind).some(l=>l.resourceID===b.resourceID)).length-data.scenes.filter(s=>resolution(data,s.locationID,kind).some(l=>l.resourceID===a.resourceID)).length||a.name.localeCompare(b.name));return data.scenes.flatMap(s=>resolution(data,s.locationID,kind));} - function draw(){if(!data||disposed)return;error.textContent='';scenes();q('[data-spatial-return]').disabled=selection===data.scope.primaryLocationID;q('[data-spatial-return]').onclick=()=>select(data.scope.primaryLocationID);if(kind==='locations'){details();return;}const options=catalog(),links=relevant(),available=new Set(links.map(l=>l.resourceID));const preferred=Number(preferences.resource);const next=resource&&available.has(resource)?resource:available.has(preferred)?preferred:links[0]?.resourceID||resource&&options.some(x=>x.id===resource)&&resource||null;const menu=q('[data-spatial-resource]');menu.replaceChildren(new Option('Choose existing resource',''),...options.map(r=>new Option(r.name,String(r.id))));menu.value=next||'';menu.onchange=()=>{resource=Number(menu.value)||null;preferences.resource=resource;save();void renderResource();};const selectedLinks=resolution(data,selection,kind).filter(x=>x.resourceID===next);q('[data-spatial-resolution]').textContent=selectedLinks.length?(selectedLinks[0].depth?`Represented through containing location: ${path(data,selectedLinks[0].represented)}. This is not an exact position for the inspected location.`:'Directly associated with the inspected location.'):'No authoritative representation of the inspected location on this resource.';if(resource!==next){resource=next;void renderResource();}else if(renderer){if(renderer.revision!==String(catalog().find(c=>c.id===resource)?.modifiedDate)){void renderResource();}else highlight();}else void renderResource();q('[data-spatial-place]').disabled=!data.scope.canEdit||!resource||(kind==='maps'&&!selection);q('[data-spatial-place]').onclick=()=>kind==='maps'?startPlacement(selection):chooseRoom();const advanced=q('[data-spatial-advanced]');advanced.href=kind==='maps'?`/Maps?projectId=${position.projectId}&id=${resource}`:`/FloorPlans/Edit/${resource}`;advanced.hidden=!resource;} + function draw(){if(!data||disposed)return;error.textContent='';scenes();if(kind==='maps')q('[data-spatial-feature]').replaceChildren();q('[data-spatial-return]').disabled=selection===data.scope.primaryLocationID;q('[data-spatial-return]').onclick=()=>select(data.scope.primaryLocationID);if(kind==='locations'){details();return;}const options=catalog(),links=relevant(),available=new Set(links.map(l=>l.resourceID));const preferred=Number(preferences.resource);const next=resource&&available.has(resource)?resource:available.has(preferred)?preferred:links[0]?.resourceID||resource&&options.some(x=>x.id===resource)&&resource||null;const menu=q('[data-spatial-resource]');menu.replaceChildren(new Option('Choose existing resource',''),...options.map(r=>new Option(r.name,String(r.id))));menu.value=next||'';menu.onchange=()=>{resource=Number(menu.value)||null;preferences.resource=resource;save();void renderResource();};q('[data-spatial-resolution]').textContent=resourceCaption(next);if(resource!==next){resource=next;void renderResource();}else if(renderer){if(renderer.revision!==String(catalog().find(c=>c.id===resource)?.modifiedDate)){void renderResource();}else highlight();}else void renderResource();q('[data-spatial-place]').disabled=!data.scope.canEdit||!resource||(kind==='maps'&&!selection);q('[data-spatial-place]').onclick=()=>kind==='maps'?startPlacement(selection):chooseRoom();updateAdvanced();} + function updateAdvanced(){const advanced=q('[data-spatial-advanced]');const represented=resolution(data,selection,kind).find(l=>l.resourceID===resource);advanced.href=kind==='maps'?`/Maps?projectId=${position.projectId}&id=${resource}${represented?.featureID?'&featureId='+encodeURIComponent(represented.featureID):''}`:`/FloorPlans/Edit/${resource}${represented?.blockID?'?selectedBlockId='+represented.blockID:''}`;advanced.hidden=!resource;} + function resourceCaption(target=resource){const found=resolution(data,selection,kind).filter(x=>x.resourceID===target);return found.length?(found[0].depth?`Represented through containing location: ${path(data,found[0].represented)}. This is not an exact position for the inspected location.`:'Directly associated with the inspected location.'):'No authoritative representation of the inspected location on this resource.';} function sceneHighlights(){const grouped=new Map();for(const s of data.scenes){const found=resolution(data,s.locationID,kind).filter(l=>l.resourceID===resource);for(const f of found){const key=kind==='maps'?f.featureID:f.blockID;if(!key)continue;if(!grouped.has(key))grouped.set(key,{featureID:key,roles:[],label:[]});const value=grouped.get(key);value.roles.push(s.position);value.label.push(`${['Previous','Current','Next'][s.position+1]}: ${path(data,s.locationID)}${f.depth?' (containing location)':''}`);}}return [...grouped.values()].map(x=>({...x,label:x.label.join(' · ')}));} function annotate(){if(kind==='locations'||!data)return;for(const scene of data.scenes){const row=q(`[data-scene-position="${scene.position}"]`);if(!row)continue;row.querySelector('.spatial-elsewhere')?.remove();const resolved=resolution(data,scene.locationID,kind),here=resolved.filter(l=>l.resourceID===resource);let label='';if(scene.locationID){if(!resolved.length)label=kind==='maps'?'No mapped representation':'No associated plan';else if(!here.length)label=kind==='maps'?'On another map':'On another plan';else if(kind==='floorplans'&&here.every(l=>l.floorID&&l.floorID!==renderer?.getFloor?.()))label='On another level';else if(kind==='floorplans'&&!here.some(l=>l.blockID))label='Plan available; no associated room';else if(here.some(l=>l.depth))label='Containing location represented';}if(label)row.append(el('small',label,'spatial-elsewhere'));}} function highlight(){if(!renderer)return;annotate();renderer.highlight(sceneHighlights());const target=resolution(data,selection,kind).find(x=>x.resourceID===resource);if(renderer.selection!==selection){renderer.selection=selection;if(target){if(kind==='floorplans'&&!target.blockID&&target.floorID)renderer.floor?.(target.floorID);else renderer.centre(kind==='maps'?target.featureID:target.blockID,false);}}if(kind==='maps'&&bus.pendingPlacement&&renderer.map?.()){const target=bus.pendingPlacement;bus.pendingPlacement=null;void startPlacement(target).catch(fail);}} - async function renderResource(){if(!canvas)return;const item=catalog().find(c=>c.id===resource);if(!item){renderer?.dispose();renderer=null;canvas.replaceChildren(el('p',`No suitable ${kind==='maps'?'map':'floor plan'} is associated. Choose an existing resource above or open the main World workspace.`));return;}if(kind==='maps'&&renderer?.id===resource){renderer.revision=String(item.modifiedDate);renderer.command('reload');return;}if(kind==='floorplans'&&renderer)floorSnapshot={id:renderer.id,floor:renderer.getFloor?.(),selection:renderer.selection};renderer?.dispose();renderer=null;canvas.replaceChildren();const target=resource,scope={...position};if(kind==='maps'){const frame=el('iframe');frame.title='Context map';frame.src=`/SpatialContext/Map?bookId=${scope.bookId}&sceneId=${scope.sceneId}&id=${target}`;const channel=crypto.randomUUID();let features=[],map,ready=false;const command=(action,args={})=>frame.contentWindow?.postMessage({type:'plotdirector.spatial.command',channel,action,...args},location.origin);const receive=e=>{if(e.origin!==location.origin||e.source!==frame.contentWindow||e.data?.channel!==channel||e.data.type!=='plotdirector.spatial.renderer')return;const m=e.data;if(m.action==='ready'){features=m.features;map=m.map;ready=true;highlight();if(bus.pendingPlacement){const target=bus.pendingPlacement;bus.pendingPlacement=null;void startPlacement(target).catch(fail);}}if(m.action==='viewport'){preferences.views??={};preferences.views[target]=m.view;save();}if(m.action==='select'&&m.feature?.locationID)void select(m.feature.locationID);if(m.action==='cancel'&&operation)clearOperation();if(m.action==='place'&&operation)void savePlacement(m.point);if(m.action==='drop'&&validDrop(m.payload))void dropPlacement(m.payload.locationId,m.point);if(m.action==='error')fail(Error(m.message));};window.addEventListener('message',receive);renderer={id:target,revision:String(item.modifiedDate),command,highlight:items=>command('highlight',{highlights:items}),centre:(id,force)=>{if(ready)command('centre',{id,force});},fit:()=>command('fit',{ids:sceneHighlights().map(h=>h.featureID)}),zoom:factor=>command('zoom',{factor}),features:()=>features,map:()=>map,dispose:()=>window.removeEventListener('message',receive)};frame.onload=()=>command('init',{view:preferences.views?.[target]});canvas.append(frame);}else{const request=++epoch;try{const response=await fetch(`/SpatialContext/Floor?bookId=${scope.bookId}&sceneId=${scope.sceneId}&id=${target}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error('Floor plan unavailable.');const html=await response.text();if(disposed||request!==epoch||resource!==target)return;canvas.innerHTML=html;renderer=floorRenderer(canvas,item);if(floorSnapshot?.id===item.id){renderer.floor?.(floorSnapshot.floor);renderer.selection=floorSnapshot.selection;}highlight();}catch(e){fail(e);}}} + async function renderResource(){if(!canvas)return;updateAdvanced();q('[data-spatial-feature]').replaceChildren();q('[data-spatial-resolution]').textContent=resourceCaption();const item=catalog().find(c=>c.id===resource);if(!item){renderer?.dispose();renderer=null;canvas.replaceChildren(el('p',`No suitable ${kind==='maps'?'map':'floor plan'} is associated. Choose an existing resource above or open the main World workspace.`));return;}if(kind==='maps'&&renderer?.id===resource){renderer.revision=String(item.modifiedDate);renderer.command('reload');return;}if(kind==='floorplans'&&renderer)floorSnapshot={id:renderer.id,floor:renderer.getFloor?.(),selection:renderer.selection};renderer?.dispose();renderer=null;canvas.replaceChildren();const target=resource,scope={...position};if(kind==='maps'){const frame=el('iframe');frame.title='Context map';frame.src=`/SpatialContext/Map?bookId=${scope.bookId}&sceneId=${scope.sceneId}&id=${target}`;const channel=crypto.randomUUID();let features=[],map,ready=false;const command=(action,args={})=>frame.contentWindow?.postMessage({type:'plotdirector.spatial.command',channel,action,...args},location.origin);const receive=e=>{if(e.origin!==location.origin||e.source!==frame.contentWindow||e.data?.channel!==channel||e.data.type!=='plotdirector.spatial.renderer')return;const m=e.data;if(m.action==='ready'){features=m.features;map=m.map;ready=true;highlight();if(bus.pendingPlacement){const target=bus.pendingPlacement;bus.pendingPlacement=null;void startPlacement(target).catch(fail);}}if(m.action==='viewport'){preferences.views??={};preferences.views[target]=m.view;save();}if(m.action==='select'&&m.feature)void(async()=>{if(m.feature.locationID)await select(m.feature.locationID);if(disposed||renderer?.id!==target)return;const detail=q('[data-spatial-feature]');detail.replaceChildren(el('strong',m.feature.name),el('small',m.feature.locationID?'Associated story location':'No associated location; inspection does not assign this feature to a scene.'));if(m.feature.notes)detail.append(el('p',m.feature.notes));q('[data-spatial-advanced]').href=`/Maps?projectId=${position.projectId}&id=${target}&featureId=${encodeURIComponent(m.feature.featureID)}`;})().catch(fail);if(m.action==='cancel'&&operation)clearOperation();if(m.action==='place'&&operation)void savePlacement(m.point);if(m.action==='drop'&&validDrop(m.payload))void dropPlacement(m.payload.locationId,m.point);if(m.action==='error')fail(Error(m.message));};window.addEventListener('message',receive);renderer={id:target,revision:String(item.modifiedDate),command,highlight:items=>command('highlight',{highlights:items}),centre:(id,force)=>{if(ready)command('centre',{id,force});},fit:()=>command('fit',{ids:sceneHighlights().map(h=>h.featureID)}),zoom:factor=>command('zoom',{factor}),features:()=>features,map:()=>map,dispose:()=>window.removeEventListener('message',receive)};frame.onload=()=>command('init',{view:preferences.views?.[target]});canvas.append(frame);}else{const request=++epoch;try{const response=await fetch(`/SpatialContext/Floor?bookId=${scope.bookId}&sceneId=${scope.sceneId}&id=${target}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error('Floor plan unavailable.');const html=await response.text();if(disposed||request!==epoch||resource!==target)return;canvas.innerHTML=html;renderer=floorRenderer(canvas,item);if(floorSnapshot?.id===item.id){renderer.floor?.(floorSnapshot.floor);renderer.selection=floorSnapshot.selection;}highlight();}catch(e){fail(e);}}} function floorRenderer(host,item){const container=host.querySelector('[data-spatial-floor-canvas]'),world=container.querySelector('[data-spatial-floor-world]'),viewport=container.querySelector('.spatial-floor-viewport'),level=container.querySelector('[data-spatial-floor]'),versions=JSON.parse(container.querySelector('[data-room-versions]').textContent);const engine=window.PlotDirectorFloorPlanRenderer.create(container);let view={x:0,y:0,scale:1},drag=null;const panels=[...container.querySelectorAll('[data-floor-panel]')],blocks=[...container.querySelectorAll('[data-block]')];const signal=new AbortController();function current(){return panels.find(p=>p.dataset.floorPanel===level.value);}function transform(){world.style.transform=`translate(${view.x}px,${view.y}px) scale(${view.scale})`;preferences.floorViews??={};preferences.floorViews[`${item.id}/${level.value}`]={...view};save();}function fit(){const grid=current()?.querySelector('[data-floor-grid]');if(!grid)return;const w=grid.offsetWidth||Number(grid.dataset.gridWidth)*34,h=grid.offsetHeight||Number(grid.dataset.gridHeight)*34;view={scale:Math.min((viewport.clientWidth-24)/w,(viewport.clientHeight-24)/h,1.5),x:12,y:12};transform();}function change(){queueMicrotask(annotate);if(!current()){viewport.replaceChildren(el('p','This plan has no floors yet. Open Floor Plans to add a level.'));return;}for(const p of panels)p.classList.toggle('active',p===current());const visibleBlocks=engine.refreshSharedWalls(current());engine.refreshHiddenLocationStyles(visibleBlocks);engine.positionTransitions(current(),visibleBlocks);view=preferences.floorViews?.[`${item.id}/${level.value}`]||{x:0,y:0,scale:1};transform();if(!preferences.floorViews?.[`${item.id}/${level.value}`])fit();}level.onchange=change;function centre(blockId,force){const block=blocks.find(b=>Number(b.dataset.block)===Number(blockId));if(!block)return;const panel=block.closest('[data-floor-panel]');if(level.value!==panel.dataset.floorPanel){level.value=panel.dataset.floorPanel;change();}blocks.forEach(b=>b.classList.toggle('spatial-selected',b===block));if(force){const x=block.offsetLeft,y=block.offsetTop;view.x=viewport.clientWidth/2-(x+block.offsetWidth/2)*view.scale;view.y=viewport.clientHeight/2-(y+block.offsetHeight/2)*view.scale;transform();}} for(const b of blocks){b.tabIndex=0;b.setAttribute('role','button');b.setAttribute('aria-label',b.textContent.trim());b.addEventListener('click',()=>{if(drag?.moved)return;const location=Number(b.dataset.locationId);if(location)void select(location);showRoom(b);},{signal:signal.signal});b.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();b.click();}},{signal:signal.signal});b.addEventListener('dragover',e=>{if(e.dataTransfer.types.includes(mime)){e.preventDefault();b.classList.add('spatial-drop');}},{signal:signal.signal});b.addEventListener('dragleave',()=>b.classList.remove('spatial-drop'),{signal:signal.signal});b.addEventListener('drop',e=>{e.preventDefault();b.classList.remove('spatial-drop');try{const p=JSON.parse(e.dataTransfer.getData(mime));if(validDrop(p))void associateRoom(b,p.locationId);}catch(error){fail(error);}},{signal:signal.signal});} viewport.addEventListener('wheel',e=>{e.preventDefault();const r=viewport.getBoundingClientRect(),x=e.clientX-r.left,y=e.clientY-r.top,scale=Math.max(.08,Math.min(4,view.scale*Math.exp(-e.deltaY*.001)));view.x=x-(x-view.x)*scale/view.scale;view.y=y-(y-view.y)*scale/view.scale;view.scale=scale;transform();},{passive:false,signal:signal.signal});viewport.addEventListener('pointerdown',e=>{if(e.button!==0)return;drag={x:e.clientX,y:e.clientY,vx:view.x,vy:view.y,moved:false};if(!e.target.closest('[data-block]'))viewport.setPointerCapture(e.pointerId);},{signal:signal.signal});viewport.addEventListener('pointermove',e=>{if(!drag||!viewport.hasPointerCapture(e.pointerId))return;drag.moved=Math.hypot(e.clientX-drag.x,e.clientY-drag.y)>4;view.x=drag.vx+e.clientX-drag.x;view.y=drag.vy+e.clientY-drag.y;transform();},{signal:signal.signal});viewport.addEventListener('pointerup',e=>{if(viewport.hasPointerCapture(e.pointerId))viewport.releasePointerCapture(e.pointerId);setTimeout(()=>drag=null,0);},{signal:signal.signal}); @@ -60,8 +63,8 @@ async function dropPlacement(location,point){try{const existing=renderer?.features().find(f=>f.locationID===location);if(existing)throw Error('This location already has a representation on this map. Use Place location to reveal or explicitly reposition it.');const map=renderer.map(),target={bookID:position.bookId,sceneID:position.sceneId,kind:'map',locationID:location,resourceID:resource,expected:String(map.revision),x:point.x,y:point.y};await confirmOperation('Place this existing location at the dropped map position?',async()=>finish(await post('/SpatialContext/Mutate',target)));}catch(e){fail(e);}} function chooseRoom(){if(!renderer?.blocks)return;const feature=q('[data-spatial-feature]');feature.replaceChildren(el('p','Select a room to associate an existing location. No geometry or parent location will be changed.'));const plan=data.planCatalog.find(p=>p.id===resource);if(plan)feature.append(btn('Associate this plan with a location',async()=>{const chosen=await picker('Associate floor plan with existing location',plan.locationID);if(chosen===undefined||chosen===null||chosen===plan.locationID)return;const target={bookID:position.bookId,sceneID:position.sceneId,kind:'plan',locationID:chosen,resourceID:resource,expected:plan.version,replace:!!plan.locationID};await confirmOperation('Associate this plan with the selected existing location?',async()=>finish(await post('/SpatialContext/Mutate',target)));}));} for(const b of node.querySelectorAll('[data-spatial-zoom]'))b.onclick=()=>renderer?.zoom(b.dataset.spatialZoom==='in'?1.25:.8);q('[data-spatial-fit]')?.addEventListener('click',()=>renderer?.fit());q('[data-spatial-centre]')?.addEventListener('click',()=>{const found=resolution(data,selection,kind).find(l=>l.resourceID===resource);if(found)renderer?.centre(kind==='maps'?found.featureID:found.blockID,true);}); - instances.set(node,{position(next){if(busy)return false;position=next;void reload();return true;},invalidate(hint){if(busy)return false;if(!['locations','maps','floorplans','spatial','structure','characters','relationships','assets',undefined].includes(hint.kind))return true;if(kind==='floorplans'&&renderer&&['locations','spatial',undefined].includes(hint.kind))renderer.revision=null;if(!invalidating){invalidating=true;requests.clear();queueMicrotask(()=>invalidating=false);}void reload();return true;},dispose(){disposed=true;epoch++;bus.listeners.delete(listener);renderer?.dispose();abort.abort();},busy:()=>busy});void reload(); + instances.set(node,{position(next){if(busy)return false;position=next;void reload();return true;},invalidate(hint){if(busy)return false;if(!['locations','maps','floorplans','spatial','structure','characters','relationships','assets',undefined].includes(hint.kind))return true;if(kind==='floorplans'&&renderer&&['locations','spatial',undefined].includes(hint.kind))renderer.revision=null;invalidateCache();void reload();return true;},dispose(){disposed=true;epoch++;bus.listeners.delete(listener);renderer?.dispose();abort.abort();},busy:()=>busy});void reload(); } - window.PlotDirectorContextLifecycles??={};window.PlotDirectorContextLifecycles.spatial={mount,dispose:node=>{instances.get(node)?.dispose();instances.delete(node);},canRefresh:node=>!instances.get(node)?.busy(),onPosition:(node,next)=>instances.get(node)?.position(next)===true,onInvalidation:(node,hint)=>instances.get(node)?.invalidate(hint)===true}; + window.PlotDirectorContextLifecycles??={};window.PlotDirectorContextLifecycles.spatial={mount,onCacheInvalidation:invalidateCache,dispose:node=>{instances.get(node)?.dispose();instances.delete(node);},canRefresh:node=>!instances.get(node)?.busy(),onPosition:(node,next)=>instances.get(node)?.position(next)===true,onInvalidation:(node,hint)=>instances.get(node)?.invalidate(hint)===true}; window.PlotDirectorSpatialContext=Object.freeze({ancestors,resolution,path,subscribe(root,listener){const s=session(root);s.listeners.add(listener);return()=>s.listeners.delete(listener);},inspect(root,location,source){if(location!==null&&(!Number.isSafeInteger(location)||location<=0))throw TypeError('A canonical location identifier is required.');session(root).select(location,source);}}); })(); diff --git a/PlotLine/wwwroot/js/context-workspace.js b/PlotLine/wwwroot/js/context-workspace.js index 8f7bb3a1..3da31cf1 100644 --- a/PlotLine/wwwroot/js/context-workspace.js +++ b/PlotLine/wwwroot/js/context-workspace.js @@ -128,6 +128,7 @@ generation++;cancelRequests(); for(const pane of panes){for(const record of pane.records.values()){ if(record.tab.contentRefresh==='none')continue; + lifecycles[record.tab.lifecycle]?.onCacheInvalidation?.(hint,record.node); const customInvalidation=lifecycles[record.tab.lifecycle]?.onInvalidation; if(customInvalidation){if(record.mounted&&visible(pane)&&!guarded(record)&&!scopeChanged(record.tab,record.position||position,position)&&customInvalidation(record.node,hint)===true){record.stale=false;continue;}record.stale=true;continue;} if(hint.kind==='names'&&record.tab.id!=='names')continue;