diff --git a/Docs/Maps_Stage3.md b/Docs/Maps_Stage3.md
index 41ace4bf..6bc2158c 100644
--- a/Docs/Maps_Stage3.md
+++ b/Docs/Maps_Stage3.md
@@ -6,7 +6,7 @@ Stage 3 refines the existing Stage 1 SVG workspace and Stage 2 batched Story pro
- The entire canvas suppresses browser text selection, clears accidental selection on pointer down, prevents default selection, and captures pointers. Forms/notes outside the canvas retain text selection. Cancel/lost capture restore tentative geometry, and a click without a drag preserves the redo stack.
- Free path endpoint handles turn and extend the path around the opposite endpoint using a similarity transform. Bend handles reshape its existing mild curve; the body still moves the whole object. Attached endpoints remain authoritative; no transform handle appears on an attached endpoint. Both attached paths expose only internal bend manipulation. Endpoint handles also support arrow keys. Transformations participate in undo/redo.
-- Width, height and label offsets display whole numbers while retaining persisted precision. Unchanged displayed values do not create geometry edits. Rotation uses a live -180° to +180° slider, degree input and Reset; each gesture is one undo transaction. Direct rotation of attached paths is disabled.
+- Width, height and label offsets display whole numbers while retaining persisted precision. Unchanged displayed values do not create geometry edits. Rotation uses a live -180° to +180° slider, tenth-degree input and Reset, preserving keyboard focus between adjustments; each gesture is one undo transaction. Direct rotation of attached paths is disabled.
- All 75 built-in assets have distinct, coherent inline SVG pictograms/swatches. Marker rendering reuses the same vocabulary. Asset labels remain visible; icons use outlines, structure and line patterns, not colour alone. No raster assets or style packs.
- The shared ribbon catalogue now includes Undo, Redo, Previous, Next, Restore workspace, Separate window, Lock and Unlock. Map action commands use existing Writer/Copy/Remove icons. Selectors and mode tabs remain ordinary text controls.
- Maps' competing context-menu listener, DOM and CSS are removed. An opt-in provider contributes to the canonical `application-context-menu.js` menu in web and PWA modes. Right-click selects an unselected item, preserves a useful multi-selection, and offers appropriate inspection/navigation/edit commands. Locked, background, path and multi-selection commands are bounded to their valid operations. The Map menu button supplies a touch/keyboard equivalent; Shift+F10 and ContextMenu also work. Ctrl+right-click remains the existing native-menu escape hatch.
@@ -18,7 +18,7 @@ Stage 3 refines the existing Stage 1 SVG workspace and Stage 2 batched Story pro
One pending action retains the first destination. The unsaved modal offers Save and continue, Discard changes and Keep editing. Successful explicit save precedes continuation. A failed save keeps the modal, error, edits and current map. Discard restores the last saved document before performing the action. Keep editing, X and Escape leave the document, viewport, selection and editing state intact and restore focus. Escape is contained within the modal so it cannot also clear canvas selection. Rapid navigation cannot stack dialogs or replace the first action.
-The guard covers map selection, hierarchy and other same-origin in-application links, new/detailed maps, duplication, Floor Plans and transitions to Story. Explore retains edits and can explicitly save through the navigation modal. Modified/new-window links leave the current workspace intact. True unload still uses the minimal standards `beforeunload` guard; browsers own refresh/tab-close confirmation. Browser Back/Forward that actually unloads the page is covered there, without claiming asynchronous UI can intercept every browser navigation.
+The guard covers map selection, hierarchy and other same-origin in-application links and navigation forms (including Logout), new/detailed maps, duplication, Floor Plans and transitions to Story. Explore retains edits and can explicitly save through the navigation modal. Modified/new-window links leave the current workspace intact. True unload still uses the minimal standards `beforeunload` guard; browsers own refresh/tab-close confirmation. Browser Back/Forward that actually unloads the page is covered there, without claiming asynchronous UI can intercept every browser navigation.
## Shared workspace surface
@@ -27,7 +27,7 @@ The guard covers map selection, hierarchy and other same-origin in-application l
## Story navigation and readability
- All three ordinary character pickers sort case-insensitively A–Z, with ID as tie-breaker. Importance ordering of projection data remains intact for intentional automatic Time defaults.
-- Scene mode adds a compact, keyboard-operable range scrubber over the canvas. It uses the same filtered canonical/scenario sequence as Previous/Next. It retains no-Location, unmapped and other/child-map positions; it creates no pretend markers. Picker, scrubber and Previous/Next share `sceneID`. Range work is throttled to animation frames and committed on change. `aria-valuetext` and visible context give sequence, chapter, Location and mapping state. No animated camera movement is introduced.
+- Scene mode adds a compact, keyboard-operable range scrubber over the canvas. It uses the same filtered canonical/scenario sequence as Previous/Next. It retains no-Location, unmapped and other/child-map positions; it creates no pretend markers. Picker, scrubber and Previous/Next share `sceneID`; navigation beyond a lookup search clears that search so the selected scene remains visible. Range work is throttled to animation frames and committed on change. `aria-valuetext` and visible context give sequence, chapter, Location and mapping state. No animated camera movement is introduced. Explicit geography saves invalidate cached Story projections; concurrent initial reads are coalesced.
- Coverage totals remain honest. Sparse scope copy explains that Story can place only Locations represented on this map. The restrained Inspect unmapped Locations action opens the existing gaps Details, whose existing explicit Create action places nothing automatically.
- Full numbered character journeys and revisits remain accessible. Stops use compact wrapped controls with explicit status; Details retains independent scroll. Stage 2 already groups coincident visits by character/feature and repeated movements by connection. Testing 500 scenes / 30 characters / 5,000 appearances did not justify an additional clustering model. All underlying stops and legs remain inspectable.
@@ -48,7 +48,7 @@ Automated gates and dedicated browser scripts:
- `dotnet build PlotLine.slnx` (zero warnings/errors); executable regression harness, including a detached denied-access assertion.
- `maps-engine.cjs`: geometry/arrangement plus endpoint transforms, attached authority and all 75 distinct symbols.
- `maps-workspace.cjs`: Stage 1 workflows in web/PWA, with explicit save before Story transition.
-- `maps-story-engine.cjs`, `maps-story.cjs`: unchanged Stage 2 evidence/lenses and 500-scene / 30-character / 5,000-appearance scale. Fifty scene changes measured approximately 0.5–0.7 seconds in the initial Stage 3 run; no per-scene reads or geography writes.
+- `maps-story-engine.cjs`, `maps-story.cjs`: unchanged Stage 2 evidence/lenses and 500-scene / 30-character / 5,000-appearance scale. Fifty scene changes measured approximately 0.5–0.9 seconds in the initial Stage 3 run; no per-scene reads or geography writes.
- `maps-stage3.cjs`: web/PWA unsaved Keep/Discard/Save/failure/original destination/Escape/X/repeat/unload; repeated area and every path-type manipulation; endpoint/rotation undo; rounded precision; canonical menus/multi-selection/locks; maximise; A–Z pickers; canonical scrubber states and narrow-screen usability.
- `maps-detached.cjs`: web/PWA popup, scene/character/lens sync and canonical Scene event, scoped envelopes, retained dirty peer edits, revision conflict and closed-opener fallback.
- Existing Relationships ribbon and focus-stability suites (web/PWA at 1440/1700/1920), plus the canonical context-menu suite under Xvfb (all six themes, keyboard, clipboard and native-menu escape hatch).
diff --git a/PlotLine.Tests/Browser/maps-stage3-dev-smoke.cjs b/PlotLine.Tests/Browser/maps-stage3-dev-smoke.cjs
index 31ee4026..ca6f1456 100644
--- a/PlotLine.Tests/Browser/maps-stage3-dev-smoke.cjs
+++ b/PlotLine.Tests/Browser/maps-stage3-dev-smoke.cjs
@@ -19,6 +19,7 @@ if(identity.Database!=='PlotDirector_Development'||!identity.Email.startsWith('p
// Protect all overlapping fixture shapes through the canonical multi-selection menu.
await page.evaluate(ids=>{const w=window.PlotDirectorMapWorkspace;ids.forEach((id,i)=>w.select(id,i>0));},added);await command('mapsContext');assert.equal(await page.locator('.pd-context-popup').count(),1);await page.getByRole('menuitem',{name:'Lock position',exact:true}).click();await canvas.click({position:{x:330,y:280},button:'right'});assert.equal(await page.locator('.pd-context-popup').count(),1);await page.locator('.pd-context-popup').hover();await page.keyboard.press('Escape');
await page.mouse.move((await canvas.boundingBox()).x+330,(await canvas.boundingBox()).y+280);await page.mouse.down();await page.mouse.move((await canvas.boundingBox()).x+380,(await canvas.boundingBox()).y+310,{steps:6});await page.mouse.up();assert.notDeepEqual(await page.evaluate(()=>({...window.PlotDirectorMapWorkspace.view})),view);
+ await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),added[2]);const pieceCount=await page.evaluate(()=>window.PlotDirectorMapWorkspace.document.features.length);await command('mapsContext');await page.getByRole('menuitem',{name:'Duplicate',exact:true}).click();assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.document.features.length),pieceCount+1);await command('mapsContext');await page.getByRole('menuitem',{name:'Delete',exact:true}).click();assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.document.features.length),pieceCount);await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),added[2]);await command('mapsContext');await page.getByRole('menuitem',{name:'Add relationship',exact:true}).click();const relation=page.locator('dialog[open]');await relation.locator('[name=targetID]').selectOption(added[1]);await relation.getByRole('button',{name:'Keep relationship',exact:true}).click();
const state=await page.evaluate(()=>({view:{...window.PlotDirectorMapWorkspace.view},selection:window.PlotDirectorMapWorkspace.selected}));if(!pwa){await command('mapsMaximise');await command('mapsMaximise');assert.deepEqual(await page.evaluate(()=>({view:{...window.PlotDirectorMapWorkspace.view},selection:window.PlotDirectorMapWorkspace.selected})),state);}else assert(await page.locator('#mapsMaximise').isHidden());
// Keep, X and Escape leave exact edits/view/selection; Save continues only after the real POST succeeds.
await command('mapsNew');const modal=page.locator('#pdApplicationDialog');await modal.getByRole('button',{name:'Keep editing',exact:true}).click();assert(await page.evaluate(()=>window.PlotDirectorMapWorkspace.dirty));await command('mapsNew');await page.keyboard.press('Escape');await modal.waitFor({state:'detached'});await command('mapsNew');await modal.locator('.btn-close').click();await modal.waitFor({state:'detached'});
diff --git a/PlotLine.Tests/Browser/maps-stage3.cjs b/PlotLine.Tests/Browser/maps-stage3.cjs
index 7ca98d7b..01e0d3b4 100644
--- a/PlotLine.Tests/Browser/maps-stage3.cjs
+++ b/PlotLine.Tests/Browser/maps-stage3.cjs
@@ -4,9 +4,9 @@ const base=process.env.PD_MAPS_STAGE3_URL||'http://127.0.0.1:5251';
for(const pwa of [false,true]){
const context=await browser.newContext({viewport:{width:1800,height:1100}});if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
const page=await context.newPage(),errors=[],dialogs=[];page.on('pageerror',e=>errors.push(e.message));page.on('dialog',async d=>{dialogs.push(d.type());await d.dismiss();});
- let saveFails=false,saves=0;const fixture=await(await context.request.get(base+'/map-story-fixture')).json();fixture.characters.reverse();
- await context.route('**/Maps/Story?**',r=>r.fulfill({json:fixture}));
- await context.route('**/Maps/Save',r=>{saves++;const doc=r.request().postDataJSON();doc.map.revision++;return r.fulfill(saveFails?{status:409,json:{message:'Another window saved this map. Your edits remain here.'}}:{json:doc});});
+ let saveFails=false,saves=0,reads=0;const fixture=await(await context.request.get(base+'/map-story-fixture')).json();fixture.characters.reverse();
+ await context.route('**/Maps/Story?**',r=>{reads++;return r.fulfill({json:fixture});});
+ await context.route('**/Maps/Save',r=>{saves++;const doc=r.request().postDataJSON();doc.map.revision++;if(saveFails==='invalid')return r.fulfill({json:{unexpected:true}});return r.fulfill(saveFails?{status:409,json:{message:'Another window saved this map. Your edits remain here.'}}:{json:doc});});
await context.route('**/stage3-destination-*',r=>r.fulfill({contentType:'text/html',body:'
Destination
'}));
async function open(){await page.goto(base+'/fixture?page=maps&story=true');await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);}
let editNumber=0;async function dirty(){await page.evaluate(()=>{const w=window.PlotDirectorMapWorkspace;w.setMode('create');w.select(w.document.features[0].featureID);});await page.locator('[data-field=name]').fill('Unsaved name '+(++editNumber));await page.locator('[data-field=name]').blur();assert(await page.evaluate(()=>window.PlotDirectorMapWorkspace.dirty));}
@@ -20,9 +20,11 @@ const base=process.env.PD_MAPS_STAGE3_URL||'http://127.0.0.1:5251';
console.log('Kept ready');assert.deepEqual(await page.evaluate(()=>window.__continued),[]);assert.deepEqual(await page.evaluate(()=>({doc:JSON.stringify(window.PlotDirectorMapWorkspace.document),view:{...window.PlotDirectorMapWorkspace.view},selection:window.PlotDirectorMapWorkspace.selected})),preserved);
for(const close of ['Escape','X']){await page.evaluate(()=>{void window.PlotDirectorMapWorkspace.requestLeave(()=>window.__continued.push('wrong'));});await modal.waitFor();if(close==='Escape')await page.keyboard.press('Escape');else await modal.locator('.btn-close').click();await modal.waitFor({state:'detached'});assert.deepEqual(await page.evaluate(()=>window.__continued),[]);assert.deepEqual(await page.evaluate(()=>window.PlotDirectorMapWorkspace.selected),preserved.selection);}
console.log('Save failure test');await page.evaluate(()=>window.PlotDirectorMapWorkspace.setMode('explore'));saveFails=true;await page.evaluate(()=>{void window.PlotDirectorMapWorkspace.requestLeave(()=>window.__continued.push('saved'));});await modal.getByRole('button',{name:'Save and continue',exact:true}).click();await modal.locator('[data-dialog-error]').waitFor();assert.match(await page.locator('#mapsStatus').innerText(),/Another window/);assert(await page.evaluate(()=>window.PlotDirectorMapWorkspace.dirty));assert.deepEqual(await page.evaluate(()=>window.__continued),[]);
- saveFails=false;await modal.getByRole('button',{name:'Save and continue',exact:true}).click();await modal.waitFor({state:'detached'});assert.deepEqual(await page.evaluate(()=>window.__continued),['saved']);assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.dirty),false);assert.equal(saves,2);
+ saveFails='invalid';await modal.getByRole('button',{name:'Save and continue',exact:true}).click();await page.waitForFunction(()=>document.getElementById('mapsStatus').textContent.includes('could not be verified'));assert(await page.evaluate(()=>window.PlotDirectorMapWorkspace.dirty));assert.deepEqual(await page.evaluate(()=>window.__continued),[]);
+ saveFails=false;await modal.getByRole('button',{name:'Save and continue',exact:true}).click();await modal.waitFor({state:'detached'});assert.deepEqual(await page.evaluate(()=>window.__continued),['saved']);assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.dirty),false);assert.equal(saves,3);
await dirty();await page.evaluate(()=>{window.PlotDirectorMapWorkspace.requestLeave(()=>window.__continued.push('discarded'));});await modal.getByRole('button',{name:'Discard changes',exact:true}).click();await modal.waitFor({state:'detached'});assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.dirty),false);assert.deepEqual(await page.evaluate(()=>window.__continued),['saved','discarded']);
console.log('Destination test');await dirty();await page.evaluate(()=>{for(const n of [1,2]){const a=document.createElement('a');a.href='/stage3-destination-'+n;a.id='destination'+n;document.body.append(a);}document.getElementById('destination1').click();document.getElementById('destination2').click();});await modal.getByRole('button',{name:'Discard changes',exact:true}).click();await page.waitForURL('**/stage3-destination-1');
+ await open();await dirty();await page.evaluate(()=>{const form=document.createElement('form');form.action='/stage3-destination-form';form.innerHTML='';document.body.append(form);form.requestSubmit();});await modal.getByRole('button',{name:'Discard changes',exact:true}).click();await page.waitForURL(/stage3-destination-form/);assert.equal(new URL(page.url()).searchParams.get('retained'),'42');
console.log('Unload test');await open();await dirty();await page.locator('#mapsCanvas').click({position:{x:20,y:150}});await page.reload({waitUntil:'domcontentloaded'}).catch(()=>{});assert.deepEqual(dialogs,['beforeunload'],'only genuine unload invokes browser dialog');
// Discard the retained edits deliberately, then test manipulation without native dialogs.
await page.evaluate(()=>{void window.PlotDirectorMapWorkspace.requestLeave(()=>{});});await modal.getByRole('button',{name:'Discard changes',exact:true}).click();await modal.waitFor({state:'detached'});
@@ -36,16 +38,17 @@ const base=process.env.PD_MAPS_STAGE3_URL||'http://127.0.0.1:5251';
for(const type of ['Land Mass','Forest','Railway','River','Canal','Stream','Trail','Track','Sea route','Wall','Mountain ridge','Major road']){await place(type);await page.locator('[data-action=shape]').click();for(let i=0;i<2;i++)await dragHandle('[data-handle=point]',i?8:-8,7);assert.equal(await page.evaluate(()=>getSelection().toString()),'');}
const island=await place('Island');await page.evaluate(id=>{const w=window.PlotDirectorMapWorkspace,f=w.document.features.find(f=>f.featureID===id);f.width=1226.985091801661;w.refreshDetails();},island);assert.equal(await page.locator('[data-field=width]').inputValue(),'1227');await page.locator('[data-field=width]').focus();await page.locator('[data-field=width]').blur();assert.equal(await page.evaluate(id=>window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id).width,island),1226.985091801661);
const rotate=page.locator('input[type=range][data-rotate]');await rotate.fill('45');await rotate.dispatchEvent('input');await rotate.dispatchEvent('change');assert.equal(await page.evaluate(id=>window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id).rotation,island),45);await command('mapsUndo');assert.equal(await page.evaluate(id=>window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id).rotation,island),0);await command('mapsRedo');
- await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),island);await page.locator('[data-action=shape]').click();for(let i=0;i<5;i++)await dragHandle('[data-handle=point]',8,i%2?10:-10);assert.equal(await page.evaluate(()=>getSelection().toString()),'');
+ await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),island);await page.locator('input[type=range][data-rotate]').focus();await page.keyboard.press('ArrowRight');assert.equal(await page.evaluate(()=>document.activeElement?.getAttribute('data-rotate')),'');await page.keyboard.press('ArrowRight');assert.equal(await page.evaluate(id=>window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id).rotation,island),47);await page.locator('[data-action=shape]').click();for(let i=0;i<5;i++)await dragHandle('[data-handle=point]',8,i%2?10:-10);assert.equal(await page.evaluate(()=>getSelection().toString()),'');
await page.evaluate(ids=>{const w=window.PlotDirectorMapWorkspace;w.select(ids[0]);w.select(ids[1],true);},ids);const object=page.locator(`[data-feature-id="${ids[0]}"]`);await object.dispatchEvent('contextmenu',{button:2,clientX:600,clientY:350});assert.equal(await page.locator('.pd-context-popup').count(),1);assert.equal(await page.locator('.maps-context-menu').count(),0);assert.equal((await page.evaluate(()=>window.PlotDirectorMapWorkspace.selected)).length,2);await page.locator('.pd-context-popup').hover();await page.getByRole('menuitem',{name:'Lock position',exact:true}).click();assert(await page.evaluate(ids=>ids.every(id=>window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id).isLocked),ids));
await page.evaluate(()=>{const w=window.PlotDirectorMapWorkspace;w.document.features.forEach((f,i)=>w.select(f.featureID,i>0));});await command('mapsContext');await page.getByRole('menuitem',{name:'Lock position',exact:true}).click();
const view=await page.evaluate(()=>({...window.PlotDirectorMapWorkspace.view})),center=await page.evaluate(id=>{const f=window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id),p=new DOMPoint(f.x,f.y).matrixTransform(document.getElementById('mapsCanvas').getScreenCTM());return {x:p.x,y:p.y};},island);await page.mouse.move(center.x,center.y);await page.mouse.down();await page.mouse.move(center.x+65,center.y+40,{steps:8});await page.mouse.up();assert.notDeepEqual(await page.evaluate(()=>({...window.PlotDirectorMapWorkspace.view})),view);
const maxState=await page.evaluate(()=>({view:{...window.PlotDirectorMapWorkspace.view},selected:window.PlotDirectorMapWorkspace.selected}));if(pwa)assert(await page.locator('#mapsMaximise').isHidden());else{await command('mapsMaximise');await command('mapsMaximise');assert.deepEqual(await page.evaluate(()=>({view:{...window.PlotDirectorMapWorkspace.view},selected:window.PlotDirectorMapWorkspace.selected})),maxState);}
// Story transition is explicitly resolved; scene controls all share canonical state.
await page.evaluate(()=>window.PlotDirectorMapWorkspace.setMode('story'));await modal.getByRole('button',{name:'Discard changes',exact:true}).click();await page.waitForFunction(()=>!!window.PlotDirectorStoryOverlay?.data);await page.evaluate(()=>{const n=document.getElementById('mapStoryLens');n.value='scene';n.dispatchEvent(new Event('change',{bubbles:true}));});
- const scrubber=page.locator('#mapStoryScrubber');for(const index of [0,3,4,5]){await scrubber.fill(String(index));await scrubber.dispatchEvent('input');await scrubber.dispatchEvent('change');assert.equal(await page.evaluate(()=>window.PlotDirectorStoryOverlay.state.sceneID),fixture.scenes[index].sceneID);assert.match(await scrubber.getAttribute('aria-valuetext'),new RegExp(fixture.scenes[index].position.status));}
+ const scrubber=page.locator('#mapStoryScrubber');await page.evaluate(()=>{const search=document.getElementById('mapStorySceneSearch');search.value='Harbour';search.dispatchEvent(new Event('input',{bubbles:true}));});await scrubber.fill('5');await scrubber.dispatchEvent('change');assert.equal(await page.locator('#mapStoryScene').inputValue(),String(fixture.scenes[5].sceneID),'Scrubbing outside search results must still show the selected scene');for(const index of [0,3,4,5]){await scrubber.fill(String(index));await scrubber.dispatchEvent('input');await scrubber.dispatchEvent('change');assert.equal(await page.evaluate(()=>window.PlotDirectorStoryOverlay.state.sceneID),fixture.scenes[index].sceneID);assert.match(await scrubber.getAttribute('aria-valuetext'),new RegExp(fixture.scenes[index].position.status));}
await command('mapStoryPrevious');assert.equal(await scrubber.inputValue(),'4');await command('mapStoryNext');assert.equal(await scrubber.inputValue(),'5');assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.dirty),false);
const names=await page.locator('#mapStoryCharacter1 option').allTextContents();assert.deepEqual(names.slice(1),names.slice(1).sort((a,b)=>a.localeCompare(b,undefined,{sensitivity:'base'})));
+ const beforeReads=reads;await dirty();assert(await page.evaluate(()=>window.PlotDirectorMapWorkspace.save()));await page.evaluate(()=>window.PlotDirectorMapWorkspace.setMode('story'));await page.waitForFunction(()=>!!window.PlotDirectorStoryOverlay.data);assert.equal(reads,beforeReads+1,'An explicit geography save invalidates the cached Story projection');
await page.setViewportSize({width:430,height:900});assert(await scrubber.isVisible());assert((await scrubber.boundingBox()).width>100);assert(await page.locator('#mapsCanvas').isVisible());
assert.deepEqual(errors,[]);console.log(`PASS Maps Stage 3 ${pwa?'PWA':'web'}: unsaved actions/failure/destination/Escape/X/repeat/unload, path/rotation undo, precision, text selection, canonical context/multiselect/locks, maximise, canonical scrubber`);await context.close();
}
diff --git a/PlotLine/wwwroot/js/application-dialogs.js b/PlotLine/wwwroot/js/application-dialogs.js
index bab24a51..0da4d80c 100644
--- a/PlotLine/wwwroot/js/application-dialogs.js
+++ b/PlotLine/wwwroot/js/application-dialogs.js
@@ -10,6 +10,7 @@
node.addEventListener('keydown',e=>{if(e.key==='Escape'){e.preventDefault();e.stopImmediatePropagation();if(!working)modal.hide();}},true);
pending=new Promise(resolve=>{node.addEventListener('hidden.bs.modal',()=>{modal.dispose();node.remove();pending=null;if(previousFocus?.isConnected)previousFocus.focus({preventScroll:true});resolve(result);},{once:true});});
for(const action of options.actions){const b=document.createElement('button');b.type='button';b.className='btn '+(action.className||'btn-outline-secondary');b.textContent=action.label;b.dataset.dialogAction=action.value;b.onclick=async()=>{if(working)return;working=true;node.querySelectorAll('button').forEach(n=>n.disabled=true);try{if(action.run&&!(await action.run(node.querySelector('[data-dialog-input]').value))){node.querySelector('[data-dialog-error]').textContent=options.failureMessage||'The changes could not be saved. Keep editing or try again.';node.querySelector('[data-dialog-error]').hidden=false;return;}result={value:action.value,input:node.querySelector('[data-dialog-input]').value};modal.hide();}catch(error){node.querySelector('[data-dialog-error]').textContent=error.message||'The action could not be completed. Please try again.';node.querySelector('[data-dialog-error]').hidden=false;}finally{working=false;node.querySelectorAll('button').forEach(n=>n.disabled=false);}};node.querySelector('[data-dialog-actions]').append(b);}
+ node.querySelector('[data-dialog-input]').addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();node.querySelector('[data-dialog-actions] button')?.click();}});
node.addEventListener('hide.bs.modal',e=>{if(working&&result===null)e.preventDefault();});node.addEventListener('shown.bs.modal',()=>{(options.input?node.querySelector('[data-dialog-input]'):node.querySelector('[data-dialog-actions] button:last-child'))?.focus();});modal.show();return pending;
}};
})();
diff --git a/PlotLine/wwwroot/js/maps-story.js b/PlotLine/wwwroot/js/maps-story.js
index 246ffc91..2f1292aa 100644
--- a/PlotLine/wwwroot/js/maps-story.js
+++ b/PlotLine/wwwroot/js/maps-story.js
@@ -7,6 +7,7 @@
const option=(id,label)=>``;
const ids=['mapStoryLens','mapStoryBook','mapStoryScenario','mapStoryScene','mapStoryChapter','mapStoryTime','mapStoryMapping','mapStoryPlanning',...Array.from({length:3},(_,i)=>'mapStoryCharacter'+(i+1)),...Array.from({length:3},(_,i)=>'mapStoryPlot'+(i+1))];
const state={lens:'overview',scenarioID:Number(new URLSearchParams(location.search).get('scenarioId'))||0,bookID:0,chapterID:0,sceneID:0,characterIDs:[],plotIDs:[],mapping:'all',planning:'all',at:'',visible:true,selection:{kind:'overview'}};
+ let loadRequest=null;
let data=null,scenes=new Map(),people=new Map(),requestVersion=0,loading=false,error='',internalSelect=false,restored=false,initialContextApplied=false;
const overlayNodes=new Map(),colors=['#265e83','#7c4f83','#936027'],styles=['8 5','2 5','12 4 2 4'];
const active=()=>W.mode==='story';
@@ -36,7 +37,8 @@
$('mapStoryChapter').innerHTML=option(0,'All chapters')+chapters.map(([id,label])=>option(id,label)).join('');if(state.chapterID&&!chapters.some(([id])=>id===state.chapterID))state.chapterID=0;$('mapStoryChapter').value=String(state.chapterID);
const times=E.timeEvents(data,state.bookID);$('mapStoryTime').innerHTML=times.map(s=>option(s.startDateTime,`${dateLabel(s)} · ${s.sceneTitle}`)).join('');if(!times.some(s=>s.startDateTime===state.at))state.at=times[0]?.startDateTime||'';$('mapStoryTime').value=state.at;
}
- async function load(force=false){
+ function load(force=false){if(loadRequest&&!force)return loadRequest;const request=loadCore(force);loadRequest=request;request.finally(()=>{if(loadRequest===request)loadRequest=null;});return request;}
+ async function loadCore(force=false){
if(!W.document)return;
if(W.dirty){error='Save or undo geography changes in Create before loading Story. Story navigation never saves your map.';data=null;refresh();return;}
if(data&&!force){refresh();return;}
@@ -136,7 +138,7 @@
if(!html)html=overviewDetails(selected);
const pane=$('mapsDetails'),scroll=pane.scrollTop;$('mapsDetailContent').innerHTML=`
${html}
`;pane.scrollTop=scroll;return true;
}
- function chooseScene(id,characterID=0){const s=scenes.get(id);if(!s)return;state.sceneID=id;state.selection={kind:'scene',sceneID:id,characterID};$('mapStoryScene').value=String(id);const stop=characterID?data.stops.find(x=>x.characterID===characterID&&x.sceneID===id):null,p=stop?.position||s.position;internalSelect=true;if(p.featureID){W.select(p.featureID);W.focus(p.featureID);}else W.clearSelection();internalSelect=false;refresh();}
+ function chooseScene(id,characterID=0){const s=scenes.get(id);if(!s)return;state.sceneID=id;state.selection={kind:'scene',sceneID:id,characterID};if(![...$('mapStoryScene').options].some(o=>Number(o.value)===id)){$('mapStorySceneSearch').value='';scopeOptions();}$('mapStoryScene').value=String(id);const stop=characterID?data.stops.find(x=>x.characterID===characterID&&x.sceneID===id):null,p=stop?.position||s.position;internalSelect=true;if(p.featureID){W.select(p.featureID);W.focus(p.featureID);}else W.clearSelection();internalSelect=false;refresh();}
function navigateStep(direction){if(!data)return;const sequence=state.lens==='time'?E.timeEvents(data,state.bookID):visibleScenes(),index=state.lens==='time'?sequence.findIndex(s=>s.startDateTime===state.at):sequence.findIndex(s=>s.sceneID===state.sceneID),next=sequence[index+direction];if(!next)return;if(state.lens==='time'){state.at=next.startDateTime;$('mapStoryTime').value=state.at;state.selection={kind:'overview'};refresh();}else chooseScene(next.sceneID);}
svg.addEventListener('pointerdown',e=>{if(active()&&e.target.closest('[data-feature-id]')&&!internalSelect)state.selection={kind:'feature'};},true);
document.addEventListener('click',e=>{if(active()&&e.target.closest('[data-search-feature]'))state.selection={kind:'feature'};},true);
@@ -174,6 +176,7 @@
$('mapStoryScrubber').addEventListener('change',e=>{scrubValue=Number(e.target.value);if(scrubFrame)cancelAnimationFrame(scrubFrame);scrub();});
$('mapStoryCoverage').onclick=()=>{state.selection={kind:'gaps'};renderDetails();};
$('mapStoryPrevious').onclick=()=>navigateStep(-1);$('mapStoryNext').onclick=()=>navigateStep(1);$('mapStoryLayer').onclick=()=>{state.visible=!state.visible;refresh();};$('mapStoryGaps').onclick=()=>{state.selection={kind:'gaps'};renderDetails();document.querySelector('#mapsStoryToolbar details').open=false;};$('mapStoryObservations').onclick=()=>{state.selection={kind:'observations'};renderDetails();document.querySelector('#mapsStoryToolbar details').open=false;};$('mapStoryRefresh').onclick=()=>load(true);
+ window.addEventListener('pd-map-saved',()=>{requestVersion++;loadRequest=null;data=null;loading=false;error='';});
window.addEventListener('pd-map-mode',e=>{controls();if(e.detail==='story')load();else refresh();});
window.addEventListener('pageshow',e=>{if(e.persisted&&active())load(true);});
window.PlotDirectorStoryOverlay={redraw,details:renderDetails,floorPlanURL,get data(){return data;},get state(){return state;},refresh:()=>load(true),chooseScene};
diff --git a/PlotLine/wwwroot/js/maps-workspace.js b/PlotLine/wwwroot/js/maps-workspace.js
index 4a8c5da1..fc1c95d8 100644
--- a/PlotLine/wwwroot/js/maps-workspace.js
+++ b/PlotLine/wwwroot/js/maps-workspace.js
@@ -27,8 +27,9 @@
busy=true;updateButtons();const sent=snapshot();status('Saving…');
try{
const saved=await request('Save',JSON.parse(sent),true);
+ if(saved?.map?.mapID!==doc.map.mapID||saved.map.projectID!==boot.projectId||!Number.isSafeInteger(saved.map.revision)||!Array.isArray(saved.features)||!Array.isArray(saved.relationships))throw new Error('The saved map could not be verified. Your edits remain here. Please try again.');
// Editing is disabled while saving; server-created Location links become canonical before further edits.
- doc=saved;savedDocument=clone(saved);dirty=false;window.PlotDirectorWorkspaceBridge?.send('map-saved',{mapID:saved.map.mapID,revision:saved.map.revision});
+ doc=saved;savedDocument=clone(saved);dirty=false;window.dispatchEvent(new CustomEvent('pd-map-saved'));window.PlotDirectorWorkspaceBridge?.send('map-saved',{mapID:saved.map.mapID,revision:saved.map.revision});
const reconcile=entry=>{const prior=JSON.parse(entry);prior.map.revision=saved.map.revision;for(const f of prior.features){const canonical=saved.features.find(x=>x.featureID===f.featureID);if(canonical?.locationID&&f.createLocation){f.locationID=canonical.locationID;f.createLocation=false;}}return JSON.stringify(prior);};
history=history.map(reconcile);future=future.map(reconcile);boot.document=doc;
const known=boot.maps.find(m=>m.mapID===doc.map.mapID);if(known)Object.assign(known,doc.map);
@@ -60,6 +61,13 @@
const destination=new URL(link.href,location.href);if(destination.origin!==location.origin||!/^https?:$/.test(destination.protocol)||link.getAttribute('href').startsWith('#'))return;
if(!dirty){announceNavigation(destination.href);return;}e.preventDefault();e.stopImmediatePropagation();requestLeave(()=>{announceNavigation(destination.href);location.href=destination.href;});
},true);
+ let continuingForm=null;
+ document.addEventListener('submit',e=>{
+ const form=e.target;if(!dirty||e.defaultPrevented||form===continuingForm||form.closest('#mapsApp')||form.matches('[data-appearance-form]')||!form.hasAttribute('action')||(form.target&&form.target!=='_self'))return;
+ const destination=new URL(e.submitter?.hasAttribute('formaction')?e.submitter.formAction:form.action,location.href);if(destination.origin!==location.origin)return;
+ e.preventDefault();e.stopImmediatePropagation();const submitter=e.submitter;
+ requestLeave(()=>{continuingForm=form;try{form.requestSubmit(submitter?.isConnected?submitter:undefined);}finally{continuingForm=null;}});
+ },true);
function svgNode(tag,attrs={}){const node=document.createElementNS(ns,tag);for(const[k,v]of Object.entries(attrs))node.setAttribute(k,v);return node;}
function applyView(){svg.setAttribute('viewBox',`${view.x} ${view.y} ${view.w} ${view.h}`);$('mapsZoom').textContent=Math.round(1200/view.w*100)+'%';render();}
function world(event){const p=new DOMPoint(event.clientX,event.clientY).matrixTransform(svg.getScreenCTM().inverse());return [p.x,p.y];}
@@ -149,7 +157,7 @@
if(linked)html+=`Open ${esc(linked.locationName)}`;
html+='';
if(f.geometryClass!=='Marker'){
- html+=`Shape${field('Width','width',f.width,'number','min="10" max="10000"')}${field('Height','height',f.height,'number','min="10" max="10000"')}`;
+ html+=`Shape${field('Width','width',f.width,'number','min="10" max="10000"')}${field('Height','height',f.height,'number','min="10" max="10000"')}`;
if(['Land Mass','Island'].includes(f.type))html+=``;
html+=`
${f.geometryClass==='Path'?'Drag a free endpoint to turn and extend; edit bends to reshape. Attached endpoints stay connected.':'Drag the corner to resize, or edit a few shape points.'}
`;
}
@@ -286,7 +294,7 @@
if(selected.size&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){e.preventDefault();const step=e.shiftKey?20:5;safeEdit(()=>doc.features.filter(f=>selected.has(f.featureID)&&!f.isLocked).forEach(f=>{f.x+=(e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0);f.y+=(e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0);}));}
});
function rotate(value,commit=false){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||f.isLocked||busy||mode!=='create'||f.startFeatureID||f.endFeatureID)return;if(!Number.isFinite(value))return;
- if(!rotationEdit&&f.rotation===E.normalAngle(value))return;if(!rotationEdit){checkpoint();rotationEdit=f.featureID;}f.rotation=E.normalAngle(value);changed();render();document.querySelectorAll('[data-rotate]').forEach(n=>n.value=String(Math.round(f.rotation)));if(commit){rotationEdit=null;details();}}
+ if(!rotationEdit&&f.rotation===E.normalAngle(value))return;if(!rotationEdit){checkpoint();rotationEdit=f.featureID;}f.rotation=E.normalAngle(value);changed();render();document.querySelectorAll('[data-rotate]').forEach(n=>n.value=String(n.type==='range'?Math.round(f.rotation):Math.round(f.rotation*10)/10));if(commit){const active=document.activeElement,focus=active?.matches('[data-rotate]')?'input[data-rotate][type="'+active.type+'"]':active?.matches('[data-reset-rotation]')?'[data-reset-rotation]':null;rotationEdit=null;details();if(focus)document.querySelector(focus)?.focus({preventScroll:true});}}
document.addEventListener('input',e=>{if(e.target.matches('[data-rotate]'))rotate(Number(e.target.value));});
document.addEventListener('change',e=>{if(e.target.matches('[data-rotate]'))rotate(Number(e.target.value),true);});
document.addEventListener('click',e=>{if(e.target.closest('[data-reset-rotation]'))rotate(0,true);});
diff --git a/PlotLine/wwwroot/js/workspace-bridge.js b/PlotLine/wwwroot/js/workspace-bridge.js
index 97e4b8d4..f95669ab 100644
--- a/PlotLine/wwwroot/js/workspace-bridge.js
+++ b/PlotLine/wwwroot/js/workspace-bridge.js
@@ -8,7 +8,7 @@
const sender=crypto.randomUUID(),seen=new Map(),pendingOpen=new Map();
const allowed=new Set(['hello','ready','story-state','scene-selected','open-scene','scene-opened','map-saved','map-navigation']);
let channel=null,paused=0,token='',sequence=0,mainAvailable=false,detachedWindow=null;
- function send(type,payload={}){if(channel&&!paused&&allowed.has(type))channel.postMessage({uid,projectID,sender,sequence:++sequence,type,payload});}
+ function send(type,payload={}){if(channel&&(!paused||type!=='story-state')&&allowed.has(type))channel.postMessage({uid,projectID,sender,sequence:++sequence,type,payload});}
function state(){const w=window.PlotDirectorMapWorkspace,s=window.PlotDirectorStoryOverlay?.state;return s?{...s,selection:undefined,mapID:w?.document?.map.mapID}:{};}
function connect(value){
if(!positive(uid)||!positive(projectID)||!validToken(value))return;