fix(context): refresh canonical spatial editors through shared notifications
This commit is contained in:
parent
01757170c7
commit
587f067da9
@ -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. 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.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
10
PlotLine.Tests/Browser/context-spatial-development.cjs
Normal file
10
PlotLine.Tests/Browser/context-spatial-development.cjs
Normal file
@ -0,0 +1,10 @@
|
||||
// Development only. All writes target this dedicated synthetic author's owned fixture project.
|
||||
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-'));const f=identity.SpatialFixture;assert(f?.scenes?.length===3);const base='https://dev.plotdirector.com',out='/tmp/pd-spatial-evidence';
|
||||
(async()=>{const browser=await chromium.launch();let step='login';try{const context=await browser.newContext({viewport:{width:1600,height:1050}}),page=await context.newPage(),errors=[],mutations=[];page.on('pageerror',e=>errors.push(e.message));page.on('request',r=>{if(r.url().includes('/SpatialContext/Mutate'))mutations.push(r.postDataJSON());});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()]);const scope=`projectId=${identity.ProjectID}&bookId=${identity.BookID}&sceneId=${f.scenes[1]}&pinned=true`;await page.goto(base+'/Writing/Context?'+scope);await page.selectOption('[data-context-pane="0"] [data-context-tab]','locations');const pane=i=>page.locator(`[data-context-pane="${i}"]`),shot=name=>page.screenshot({path:`${out}/development-${name}.png`});await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor();const token=await pane(0).locator('[name=__RequestVerificationToken]').inputValue();async function state(){const r=await page.request.get(base+`/SpatialContext/State?bookId=${identity.BookID}&sceneId=${f.scenes[1]}`);assert.equal(r.status(),200);return r.json();}async function mapState(){const r=await page.request.get(base+`/Maps/State?projectId=${identity.ProjectID}&id=${f.mapId}`);assert.equal(r.status(),200);return r.json();}async function waitState(test){for(let i=0;i<30;i++){const value=await state();if(test(value))return value;await page.waitForTimeout(100);}throw Error('Saved state did not reach expected value.');}async function undo(i){await pane(i).getByRole('button',{name:'Undo spatial change',exact:true}).click();}async function chooseLocation(location){const dialog=page.locator('dialog[open]').last();await dialog.locator(`[data-picker-id="${location}"] .pd-location-picker-name`).click();await dialog.getByRole('button',{name:'Choose',exact:true}).click();}
|
||||
step='authoritative sequence';let data=await state();assert.deepEqual(data.scenes.map(s=>s.sceneID),f.scenes);assert.equal(data.scenes[0].chapterID,f.chapters[0]);assert.equal(data.scenes[1].chapterID,f.chapters[1]);assert.equal(data.scope.primaryLocationID,f.locations[1]);const originalMap=await mapState(),originalFeature=JSON.stringify(originalMap.features[0]);await shot('locations');
|
||||
step='explicit current-scene assignment while inspecting adjacent';await pane(0).locator('[data-scene-position="-1"] button').first().click();await pane(0).getByRole('heading',{name:'Lounge',exact:true}).waitFor();await pane(0).getByRole('button',{name:'Change current scene location',exact:true}).click();await chooseLocation(f.locations[3]);await waitState(x=>x.scope.primaryLocationID===f.locations[3]);assert.equal(mutations.at(-1).sceneID,f.scenes[1]);assert.equal(mutations.at(-1).locationID,f.locations[3]);await undo(0);await waitState(x=>x.scope.primaryLocationID===f.locations[1]);await pane(0).getByRole('button',{name:'Return to scene location',exact:true}).click();await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor();
|
||||
step='description and existing protected Undo';await pane(0).getByRole('button',{name:'Edit description',exact:true}).click();await pane(0).locator('textarea').fill('Spatial acceptance prose, saved exactly without AI.');await pane(0).getByRole('button',{name:'Save',exact:true}).click();await pane(0).getByText('Spatial acceptance prose, saved exactly without AI.',{exact:true}).waitFor();await undo(0);await waitState(x=>!x.locations.find(l=>l.locationID===f.locations[1]).description);
|
||||
step='map placement and Undo';const liveMap=await context.newPage();await liveMap.goto(base+`/Maps?projectId=${identity.ProjectID}&id=${f.mapId}`);await liveMap.waitForFunction(()=>!!window.PlotDirectorPresenceConnection&&!!window.PlotDirectorMapWorkspace);await page.bringToFront();await page.selectOption('[data-context-layout]','columns');await page.selectOption('[data-context-pane="1"] [data-context-tab]','maps');await pane(1).locator('iframe').waitFor();await page.waitForFunction(()=>document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.document.features.length===1);const mapFrame=page.frames().find(frame=>frame.url().includes('/SpatialContext/Map'));await shot('locations-maps');await pane(1).getByRole('button',{name:'Place location',exact:true}).click();await pane(1).locator('[data-spatial-operation]').filter({hasText:'Place existing location: Bedroom'}).waitFor();await shot('placement');await mapFrame.locator('#mapsCanvas').click({position:{x:150,y:130}});await waitState(x=>x.maps.some(m=>m.locationID===f.locations[1]));await liveMap.waitForFunction(()=>PlotDirectorMapWorkspace.document.features.length===2);let saved=await mapState();assert.equal(saved.features.filter(x=>x.locationID===f.locations[1]).length,1);assert.equal(JSON.stringify(saved.features.find(x=>x.featureID===originalMap.features[0].featureID)),originalFeature);const marker=saved.features.find(x=>x.locationID===f.locations[1]);const main=await context.newPage();await main.goto(base+`/Maps?projectId=${identity.ProjectID}&id=${f.mapId}&featureId=${marker.featureID}`);await main.waitForFunction(id=>PlotDirectorMapWorkspace?.selected.includes(id),marker.featureID);await main.close();await undo(1);await waitState(x=>!x.maps.some(m=>m.locationID===f.locations[1]));assert.equal((await mapState()).features.length,1);await liveMap.waitForFunction(()=>PlotDirectorMapWorkspace.document.features.length===1);await liveMap.close();
|
||||
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');
|
||||
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}`,`/Relationships?projectId=${identity.ProjectID}`,`/Maps?projectId=${identity.ProjectID}&id=${f.mapId}`,`/FloorPlans/Edit/${f.planId}`,`/Assets?projectId=${identity.ProjectID}`]){const response=await verification.goto(base+route);assert.equal(response.status(),200,route);checks.push(route.split('?')[0]);}await verification.close();
|
||||
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.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();}})();
|
||||
2
PlotLine.Tests/Browser/spatial-main-live-updates.cjs
Normal file
2
PlotLine.Tests/Browser/spatial-main-live-updates.cjs
Normal file
@ -0,0 +1,2 @@
|
||||
const{chromium}=require('playwright'),assert=require('node:assert/strict');(async()=>{const browser=await chromium.launch();try{const p=await browser.newPage();const errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto('http://127.0.0.1:5238/fixture?page=maps');await p.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);await p.addScriptTag({url:'http://127.0.0.1:5238/js/spatial-live-updates.js'});await p.waitForFunction(()=>!!window.PlotDirectorSpatialLiveUpdates);await p.evaluate(()=>PlotDirectorMapWorkspace.setView({x:30,y:40,w:900,h:650}));const doc=await p.evaluate(()=>structuredClone(PlotDirectorMapWorkspace.document));doc.map.revision++;doc.features.push({featureID:'11111111-2222-4333-8444-555555555555',mapID:1,name:'Persisted elsewhere',type:'Custom',geometryClass:'Marker',layer:'Places',x:90,y:100,width:48,height:48,isPlaced:true,showLabel:true,geometryJson:'{}'});let reads=0;await p.route('**/Maps/State?*',r=>{reads++;return r.fulfill({json:doc});});await p.evaluate(()=>PlotDirectorSpatialLiveUpdates.refresh({projectId:7,kind:'maps'}));assert.equal(await p.evaluate(()=>PlotDirectorMapWorkspace.document.features.length),1);assert.equal(await p.evaluate(()=>PlotDirectorMapWorkspace.view.w),900);await p.evaluate(()=>PlotDirectorMapWorkspace.edit(()=>PlotDirectorMapWorkspace.document.features[0].x=333));const before=reads;await p.evaluate(()=>PlotDirectorSpatialLiveUpdates.refresh({projectId:7,kind:'maps'}));assert.equal(reads,before);assert.equal(await p.evaluate(()=>PlotDirectorMapWorkspace.document.features[0].x),333);
|
||||
await p.goto('http://127.0.0.1:5238/fixture?page=floorplans');await p.waitForSelector('[data-floor-plan-initialized=true]');await p.route('**/FloorPlans/Edit/31',async r=>{const response=await r.fetch({url:'http://127.0.0.1:5238/fixture?page=floorplans'});return r.fulfill({response,body:(await response.text()).replace('data-location-id=""','data-location-id="99"')});});const original=await p.locator('[data-floor-plan-workspace]').elementHandle();await p.evaluate(()=>PlotDirectorSpatialLiveUpdates.refresh({projectId:7,kind:'floorplans'}));assert.equal(await original.evaluate(n=>n.isConnected),false);await p.waitForSelector('[data-floor-plan-initialized=true]');const current=await p.locator('[data-floor-plan-workspace]').elementHandle();await p.evaluate(()=>document.querySelector('[data-save-status]').dataset.saveState='dirty');await p.evaluate(()=>PlotDirectorSpatialLiveUpdates.refresh({projectId:7,kind:'floorplans'}));assert.equal(await current.evaluate(n=>n.isConnected),true);assert.deepEqual(errors,[]);console.log('PASS main spatial live updates: existing connection, in-place clean map refresh, retained viewport, clean floor workspace refresh, unsaved map/floor protection');}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
@ -10,10 +10,10 @@ public sealed class ContextReferenceInvalidationFilter(ContextWorkspaceNotificat
|
||||
var result = await next();
|
||||
var controller = context.RouteData.Values["controller"]?.ToString();
|
||||
if (controller == "Writer" && context.RouteData.Values["action"]?.ToString() != "SaveChapterGoal") return;
|
||||
if (!HttpMethods.IsPost(context.HttpContext.Request.Method) || controller is not ("Scenes" or "Writer" or "Characters" or "CharacterWorkspace" or "RelationshipMap" or "Chapters" or "PlotLines" or "PlotLineWorkspace" or "Timeline" or "Locations" or "WriterAuthoring" or "WriterReview" or "IntelligenceReview" or "ParagraphManuscript") ||
|
||||
if (!HttpMethods.IsPost(context.HttpContext.Request.Method) || controller is not ("Scenes" or "Writer" or "Characters" or "CharacterWorkspace" or "RelationshipMap" or "Chapters" or "PlotLines" or "PlotLineWorkspace" or "Timeline" or "Locations" or "WriterAuthoring" or "WriterReview" or "IntelligenceReview" or "ParagraphManuscript" or "Maps" or "FloorPlans") ||
|
||||
currentUser.UserId is not int user || result.Exception != null || !context.ModelState.IsValid) return;
|
||||
if (result.Result is ForbidResult or ChallengeResult) return;
|
||||
var status = result.Result switch { ObjectResult value => value.StatusCode ?? 200, StatusCodeResult value => value.StatusCode, _ => 200 };
|
||||
if(status<400&&!notifications.AlreadyInvalidated){var kind=controller switch{"RelationshipMap"=>"relationships","Characters"=>context.RouteData.Values["action"]?.ToString()?.Contains("Relationship")==true?"relationships":"characters","Chapters" or "Scenes"=>"structure",_=>null};await notifications.Invalidate(user,kind:kind);}
|
||||
if(status<400&&!notifications.AlreadyInvalidated){var kind=controller switch{"RelationshipMap"=>"relationships","Characters"=>context.RouteData.Values["action"]?.ToString()?.Contains("Relationship")==true?"relationships":"characters","Chapters" or "Scenes"=>"structure","Maps"=>"maps","FloorPlans"=>"floorplans",_=>null};await notifications.Invalidate(user,kind:kind);}
|
||||
}
|
||||
}
|
||||
|
||||
@ -58,7 +58,7 @@
|
||||
<div class="alert alert-danger">@error</div>
|
||||
}
|
||||
|
||||
<div data-floor-plan-workspace data-floor-plan-id="@Model.FloorPlan.FloorPlanID">
|
||||
<div data-floor-plan-workspace data-floor-plan-id="@Model.FloorPlan.FloorPlanID" data-spatial-project-id="@Model.Project.ProjectID">
|
||||
@if (!Model.Floors.Any())
|
||||
{
|
||||
<section class="empty-panel">
|
||||
@ -860,6 +860,7 @@
|
||||
|
||||
@section Scripts {
|
||||
<partial name="_ValidationScriptsPartial" />
|
||||
<script src="~/js/spatial-live-updates.js" asp-append-version="true"></script>
|
||||
<script src="~/js/floor-plan-renderer.js" asp-append-version="true"></script>
|
||||
<script src="~/js/workspace-surface.js" asp-append-version="true"></script>
|
||||
<script>
|
||||
@ -1290,7 +1291,7 @@
|
||||
document.body.scrollTop = state.pageY || 0;
|
||||
}
|
||||
|
||||
async function refreshWorkspaceAsync(state, preserveLiveState = false) {
|
||||
async function refreshWorkspaceAsync(state, preserveLiveState = false, canReplace = () => true) {
|
||||
const floorPlanId = workspace?.dataset.floorPlanId;
|
||||
if (!workspace || !floorPlanId) return;
|
||||
|
||||
@ -1310,6 +1311,7 @@
|
||||
throw new Error("The refreshed floor plan workspace was not found.");
|
||||
}
|
||||
|
||||
if (!canReplace()) return false;
|
||||
if (preserveLiveState) state = workspaceState();
|
||||
cleanupModalArtifacts();
|
||||
workspace.dispatchEvent(new Event("floor-plan-dispose"));
|
||||
@ -1335,6 +1337,13 @@
|
||||
});
|
||||
}
|
||||
|
||||
workspace.refreshSpatialReference = async () => {
|
||||
const clean = () => workspace.isConnected && !saveInFlight && saveStatus?.dataset.saveState === "saved" && !workspace.contains(document.activeElement?.closest("input,textarea,select"));
|
||||
if (!clean()) return false;
|
||||
await refreshWorkspaceAsync(workspaceState(), true, clean);
|
||||
return !workspace.isConnected;
|
||||
};
|
||||
|
||||
let activeSave = Promise.resolve();
|
||||
function saveLayoutAsync() {
|
||||
activeSave = activeSave.then(performSaveLayoutAsync);
|
||||
|
||||
@ -96,6 +96,7 @@
|
||||
<script src="~/js/maps-workspace.js" asp-append-version="true"></script>
|
||||
<script src="~/js/maps-appearance.js" asp-append-version="true"></script>
|
||||
@if(ViewData["SpatialRenderer"] is not true){
|
||||
<script src="~/js/spatial-live-updates.js" asp-append-version="true"></script>
|
||||
<script src="~/js/maps-story-engine.js" asp-append-version="true"></script>
|
||||
<script src="~/js/maps-story.js" asp-append-version="true"></script>
|
||||
}
|
||||
|
||||
22
PlotLine/wwwroot/js/spatial-live-updates.js
Normal file
22
PlotLine/wwwroot/js/spatial-live-updates.js
Normal file
@ -0,0 +1,22 @@
|
||||
/* Reuse the main window's established presence connection. Never create a connection or overwrite drafts. */
|
||||
(() => {
|
||||
if(window.PlotDirectorSpatialLiveUpdates||document.body.classList.contains('spatial-renderer-page'))return;
|
||||
const wired=new WeakSet();let pending=null,flight=false,warned=false;
|
||||
async function refresh(hint={}){
|
||||
const map=document.querySelector('#mapsApp')&&window.PlotDirectorMapWorkspace,floor=document.querySelector('[data-floor-plan-workspace]');if(!map&&!floor)return;
|
||||
const project=Number(map?.document?.map.projectID||floor?.dataset.spatialProjectId);
|
||||
if(hint.projectId&&Number(hint.projectId)!==project)return;
|
||||
if(hint.kind&&!(map?['maps','locations','spatial']:['floorplans','locations','spatial']).includes(hint.kind))return;
|
||||
pending=hint;if(flight)return;flight=true;
|
||||
try{
|
||||
let done=false;
|
||||
if(map){if(!map.dirty&&!map.busy&&!window.PlotDirectorMapAppearance?.adjusting){const response=await fetch(`/Maps/State?projectId=${project}&id=${map.document.map.mapID}`,{cache:'no-store'});if(!response.ok||response.redirected)return;const next=await response.json();if(window.PlotDirectorMapWorkspace===map&&!map.dirty&&!map.busy&&!window.PlotDirectorMapAppearance?.adjusting&&next.map.mapID===map.document.map.mapID){if(next.map.revision>map.document.map.revision)map.replaceDocument(next);done=true;}}}
|
||||
else done=await floor.refreshSpatialReference?.()===true;
|
||||
if(done){pending=null;warned=false;}else if(!warned){warned=true;window.PlotDirector?.toast?.info('Saved spatial information changed elsewhere. Your active edits remain here; finish them before refreshing.');}
|
||||
}catch{/* Persisted changes remain authoritative; normal navigation can retry. */}
|
||||
finally{flight=false;}
|
||||
}
|
||||
function wire(connection){if(!connection||wired.has(connection))return;wired.add(connection);connection.on('ContextInvalidated',hint=>void refresh(hint));}
|
||||
document.addEventListener('pd-presence-connection',e=>wire(e.detail));document.addEventListener('pd-presence-ready',()=>wire(window.PlotDirectorPresenceConnection));wire(window.PlotDirectorPresenceConnection);
|
||||
window.addEventListener('focus',()=>{if(pending)void refresh(pending);});window.PlotDirectorSpatialLiveUpdates=Object.freeze({refresh});
|
||||
})();
|
||||
Loading…
x
Reference in New Issue
Block a user