Preserve unsaved floor plan edits until their save is acknowledged

This commit is contained in:
Nick Beckley 2026-11-03 20:50:19 +00:00
parent 86509cb4db
commit 2f99a3c88a
3 changed files with 81 additions and 5 deletions

View File

@ -102,3 +102,9 @@ Deployment preflight: verified effective database name PlotDirector_Development.
Visual review found Maps could compact Restore workspace into an overflow menu. Marked Maps and Floor Plans Workspace contributions essential, matching Relationships. Strengthened maximise coverage to require a directly visible restore button, rather than merely an existing ribbon command. Initial investigation incorrectly suspected the shared essential-group reader; the existing Relationships test demonstrated that logic was already correct, so it was retained. Visual review found Maps could compact Restore workspace into an overflow menu. Marked Maps and Floor Plans Workspace contributions essential, matching Relationships. Strengthened maximise coverage to require a directly visible restore button, rather than merely an existing ribbon command. Initial investigation incorrectly suspected the shared essential-group reader; the existing Relationships test demonstrated that logic was already correct, so it was retained.
Verification: build passed; all-editor/four-theme browser/PWA maximise suite and Relationships ribbon suite passed. General toolbar, PWA cache/privacy, responsive-content and Plot Lines narrative-map regressions also passed during the broader audit. Release publish succeeded, but is superseded by this follow-up and the next Floor Plans reliability repair; nothing deployed yet. Verification: build passed; all-editor/four-theme browser/PWA maximise suite and Relationships ribbon suite passed. General toolbar, PWA cache/privacy, responsive-content and Plot Lines narrative-map regressions also passed during the broader audit. Release publish succeeded, but is superseded by this follow-up and the next Floor Plans reliability repair; nothing deployed yet.
### E — Floor Plans reliable save acknowledgement and unsaved changes
Reproduced two data-loss risks in the real editor fixture: (1) a save redirected to a login HTML page was labelled Saved; (2) an older successful request marked edits made during that request Saved before their own autosave. Require a non-redirected explicit ok:true response, reject malformed/null JSON safely, retain block state on failure, and track layout revisions so older acknowledgements cannot clear newer edits. Protect browser navigation while layout changes are dirty, saving or failed; remove that listener on workspace disposal.
Verification: both failures were reproduced by the new browser test before repair. Build passed (0 warnings/errors). Browser/PWA save tests passed for redirects, malformed/null payloads, server rejection, valid acknowledgement, preserved blocks, navigation protection and concurrent edits followed by their own autosave. All-editor resizing regression passed again. Full harness rerun in progress. Restore-visibility follow-up commit: 86509cb.

View File

@ -0,0 +1,54 @@
const {chromium}=require('playwright');
const assert=require('node:assert/strict');
(async()=>{
const browser=await chromium.launch();
try {
for(const pwa of [false,true]) {
const context=await browser.newContext({viewport:{width:1600,height:1000}});
if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message)); page.on('dialog',dialog=>dialog.accept());
for(const scenario of ['redirect','invalid','invalid-null','rejected','success']) {
await page.goto('http://127.0.0.1:5238/fixture?page=floorplans');
await page.waitForFunction(()=>document.querySelector('[data-floor-plan-initialized=true]'));
const blocks=await page.locator('[data-block]').evaluateAll(nodes=>JSON.stringify(nodes.map(node=>({...node.dataset}))));
await page.route('**/FloorPlans/SaveLayout',route=> {
if(scenario==='redirect')return route.fulfill({status:302,headers:{location:'/fixture?page=floorplans&login=true'}});
if(scenario==='invalid')return route.fulfill({json:{}});
if(scenario==='invalid-null')return route.fulfill({body:'null',contentType:'application/json'});
if(scenario==='rejected')return route.fulfill({status:400,json:{ok:false,message:'Save rejected by server'}});
return route.fulfill({json:{ok:true,message:'Saved'}});
});
await page.locator('[data-save-layout-button]').evaluate(button=>button.click());
const expected=scenario==='success'?'saved':'failed';
await page.waitForFunction(()=>document.querySelector('[data-save-status]').dataset.saveState!=='saving');
assert.equal(await page.locator('[data-save-status]').getAttribute('data-save-state'),expected,scenario+' must not acknowledge an unsuccessful save');
assert.equal(await page.locator('[data-block]').evaluateAll(nodes=>JSON.stringify(nodes.map(node=>({...node.dataset})))),blocks,'save failure preserves block state');
const guarded=await page.evaluate(()=>{const event=new Event('beforeunload',{cancelable:true});window.dispatchEvent(event);return event.defaultPrevented;});
assert.equal(guarded,scenario!=='success','Failed saves retain unsaved-navigation protection; acknowledged saves release it');
await page.unroute('**/FloorPlans/SaveLayout');
}
await page.goto('http://127.0.0.1:5238/fixture?page=floorplans');
await page.waitForFunction(()=>document.querySelector('[data-floor-plan-initialized=true]'));
await page.locator('.floor-plan-block[data-block]').first().click();
let releaseFirst;
const held = new Promise(resolve => releaseFirst = resolve);
const started = page.waitForRequest('**/FloorPlans/SaveLayout');
let requests=0;
await page.route('**/FloorPlans/SaveLayout', async route => {
if (++requests === 1) await held;
await route.fulfill({json:{ok:true,message:'Saved'}});
});
await page.locator('[data-save-layout-button]').evaluate(button=>button.click());
await started;
await page.locator('[data-block-field="x"]').first().selectOption('3');
releaseFirst();
await page.waitForFunction(()=>document.querySelector('[data-save-status]').dataset.saveState!=='saving');
assert.equal(await page.locator('[data-save-status]').getAttribute('data-save-state'),'dirty','An earlier save cannot acknowledge newer edits');
await page.waitForFunction(()=>document.querySelector('[data-save-status]').dataset.saveState==='saved');
assert.ok(requests>=2,'Newer edits receive their own save acknowledgement');
await page.unroute('**/FloorPlans/SaveLayout');
assert.deepEqual(errors,[]);await context.close();
}
console.log('PASS Floor Plans save acknowledgement, expired-session redirects, invalid JSON, server errors, retained blocks, overlapping edits and unsaved-navigation guard in browser/PWA');
}finally{await browser.close();}
})().catch(error=>{console.error(error);process.exitCode=1;});

View File

@ -1140,7 +1140,17 @@
}); });
} }
let layoutNeedsSave = false;
let layoutRevision = 0;
const protectUnsavedLayout = event => {
if (!layoutNeedsSave || !workspace.isConnected) return;
event.preventDefault();
event.returnValue = "";
};
window.addEventListener("beforeunload", protectUnsavedLayout);
function setSaveStatus(state, message) { function setSaveStatus(state, message) {
layoutNeedsSave = state !== "saved";
if (!saveStatus) return; if (!saveStatus) return;
saveStatus.dataset.saveState = state; saveStatus.dataset.saveState = state;
saveStatus.textContent = message || saveStatusText[state] || state; saveStatus.textContent = message || saveStatusText[state] || state;
@ -1362,6 +1372,7 @@
} }
function markDirty() { function markDirty() {
layoutRevision++;
setSaveStatus("dirty"); setSaveStatus("dirty");
window.clearTimeout(saveTimer); window.clearTimeout(saveTimer);
saveTimer = window.setTimeout(() => saveLayoutAsync(), 1000); saveTimer = window.setTimeout(() => saveLayoutAsync(), 1000);
@ -1509,6 +1520,7 @@
} }
saveInFlight = true; saveInFlight = true;
const savingRevision = layoutRevision;
saveButtons.forEach(button => button.disabled = true); saveButtons.forEach(button => button.disabled = true);
setSaveStatus("saving"); setSaveStatus("saving");
try { try {
@ -1521,17 +1533,20 @@
}, },
credentials: "same-origin" credentials: "same-origin"
}); });
const result = await response.json().catch(() => ({})); if (response.redirected) {
if (!response.ok || result.ok === false) { throw new Error("Your session or subscription needs attention. Open your account in another tab; your edits remain here.");
throw new Error(result.message || "Unable to save layout."); }
const result = await response.json().catch(() => null);
if (!response.ok || result?.ok !== true) {
throw new Error(result?.message || "Unable to save layout.");
} }
clearWorkspaceError(); clearWorkspaceError();
if (refreshAfterSave) { if (refreshAfterSave && layoutRevision === savingRevision) {
refreshAfterSave = false; refreshAfterSave = false;
await refreshWorkspaceAsync(workspaceState(), true); await refreshWorkspaceAsync(workspaceState(), true);
} else { } else {
setSaveStatus("saved"); setSaveStatus(layoutRevision === savingRevision ? "saved" : "dirty");
} }
} catch (error) { } catch (error) {
setSaveStatus("failed", error.message || "Save failed"); setSaveStatus("failed", error.message || "Save failed");
@ -2798,6 +2813,7 @@
workspace._resizeObserver.observe(document.querySelector(".pd-application-header") || document.body); workspace._resizeObserver.observe(document.querySelector(".pd-application-header") || document.body);
window.addEventListener("resize", sizeWorkspace); window.addEventListener("resize", sizeWorkspace);
workspace.addEventListener("floor-plan-dispose", () => { workspace.addEventListener("floor-plan-dispose", () => {
window.removeEventListener("beforeunload", protectUnsavedLayout);
surface.dispose(); surface.dispose();
workspace._resizeObserver.disconnect(); workspace._resizeObserver.disconnect();
window.removeEventListener("resize", sizeWorkspace); window.removeEventListener("resize", sizeWorkspace);