Refine Maps editing, Story navigation and paired workspaces
This commit is contained in:
parent
448f35b583
commit
78e80569dd
57
Docs/Maps_Stage3.md
Normal file
57
Docs/Maps_Stage3.md
Normal file
@ -0,0 +1,57 @@
|
||||
# Maps Stage 3
|
||||
|
||||
Stage 3 refines the existing Stage 1 SVG workspace and Stage 2 batched Story projection. It introduces no database migration and no changes to Story evidence inference. Development only; production is outside this change.
|
||||
|
||||
## Editing and desktop interactions
|
||||
|
||||
- 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.
|
||||
- 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.
|
||||
- Locked object drags pan the viewport; clicks still select. Explore/Story object drags also pan. Unlocked Create drags manipulate the object. The cursor reflects dragging/locking.
|
||||
|
||||
## Unsaved changes
|
||||
|
||||
`PlotDirectorDialogs.choose` extends the existing shared Bootstrap confirmation-dialog partial and styling. Maps uses it for unsaved edits, Rename and Delete. There are no direct Maps calls to browser confirm, alert or prompt.
|
||||
|
||||
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.
|
||||
|
||||
## Shared workspace surface
|
||||
|
||||
`workspace-surface.js/css` is used by Maps and Relationship Map. Maximise/Restore updates canonical command state and sizing without fitting/rebuilding geography or resetting view/selection/mode/Story scope. Escape first respects open menus/dialogs and active editing gestures. Maps hides redundant Maximise in standalone PWA mode. Relationship Map retains its prior PWA behaviour.
|
||||
|
||||
## 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.
|
||||
- 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.
|
||||
|
||||
## Detached workspace
|
||||
|
||||
An explicit Open in separate window action opens the current map/mode, with Story context transferred through the paired-window handshake. `_WorkspaceLayout` keeps the author theme, map toolbar, navigation and canonical dialog/context infrastructure while omitting site/public chrome. Detached map/hierarchy links retain detached mode and pairing. Repeated detach clicks focus the existing open window, protecting its unsaved edits.
|
||||
|
||||
`workspace-bridge.js` uses event-driven same-origin BroadcastChannel messages, scoped by authenticated user ID, project and an explicit random pairing token. Tokens persist only in sessionStorage/query context to bridge main-page navigation. Messages are typed, bounded by sender sequence, and never accept arbitrary navigation URLs. Fixed scene routes are built only from positive integer scene IDs; all destination controllers still enforce normal access. No polling and no new write API.
|
||||
|
||||
Paired windows exchange Story scene/lens/character state and existing-map navigation; the canonical `plotdirector:story-position-changed` event and opening a Scene editor can focus the detached Story map. Incoming Story changes do not replace unsaved Create work. Explicit detached Open scene links request the main editor; acknowledgement prevents duplicate navigation, and a one-shot timeout falls back to the detached window if the main window is gone. An existing main unsaved modal owns its request and can cancel it. Closing either window does not persist/destroy the other's transient state.
|
||||
|
||||
Create is allowed in both windows using the existing server revision checks. Saves notify the peer that it is stale; stale writes fail with retained edits and normal error handling. There is no geometry merge, auto-save, silent reload, shared editing lock or claim of collaborative editing. Incoming other-map navigation leaves a dirty peer where it is and informs it. Project changes create a different scoped pairing; this version does not silently carry a detached map into a different project. Authentication, ownership, subscription, CSRF and Story read-only geography rules are unchanged.
|
||||
|
||||
## Verification
|
||||
|
||||
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-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).
|
||||
- `maps-stage3-dev-smoke.cjs`: authenticated live Development operations on a dedicated disposable account/project, including real server revision conflicts and minimal detached shell. Stage 1/2 Development smoke scripts remain available.
|
||||
|
||||
Deployment/live acceptance and cleanup results are recorded in the task report after execution. No database schema changes are needed. Future Stage 4 candidates remain dense-label layout, richer route chains and publication/export styles; this stage deliberately adds no route inference, background imagery, simulation or server-persisted Story preferences.
|
||||
35
PlotLine.Tests/Browser/maps-detached.cjs
Normal file
35
PlotLine.Tests/Browser/maps-detached.cjs
Normal file
@ -0,0 +1,35 @@
|
||||
const {chromium}=require('playwright'),assert=require('node:assert/strict');
|
||||
const base=process.env.PD_MAPS_STAGE3_URL||'http://127.0.0.1:5251';
|
||||
(async()=>{const browser=await chromium.launch();try{
|
||||
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 fixture=await(await context.request.get(base+'/map-story-fixture')).json();let revision=12,saves=0;
|
||||
await context.route('**/Maps?**',async r=>{const response=await context.request.get(base+'/fixture?page=maps&story=true');await r.fulfill({response});});
|
||||
await context.route('**/Maps/Story?**',r=>r.fulfill({json:fixture}));
|
||||
await context.route('**/Maps/Save',r=>{saves++;const d=r.request().postDataJSON();if(d.map.revision!==revision)return r.fulfill({status:409,json:{message:'This map changed in another window. Reload before saving; your edits remain here.'}});d.map.revision=++revision;return r.fulfill({json:d});});
|
||||
const main=await context.newPage(),errors=[];main.on('pageerror',e=>errors.push(e.message));main.setDefaultTimeout(10000);
|
||||
await main.goto(base+'/fixture?page=maps&story=true');await main.evaluate(()=>window.PlotDirectorMapWorkspace.setMode('story'));await main.waitForFunction(()=>!!window.PlotDirectorStoryOverlay?.data);
|
||||
await main.evaluate(()=>{document.getElementById('mapStoryLens').value='scene';document.getElementById('mapStoryLens').dispatchEvent(new Event('change',{bubbles:true}));window.PlotDirectorStoryOverlay.chooseScene(70);});
|
||||
const popup=main.waitForEvent('popup');await main.evaluate(()=>document.getElementById('mapsDetach').click());const detached=await popup;detached.on('pageerror',e=>errors.push(e.message));detached.setDefaultTimeout(10000);
|
||||
await detached.waitForFunction(()=>!!window.PlotDirectorStoryOverlay?.data);await detached.waitForFunction(()=>window.PlotDirectorStoryOverlay.state.sceneID===70);
|
||||
assert.equal(new URL(detached.url()).searchParams.get('detached'),'true');assert(await detached.evaluate(()=>window.PlotDirectorWorkspaceBridge.mainAvailable));
|
||||
await main.evaluate(()=>window.PlotDirectorStoryOverlay.chooseScene(20));await detached.waitForFunction(()=>window.PlotDirectorStoryOverlay.state.sceneID===20);
|
||||
await detached.evaluate(()=>window.PlotDirectorStoryOverlay.chooseScene(80));await main.waitForFunction(()=>window.PlotDirectorStoryOverlay.state.sceneID===80);
|
||||
await main.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:story-position-changed',{detail:{projectId:7,sceneId:10}})));await detached.waitForFunction(()=>window.PlotDirectorStoryOverlay.state.sceneID===10);
|
||||
await main.evaluate(()=>{document.getElementById('mapStoryLens').value='character';document.getElementById('mapStoryCharacter1').value='1';document.getElementById('mapStoryCharacter1').dispatchEvent(new Event('change',{bubbles:true}));});await detached.waitForFunction(()=>window.PlotDirectorStoryOverlay.state.lens==='character'&&window.PlotDirectorStoryOverlay.state.characterIDs[0]===1);
|
||||
assert.equal(saves,0);assert.equal(await detached.evaluate(()=>window.PlotDirectorMapWorkspace.dirty),false);
|
||||
// A forged envelope from another user cannot change the paired view.
|
||||
await detached.evaluate(()=>{const token=new URLSearchParams(location.search).get('workspace'),c=new BroadcastChannel('pd-workspace:1:7:'+token);c.postMessage({uid:999,projectID:7,sender:crypto.randomUUID(),sequence:1,type:'scene-selected',payload:{sceneID:30}});c.close();});
|
||||
await main.evaluate(()=>new Promise(resolve=>setTimeout(resolve,100)));assert.equal(await main.evaluate(()=>window.PlotDirectorStoryOverlay.state.lens),'character');
|
||||
async function edit(page,name){await page.evaluate(()=>{const w=window.PlotDirectorMapWorkspace;w.setMode('create');w.select(w.document.features[0].featureID);});await page.locator('[data-field=name]').fill(name);await page.locator('[data-field=name]').blur();}
|
||||
await edit(detached,'Detached unsaved geography');await main.evaluate(()=>window.PlotDirectorStoryOverlay.chooseScene(30));assert.equal(await detached.evaluate(()=>window.PlotDirectorMapWorkspace.mode),'create');assert.equal(await detached.locator('[data-field=name]').inputValue(),'Detached unsaved geography');
|
||||
await edit(main,'Main saved geography');assert(await main.evaluate(()=>window.PlotDirectorMapWorkspace.save()));await detached.waitForFunction(()=>document.getElementById('mapsStatus').textContent.includes('another window'));
|
||||
assert.equal(await detached.evaluate(()=>window.PlotDirectorMapWorkspace.save()),false);assert.equal(await detached.evaluate(()=>window.PlotDirectorMapWorkspace.dirty),true);assert.equal(await detached.locator('[data-field=name]').inputValue(),'Detached unsaved geography');assert.equal(revision,13);
|
||||
await detached.evaluate(()=>{void window.PlotDirectorMapWorkspace.requestLeave(()=>{});});await detached.getByRole('button',{name:'Discard changes',exact:true}).click();await main.close();
|
||||
await detached.evaluate(()=>window.PlotDirectorMapWorkspace.setMode('story'));await detached.evaluate(()=>window.PlotDirectorStoryOverlay.chooseScene(90));assert.equal(await detached.evaluate(()=>window.PlotDirectorStoryOverlay.state.sceneID),90);assert.equal(await detached.evaluate(()=>window.PlotDirectorMapWorkspace.dirty),false);
|
||||
// An explicit Open scene still works when its former main window has closed.
|
||||
await context.route('**/Scenes/Edit/*',r=>r.fulfill({contentType:'text/html',body:'<h1>Scene editor</h1>'}));
|
||||
await detached.getByRole('link',{name:'Open / edit scene',exact:true}).click();await detached.waitForURL('**/Scenes/Edit/90');
|
||||
assert.deepEqual(errors,[]);console.log(`PASS Maps detached ${pwa?'PWA':'web'}: explicit popup, paired scenes/lens/characters, canonical scene event, envelope scope, dirty peer protection, optimistic conflict, closed-opener fallback`);await context.close();
|
||||
}
|
||||
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
@ -47,7 +47,7 @@ const base='https://dev.plotdirector.com';
|
||||
await page.goto(rootURL);await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),towns[0].featureID);await page.locator('a:text-is("Open detailed map: Harbour detail ↳")').click();await page.waitForURL(childURL);
|
||||
// Duplicate and delete are exercised through the real server.
|
||||
await page.locator('.maps-toolbar details summary').click();await page.locator('#mapsDuplicate').click();await page.waitForURL(url=>url.href!==childURL&&url.searchParams.has('id'));
|
||||
await page.waitForFunction(()=>window.PlotDirectorMapWorkspace?.document?.map.name.endsWith(' copy'));await page.locator('.maps-toolbar details summary').click();await page.locator('#mapsDelete').click();await page.waitForURL(base+'/Maps?projectId='+projectId);
|
||||
await page.waitForFunction(()=>window.PlotDirectorMapWorkspace?.document?.map.name.endsWith(' copy'));await page.locator('.maps-toolbar details summary').click();await page.locator('#mapsDelete').click();await page.locator('#pdApplicationDialog').getByRole('button',{name:'Delete map',exact:true}).click();await page.waitForURL(base+'/Maps?projectId='+projectId);
|
||||
// New canonical Location is available in another map's unplaced tray.
|
||||
await page.goto(childURL);await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);assert(await page.locator(`[data-location="${locationID}"]`).isVisible());
|
||||
await page.locator(`[data-location="${locationID}"]`).click();let b=await page.locator('#mapsCanvas').boundingBox();await page.mouse.click(b.x+b.width/2,b.y+b.height/2);await page.locator('#mapsSave').click();await page.waitForFunction(()=>document.getElementById('mapsStatus').textContent==='Saved');
|
||||
|
||||
@ -16,3 +16,16 @@ const points=E.pathPoints(route,[a,b]);assert.deepEqual(points[0],[150,0]);asser
|
||||
const island=E.makeFeature('Island',0,0,'island');assert.equal(E.curve(E.coastline(island),true),E.curve(E.coastline(island),true));
|
||||
assert(E.library.length>70);assert(E.library.some(x=>x.type==='Forest'&&x.geometryClass==='Area'));assert(E.library.some(x=>x.type==='River'&&x.geometryClass==='Path'));
|
||||
console.log('PASS Maps arrangement determinism, bounded physical distance, graph relationships, conflicts, locks, unplaced-only, attached routes and deterministic coasts');
|
||||
// A free endpoint transforms the path around its opposite end; attachments remain authoritative.
|
||||
{
|
||||
const path=E.makeFeature('Road',40,50,'endpoint-test'),before=E.pathPoints(path,[]),target=[before[0][0]+80,before[0][1]+100];
|
||||
const next=E.transformEndpoint(path,0,target,[]),after=E.pathPoints(next,[]);
|
||||
const near=(a,b)=>assert(Math.hypot(a[0]-b[0],a[1]-b[1])<1e-8);
|
||||
near(after[0],target);near(after.at(-1),before.at(-1));assert.notEqual(next.rotation,path.rotation);
|
||||
const place=E.makeFeature('Town',250,300,'anchor');path.endFeatureID=place.featureID;
|
||||
const attached=E.transformEndpoint(path,0,target,[place]);near(E.pathPoints(attached,[place]).at(-1),[250,300]);
|
||||
path.startFeatureID=place.featureID;assert.deepEqual(E.transformEndpoint(path,0,target,[place]),path);
|
||||
const symbols=require('../../PlotLine/wwwroot/js/maps-symbols.js');assert.equal(symbols.types.length,75);for(const asset of E.library)assert(symbols.content(asset.type),'Every map piece has a semantic SVG pictogram: '+asset.type);
|
||||
assert.equal(new Set(E.library.map(a=>symbols.content(a.type))).size,75,'All palette symbols have distinct semantic treatments');
|
||||
console.log('PASS Maps endpoint similarity transforms, authoritative attachments and complete distinct 75-piece SVG symbol library');
|
||||
}
|
||||
|
||||
41
PlotLine.Tests/Browser/maps-stage3-dev-smoke.cjs
Normal file
41
PlotLine.Tests/Browser/maps-stage3-dev-smoke.cjs
Normal file
@ -0,0 +1,41 @@
|
||||
// Dedicated authenticated Development acceptance. Never uses real author projects.
|
||||
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
|
||||
const [identityPath,fixturePath]=process.argv.slice(2);
|
||||
if(!identityPath?.startsWith('/tmp/pd-dev-browser-')||!fixturePath?.startsWith('/tmp/pd-dev-browser-'))throw Error('Dedicated Development identity and fixture files required.');
|
||||
const identity=JSON.parse(fs.readFileSync(identityPath,'utf8')),f=JSON.parse(fs.readFileSync(fixturePath,'utf8')),base='https://dev.plotdirector.com';
|
||||
if(identity.Database!=='PlotDirector_Development'||!identity.Email.startsWith('pwa-browser-'))throw Error('Development identity required.');
|
||||
(async()=>{const browser=await chromium.launch();try{
|
||||
const signedIn=await browser.newContext(),login=await signedIn.newPage();await login.goto(base+'/Account/Login');await login.locator('#Email').fill(identity.Email);await login.locator('#Password').fill(identity.Password);await Promise.all([login.waitForURL('**/Projects'),login.locator('form[action="/Account/Login"] button[type=submit]').click()]);
|
||||
const root=`${base}/Maps?projectId=${f.ProjectID}&id=${f.MapID}`,errors=[];
|
||||
for(const pwa of [false,true]){
|
||||
const context=await browser.newContext({viewport:{width:1800,height:1100},storageState:await signedIn.storageState()});if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
|
||||
const page=await context.newPage();page.setDefaultTimeout(20000);page.on('pageerror',e=>errors.push(e.message));page.on('dialog',d=>{errors.push('Unexpected browser dialog: '+d.type());d.dismiss();});
|
||||
await page.goto(root);await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);const canvas=page.locator('#mapsCanvas');
|
||||
async function command(id){await page.evaluate(id=>document.getElementById(id).click(),id);}
|
||||
async function drag(selector,dx,dy){const b=await page.locator(selector).first().boundingBox();assert(b);await page.mouse.move(b.x+b.width/2,b.y+b.height/2);await page.mouse.down();await page.mouse.move(b.x+b.width/2+dx,b.y+b.height/2+dy,{steps:5});await page.mouse.up();}
|
||||
const added=[];for(const type of ['Land Mass','Forest','Road','Railway','River','Canal']){await page.locator('#mapsAssetSearch').fill(type);await page.locator(`[data-asset="${type}"]`).click();await canvas.click({position:{x:330,y:280}});added.push(await page.evaluate(()=>window.PlotDirectorMapWorkspace.document.features.at(-1).featureID));await page.locator('[data-action=shape]').click();for(let i=0;i<3;i++)await drag('[data-handle=point]',i%2?8:-8,5);assert.equal(await page.evaluate(()=>getSelection().toString()),'');if(['Road','Railway','River','Canal'].includes(type))await drag('[data-handle=endpoint]',25,35);}
|
||||
await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),added[0]);const rotate=page.locator('input[type=range][data-rotate]');await rotate.fill('35');await command('mapsUndo');await command('mapsRedo');
|
||||
await page.locator('[data-field=isLocked]').check();const view=await page.evaluate(()=>({...window.PlotDirectorMapWorkspace.view}));
|
||||
// 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);
|
||||
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'});
|
||||
await page.evaluate(()=>window.PlotDirectorMapWorkspace.setMode('story'));await modal.getByRole('button',{name:'Save and continue',exact:true}).click();await page.waitForFunction(()=>!!window.PlotDirectorStoryOverlay?.data);assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.dirty),false);
|
||||
await page.evaluate(()=>{const n=document.getElementById('mapStoryLens');n.value='scene';n.dispatchEvent(new Event('change',{bubbles:true}));});const storyBefore=await(await context.request.get(`${base}/Maps/State?projectId=${f.ProjectID}&id=${f.MapID}`)).json();
|
||||
const projection=await page.evaluate(()=>window.PlotDirectorStoryOverlay.data);for(let i=0;i<projection.scenes.length;i++){await page.locator('#mapStoryScrubber').fill(String(i));await page.locator('#mapStoryScrubber').dispatchEvent('change');assert.equal(await page.evaluate(()=>window.PlotDirectorStoryOverlay.state.sceneID),projection.scenes[i].sceneID);}await command('mapStoryPrevious');await command('mapStoryNext');
|
||||
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 popup=page.waitForEvent('popup');await command('mapsDetach');const detached=await popup;detached.setDefaultTimeout(20000);detached.on('pageerror',e=>errors.push(e.message));await detached.waitForFunction(()=>!!window.PlotDirectorStoryOverlay?.data);assert.equal(await detached.locator('.pd-application-header').count(),0);assert.equal(await detached.locator('.public-footer').count(),0);assert.equal(await detached.locator('.maps-toolbar:visible').count(),1);assert(await detached.locator('#mapsDetach').isHidden());
|
||||
await page.evaluate(id=>window.PlotDirectorStoryOverlay.chooseScene(id),f.SceneAID);await detached.waitForFunction(id=>window.PlotDirectorStoryOverlay.state.sceneID===id,f.SceneAID);await detached.evaluate(id=>window.PlotDirectorStoryOverlay.chooseScene(id),f.SceneBID);await page.waitForFunction(id=>window.PlotDirectorStoryOverlay.state.sceneID===id,f.SceneBID);
|
||||
const storyAfter=await(await context.request.get(`${base}/Maps/State?projectId=${f.ProjectID}&id=${f.MapID}`)).json();assert.deepEqual(storyAfter,storyBefore);
|
||||
async function edit(p,name){await p.evaluate(()=>{const w=window.PlotDirectorMapWorkspace;w.setMode('create');w.select(w.document.features[0].featureID);});await p.locator('[data-field=name]').fill(name);await p.locator('[data-field=name]').blur();}
|
||||
await edit(detached,'Detached retained edit '+pwa);await edit(page,'Main saved edit '+pwa);assert(await page.evaluate(()=>window.PlotDirectorMapWorkspace.save()));assert.equal(await detached.evaluate(()=>window.PlotDirectorMapWorkspace.save()),false);assert(await detached.evaluate(()=>window.PlotDirectorMapWorkspace.dirty));assert.match(await detached.locator('#mapsStatus').innerText(),/changed|another|reload/i);
|
||||
// Real optimistic conflict also prevents a pending navigation from continuing.
|
||||
await detached.evaluate(()=>document.getElementById('mapsNew').click());await detached.getByRole('button',{name:'Save and continue',exact:true}).click();assert(await detached.locator('#pdApplicationDialog [data-dialog-error]').isVisible());assert(await detached.locator('#mapsNewDialog').isHidden());await detached.getByRole('button',{name:'Discard changes',exact:true}).click();await detached.locator('#mapsNewDialog').waitFor();await detached.locator('#mapsNewCancel').click();
|
||||
await page.close();await detached.evaluate(()=>window.PlotDirectorMapWorkspace.setMode('story'));await detached.evaluate(id=>window.PlotDirectorStoryOverlay.chooseScene(id),f.SceneAID);await detached.getByRole('link',{name:'Open / edit scene',exact:true}).click();await detached.waitForURL('**/Scenes/Edit/'+f.SceneAID);assert(await detached.locator('main').isVisible());
|
||||
const denied=await context.request.get(`${base}/Maps?projectId=${f.ProjectID}&id=-1&detached=true`);assert.equal(denied.status(),404);const csrf=await context.request.post(`${base}/Maps/Save`,{data:storyBefore});assert.equal(csrf.status(),400);
|
||||
console.log(`PASS live Development Maps Stage 3 ${pwa?'PWA':'web'}: repeated land/forest/path drags, transforms/rotation/undo, canonical menus/locked pan/maximise, unsaved modal, real save/conflict, scrubber/characters, minimal detached shell/sync/closed-opener scene navigation, auth/CSRF and Story geography immutability`);await context.close();
|
||||
}
|
||||
assert.deepEqual(errors,[]);await signedIn.close();
|
||||
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
52
PlotLine.Tests/Browser/maps-stage3.cjs
Normal file
52
PlotLine.Tests/Browser/maps-stage3.cjs
Normal file
@ -0,0 +1,52 @@
|
||||
const {chromium}=require('playwright'),assert=require('node:assert/strict');
|
||||
const base=process.env.PD_MAPS_STAGE3_URL||'http://127.0.0.1:5251';
|
||||
(async()=>{const browser=await chromium.launch();try{
|
||||
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});});
|
||||
await context.route('**/stage3-destination-*',r=>r.fulfill({contentType:'text/html',body:'<h1>Destination</h1>'}));
|
||||
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));}
|
||||
async function command(id){await page.evaluate(id=>document.getElementById(id).click(),id);}
|
||||
page.setDefaultTimeout(8000);page.setDefaultNavigationTimeout(8000);
|
||||
const modal=page.locator('#pdApplicationDialog');
|
||||
console.log('Modal tests',pwa);await open();await dirty();
|
||||
console.log('Dirty ready');const preserved=await page.evaluate(()=>({doc:JSON.stringify(window.PlotDirectorMapWorkspace.document),view:{...window.PlotDirectorMapWorkspace.view},selection:window.PlotDirectorMapWorkspace.selected}));
|
||||
await page.evaluate(()=>{window.__continued=[];window.PlotDirectorMapWorkspace.requestLeave(()=>window.__continued.push('first'));window.PlotDirectorMapWorkspace.requestLeave(()=>window.__continued.push('second'));});
|
||||
console.log('Pending ready');assert.equal(await modal.count(),1);await modal.getByRole('button',{name:'Keep editing',exact:true}).click();await modal.waitFor({state:'detached'});
|
||||
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);
|
||||
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');
|
||||
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'});
|
||||
async function place(type){await page.locator('#mapsAssetSearch').fill(type);await page.locator(`[data-asset="${type}"]`).click();await page.locator('#mapsCanvas').click({position:{x:280,y:280}});return await page.evaluate(()=>window.PlotDirectorMapWorkspace.document.features.at(-1).featureID);}
|
||||
console.log('Manipulation tests');const road=await place('Road');assert.equal(await page.locator('[data-handle=endpoint]').count(),2);
|
||||
async function dragHandle(selector,dx,dy){const b=await page.locator(selector).first().boundingBox();await page.mouse.move(b.x+b.width/2,b.y+b.height/2);await page.mouse.down();await page.mouse.move(b.x+b.width/2+dx,b.y+b.height/2+dy,{steps:6});await page.mouse.up();}
|
||||
const before=await page.evaluate(id=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id)),road);
|
||||
await dragHandle('[data-handle=endpoint]',45,65);const transformed=await page.evaluate(id=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id)),road);assert.notEqual(transformed,before);await command('mapsUndo');assert.equal(await page.evaluate(id=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id)),road),before);await command('mapsRedo');assert.equal(await page.evaluate(id=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id)),road),transformed);
|
||||
await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),road);await page.locator('[data-action=shape]').click();for(let i=0;i<5;i++)await dragHandle('[data-handle=point]',i%2?10:-10,8);assert.equal(await page.evaluate(()=>getSelection().toString()),'');
|
||||
const ids=await page.evaluate(()=>window.PlotDirectorMapWorkspace.document.features.filter(f=>f.geometryClass==='Marker').slice(0,2).map(f=>f.featureID));await page.locator('[data-field=startFeatureID]').selectOption(ids[0]);assert.equal(await page.locator('[data-handle=endpoint]').count(),1);await page.locator('[data-field=endFeatureID]').selectOption(ids[1]);assert.equal(await page.locator('[data-handle=endpoint]').count(),0);
|
||||
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(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));}
|
||||
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'})));
|
||||
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();
|
||||
}
|
||||
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
@ -8,6 +8,7 @@ const base=process.env.PD_MAPS_TEST_URL||'http://127.0.0.1:5246';
|
||||
const context=await browser.newContext({viewport:{width:1700,height:1100}});
|
||||
if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
|
||||
const page=await context.newPage(),errors=[];page.setDefaultTimeout(10000);page.on('pageerror',e=>errors.push(e.message));
|
||||
await page.route('**/Maps/Save',r=>{const d=r.request().postDataJSON();d.map.revision++;return r.fulfill({json:d});});
|
||||
await page.goto(base+'/fixture?page=maps');await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);
|
||||
const canvas=page.locator('#mapsCanvas');
|
||||
async function sourceClick(id){
|
||||
@ -58,6 +59,7 @@ const base=process.env.PD_MAPS_TEST_URL||'http://127.0.0.1:5246';
|
||||
if(pwa){await page.locator('[data-pwa-context-controls] input[aria-label="Find on map"]').fill('Harbour');}
|
||||
else await find.fill('Harbour');
|
||||
await page.locator('[data-search-feature]').click();assert.equal(await page.locator('.maps-feature.is-selected').count(),1);
|
||||
await page.evaluate(async()=>{window.PlotDirectorMapWorkspace.setMode('create');await window.PlotDirectorMapWorkspace.save();});
|
||||
await page.evaluate(()=>document.querySelector('button[data-mode="story"]').click());assert(await page.locator('#mapsStory').isVisible());
|
||||
await page.evaluate(()=>document.querySelector('button[data-mode="create"]').click());
|
||||
if(pwa){assert(await page.locator('#mapsMaximise').isHidden());assert(await page.locator('.maps-toolbar').isHidden());}
|
||||
|
||||
@ -34,6 +34,7 @@ internal static class MapTests
|
||||
// A denied project must short-circuit every route before any repository can be touched.
|
||||
var controller = new MapsController(null!, null!, null!, null!, new DeniedAccess(), null!);
|
||||
Check(controller.Index(7, 1).Result is NotFoundResult, "Index must enforce ownership/collaboration access.");
|
||||
Check(controller.Index(7, 1, detached: true).Result is NotFoundResult, "Detached Maps must use the same project-access gate.");
|
||||
Check(controller.State(7, 1).Result is NotFoundResult, "State must enforce access.");
|
||||
Check(controller.Create(new() { ProjectID = 7 }).Result is NotFoundResult, "Create must enforce access.");
|
||||
Check(controller.Save(d).Result is NotFoundResult, "Save must enforce access.");
|
||||
|
||||
@ -355,7 +355,7 @@ internal static class ToolbarBrowserHost
|
||||
Project = model.Project!, Maps = [map], Document = new MapDocument { Map = map },
|
||||
Locations = [new LocationItem { LocationID = 11, ProjectID = 7, LocationName = "Harbour town" }, new LocationItem { LocationID = 12, ProjectID = 7, LocationName = "Hill village" }]
|
||||
});
|
||||
surface += "<script src='/js/maps-engine.js'></script><script src='/js/maps-workspace.js'></script><script src='/js/maps-story-engine.js'></script><script src='/js/maps-story.js'></script>";
|
||||
surface += "<script src='/js/application-dialogs.js'></script><script src='/js/workspace-surface.js'></script><script src='/js/maps-symbols.js'></script><script src='/js/workspace-bridge.js'></script><script src='/js/maps-engine.js'></script><script src='/js/maps-workspace.js'></script><script src='/js/maps-story-engine.js'></script><script src='/js/maps-story.js'></script>";
|
||||
}
|
||||
surface += await Render("Shared/_ConfirmationDialog");
|
||||
var initialTheme = appearance.ThemeKey ?? "warm-light";
|
||||
@ -364,7 +364,7 @@ internal static class ToolbarBrowserHost
|
||||
PlotLine.TagHelpers.RibbonContributionTagHelper.Snapshot(context).WriteTo(contributionWriter, System.Text.Encodings.Web.HtmlEncoder.Default);
|
||||
var contributions = contributionWriter.ToString();
|
||||
context.Response.ContentType = "text/html; charset=utf-8";
|
||||
await context.Response.WriteAsync("<!doctype html><html lang='en' data-app-theme='" + initialTheme + "' data-theme='" + (initialTheme.EndsWith("dark") ? "dark" : "light") + "'><head><script src='/js/application-display-mode.js'></script><link rel='manifest' href='/site.webmanifest'><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-navigation.css'><link rel='stylesheet' href='/css/application-shell.css'><link rel='stylesheet' href='/css/record-workspace.css'><link rel='stylesheet' href='/css/application-context-menu.css'><link rel='stylesheet' href='/css/plot-line-workspace.css'><link rel='stylesheet' href='/css/onboarding.css'></head><body class='app-layout'><header class='pd-application-header'>" + menu + toolbar + "</header><template data-pwa-initial-contributions>" + contributions + "</template><script src='/js/application-page-context.js'></script><div class='plotline-help-main'><div class='container-fluid plotline-shell " + (recordLayout is null ? "pd-dashboard-shell" : $"pd-record-canvas pd-record-canvas--{recordLayout}") + "'><main data-pwa-page-content class='pb-3'>" + surface + "</main><script>window.PlotDirectorPageContext?.activate();</script></div></div><script src='/lib/bootstrap/dist/js/bootstrap.bundle.min.js'></script><script src='/js/application-navigation.js'></script><script src='/js/application-toolbar.js'></script>" + appearanceScript + "<script src='/js/application-shell.js'></script><script src='/js/site.js'></script><script src='/js/application-pwa.js'></script><script src='/js/application-context-menu.js'></script></body></html>");
|
||||
await context.Response.WriteAsync("<!doctype html><html lang='en' data-app-theme='" + initialTheme + "' data-theme='" + (initialTheme.EndsWith("dark") ? "dark" : "light") + "'><head><script src='/js/application-display-mode.js'></script><link rel='manifest' href='/site.webmanifest'><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-navigation.css'><link rel='stylesheet' href='/css/application-shell.css'><link rel='stylesheet' href='/css/record-workspace.css'><link rel='stylesheet' href='/css/application-context-menu.css'><link rel='stylesheet' href='/css/plot-line-workspace.css'><link rel='stylesheet' href='/css/onboarding.css'></head><body data-pd-user-id='1' data-pd-project-id='7' class='app-layout'><header class='pd-application-header'>" + menu + toolbar + "</header><template data-pwa-initial-contributions>" + contributions + "</template><script src='/js/application-page-context.js'></script><div class='plotline-help-main'><div class='container-fluid plotline-shell " + (recordLayout is null ? "pd-dashboard-shell" : $"pd-record-canvas pd-record-canvas--{recordLayout}") + "'><main data-pwa-page-content class='pb-3'>" + surface + "</main><script>window.PlotDirectorPageContext?.activate();</script></div></div><script src='/lib/bootstrap/dist/js/bootstrap.bundle.min.js'></script><script src='/js/application-navigation.js'></script><script src='/js/application-toolbar.js'></script>" + appearanceScript + "<script src='/js/application-shell.js'></script><script src='/js/site.js'></script><script src='/js/application-pwa.js'></script><script src='/js/application-context-menu.js'></script></body></html>");
|
||||
});
|
||||
await app.RunAsync();
|
||||
}
|
||||
|
||||
@ -11,7 +11,7 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec
|
||||
IFloorPlanRepository floorPlans, IProjectAccessService access, ICurrentUserService currentUser) : Controller
|
||||
{
|
||||
private int UserID => currentUser.UserId!.Value;
|
||||
public async Task<IActionResult> Index(int projectId, int? id)
|
||||
public async Task<IActionResult> Index(int projectId, int? id, bool detached = false)
|
||||
{
|
||||
if (projectId == 0) return View("ChooseProject", await projects.ListActiveForUserAsync(UserID));
|
||||
if (!await access.CanAccessProjectAsync(projectId)) return NotFound();
|
||||
@ -19,6 +19,7 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec
|
||||
if (project is null) return NotFound();
|
||||
var document = id.HasValue ? await maps.GetAsync(projectId, id.Value, UserID) : null;
|
||||
if (id.HasValue && document is null) return NotFound();
|
||||
if (detached) ViewData["DetachedWorkspace"] = true;
|
||||
return View(new MapsViewModel { Project = project, Maps = await maps.ListAsync(projectId, UserID), Document = document,
|
||||
Locations = await locations.ListByProjectAsync(projectId), FloorPlans = await floorPlans.ListByProjectAsync(projectId) });
|
||||
}
|
||||
|
||||
@ -41,6 +41,14 @@ public static class RibbonPresentation
|
||||
return null;
|
||||
}
|
||||
public static IReadOnlyList<RibbonIcon> AdditionalIcons { get; } = [
|
||||
new("undo", "M9 4L3 10l6 6 M3 10h10a7 7 0 0 1 7 7v3", "planning"),
|
||||
new("redo", "M15 4l6 6-6 6 M21 10H11a7 7 0 0 0-7 7v3", "planning"),
|
||||
new("previous", "M15 4l-8 8 8 8 M4 4v16", "calendar"),
|
||||
new("next", "M9 4l8 8-8 8 M20 4v16", "calendar"),
|
||||
new("restore-workspace", "M8 3h13v13 M3 8h13v13H3z", "planning"),
|
||||
new("separate-window", "M14 3h7v7 M21 3l-9 9 M10 5H3v16h16v-7", "planning"),
|
||||
new("lock", "M6 11V7a6 6 0 0 1 12 0v4 M4 11h16v10H4z M12 15v3", "planning"),
|
||||
new("unlock", "M6 11V7a6 6 0 0 1 12 0 M4 11h16v10H4z M12 15v3", "planning"),
|
||||
new("map", "M3 5l6-2 6 2 6-2v16l-6 2-6-2-6 2z M9 3v16 M15 5v16", "relationships"),
|
||||
new("focus", "M12 2v4 M12 18v4 M2 12h4 M18 12h4 M19 12a7 7 0 1 0-14 0 7 7 0 0 0 14 0 M14 12a2 2 0 1 0-4 0 2 2 0 0 0 4 0", "relationships"),
|
||||
new("details", "M4 3h16v18H4z M8 7h8 M8 11h8 M8 15h5", "books"),
|
||||
|
||||
@ -1,12 +1,14 @@
|
||||
@model PlotLine.Models.MapsViewModel
|
||||
@using System.Text.Json
|
||||
@{
|
||||
if (ViewData["DetachedWorkspace"] is true) Layout = "_WorkspaceLayout";
|
||||
ViewData["Title"] = Model.Document?.Map.Name ?? "Maps";
|
||||
ViewData["ProjectSection"] = "Maps";
|
||||
ViewData["ShellClass"] = "plotline-shell-wide maps-shell";
|
||||
}
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
@if (ViewData["DetachedWorkspace"] is not true) { <partial name="_ProjectSectionNav" model="Model.Project" /> }
|
||||
<link rel="stylesheet" href="~/css/maps-workspace.css" asp-append-version="true" />
|
||||
<link rel="stylesheet" href="~/css/workspace-surface.css" asp-append-version="true" />
|
||||
<section id="mapsApp" class="maps-app" aria-label="Maps workspace">
|
||||
<header class="maps-toolbar">
|
||||
<h1>Maps</h1>
|
||||
@ -15,10 +17,12 @@
|
||||
<form class="maps-find" id="mapsSearchForm" data-pwa-context="Search" data-pwa-scope="Search"><label>Find on map <input id="mapsFind" name="search" type="search" placeholder="Place or feature name" /></label></form>
|
||||
<button type="button" id="mapsNew" data-pwa-context="Map" data-ribbon-icon="add">New map</button>
|
||||
<button type="button" id="mapsSave" data-pwa-context="Map" data-ribbon-icon="save">Save</button>
|
||||
<details data-pwa-context="Map actions" data-pwa-menu-icon="layout" data-pwa-compact="true"><summary>Map actions</summary><div class="maps-menu"><button type="button" id="mapsRename">Rename map</button><button type="button" id="mapsDuplicate">Duplicate map</button><button type="button" id="mapsDelete">Delete map…</button></div></details>
|
||||
<details data-pwa-context="Map actions" data-pwa-menu-icon="layout" data-pwa-compact="true"><summary>Map actions</summary><div class="maps-menu"><button type="button" id="mapsRename" data-ribbon-icon="writer">Rename map</button><button type="button" id="mapsDuplicate" data-ribbon-icon="copy">Duplicate map</button><button type="button" id="mapsDelete" data-ribbon-icon="remove">Delete map…</button></div></details>
|
||||
<div data-pwa-context="Editing" class="maps-edit-tools"><button type="button" id="mapsUndo" data-ribbon-icon="undo">Undo</button><button type="button" id="mapsRedo" data-ribbon-icon="redo">Redo</button></div>
|
||||
<button type="button" id="mapsArrange" data-pwa-context="Arrange" data-ribbon-icon="auto-arrange">Arrange from relationships</button>
|
||||
<button type="button" id="mapsMaximise" data-pwa-context="Workspace" data-ribbon-icon="maximise" aria-pressed="false">Maximise workspace</button>
|
||||
<button type="button" id="mapsDetach" data-pwa-context="Workspace" data-ribbon-icon="separate-window">Open in separate window</button>
|
||||
<button type="button" id="mapsContext" data-pwa-context="Workspace" data-ribbon-icon="list" aria-label="Map context menu">Map menu</button>
|
||||
<button type="button" id="mapsMaximise" data-pwa-context="Workspace" data-ribbon-icon="maximise" aria-pressed="false"><span data-workspace-caption>Maximise workspace</span></button>
|
||||
</header>
|
||||
<div id="mapsStoryToolbar" class="maps-story-toolbar" hidden>
|
||||
<form data-pwa-context="Story lens" data-pwa-scope="Story lens"><label>Story lens <select id="mapStoryLens" aria-label="Story lens" name="lens"><option value="overview">Overview</option><option value="scene">Scene</option><option value="character">Character</option><option value="chapter">Chapter</option><option value="plot">Plot Line</option><option value="time">Time</option></select></label></form>
|
||||
@ -45,7 +49,7 @@
|
||||
<div id="mapsSearchResults" class="maps-search-results" aria-label="Map search results"></div>
|
||||
<div id="mapsStory" hidden role="status" aria-live="polite">Loading manuscript geography…</div>
|
||||
<div id="mapsWelcome" hidden><h2>Your story, in place</h2><p>Start with a few places, or build a landscape a piece at a time.</p><button type="button" id="mapsWelcomeNew">Create your first map</button><div id="mapsList"></div></div>
|
||||
<svg id="mapsCanvas" viewBox="-600 -400 1200 800" tabindex="0" role="group" aria-label="Story map. Drag background to pan. Use zoom controls. Select pieces for details.">
|
||||
<svg id="mapsCanvas" data-pd-context-web="true" viewBox="-600 -400 1200 800" tabindex="0" role="group" aria-label="Story map. Drag background to pan. Use zoom controls. Select pieces for details.">
|
||||
<defs>
|
||||
<pattern id="map-forest" width="32" height="32" patternUnits="userSpaceOnUse"><rect width="32" height="32" fill="#c4d4af"/><path d="M8 5l-6 12h12z M23 14l-6 12h12z" fill="#63845f"/></pattern>
|
||||
<pattern id="map-mountains" width="48" height="36" patternUnits="userSpaceOnUse"><rect width="48" height="36" fill="#d3cebd"/><path d="M0 32L17 5l17 27 M24 36L40 12l16 24" fill="#aca895" stroke="#727a6e"/><path d="M12 13l5-8 6 10-6-3z" fill="#f8f7ef"/></pattern>
|
||||
@ -54,6 +58,7 @@
|
||||
<pattern id="map-farmland" width="24" height="24" patternUnits="userSpaceOnUse" patternTransform="rotate(25)"><rect width="24" height="24" fill="#e1d39c"/><path d="M0 6h24M0 18h24" stroke="#b3ad73"/></pattern>
|
||||
</defs><g id="mapsScene"></g><g id="mapsStoryLayer" aria-label="Story overlays" hidden></g><g id="mapsHandles"></g>
|
||||
</svg>
|
||||
<div id="mapStoryScrubberRow" class="maps-scene-scrubber" hidden><label for="mapStoryScrubber">Scene <output id="mapStoryScrubberContext"></output></label><input id="mapStoryScrubber" type="range" min="0" max="0" value="0" aria-label="Scene in manuscript order" /><button type="button" id="mapStoryCoverage">Inspect unmapped Locations</button></div>
|
||||
<div class="maps-canvas-tools"><button type="button" id="mapsZoomOut" aria-label="Zoom out">−</button><span id="mapsZoom">100%</span><button type="button" id="mapsZoomIn" aria-label="Zoom in">+</button><button type="button" id="mapsFit">Fit map</button><button type="button" id="mapsFitSelection">Fit selection</button><span>Not to scale · N ↑</span></div>
|
||||
</div>
|
||||
<aside id="mapsDetails" class="maps-details" aria-label="Details"><h2>Details</h2><div id="mapsDetailContent">Select something on the map to see its details.</div></aside>
|
||||
@ -64,6 +69,8 @@
|
||||
@Html.AntiForgeryToken()
|
||||
<script id="mapsBootstrap" type="application/json">@Html.Raw(JsonSerializer.Serialize(new { projectId = Model.Project.ProjectID, maps = Model.Maps, locations = Model.Locations, floorPlans = Model.FloorPlans, document = Model.Document }, new JsonSerializerOptions(JsonSerializerDefaults.Web)))</script>
|
||||
@section Scripts {
|
||||
<script src="~/js/workspace-surface.js" asp-append-version="true"></script>
|
||||
<script src="~/js/maps-symbols.js" asp-append-version="true"></script>
|
||||
<script src="~/js/maps-engine.js" asp-append-version="true"></script>
|
||||
<script src="~/js/maps-workspace.js" asp-append-version="true"></script>
|
||||
<script src="~/js/maps-story-engine.js" asp-append-version="true"></script>
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
<link rel="stylesheet" href="~/css/workspace-surface.css" asp-append-version="true" /><script src="~/js/workspace-surface.js" asp-append-version="true"></script>
|
||||
@using System.Text.Json
|
||||
@model RelationshipMapViewModel
|
||||
@{ var jsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; }
|
||||
|
||||
@ -19,3 +19,12 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<template id="pdApplicationDialogTemplate">
|
||||
<div class="modal fade" tabindex="-1" aria-modal="true" role="dialog">
|
||||
<div class="modal-dialog modal-dialog-centered"><div class="modal-content plotline-confirm-modal">
|
||||
<div class="modal-header"><h2 class="modal-title fs-5" data-dialog-title></h2><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Keep editing / Cancel"></button></div>
|
||||
<div class="modal-body"><p data-dialog-message></p><label class="form-label w-100" data-dialog-field hidden><span data-dialog-label></span><input class="form-control" maxlength="200" data-dialog-input /></label><p class="text-danger" role="alert" data-dialog-error hidden></p></div>
|
||||
<div class="modal-footer" data-dialog-actions></div>
|
||||
</div></div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@ -155,7 +155,7 @@
|
||||
|
||||
}
|
||||
</head>
|
||||
<body data-desktop-eligible="@(isApplication && appNavigation.Project is not null && appNavigation.Books.Count > 0 ? "true" : "false")" data-desktop-user="@(isApplication ? userId : null)" class="@(User.Identity?.IsAuthenticated == true && !isMarketingPage ? "app-layout" : null)">
|
||||
<body data-pd-project-id="@appNavigation.Project?.ProjectID" data-pd-scene-id="@(ViewContext.RouteData.Values["controller"]?.ToString() == "Scenes" ? ViewContext.RouteData.Values["id"] : null)" data-pd-user-id="@userId" data-desktop-eligible="@(isApplication && appNavigation.Project is not null && appNavigation.Books.Count > 0 ? "true" : "false")" data-desktop-user="@(isApplication ? userId : null)" class="@(User.Identity?.IsAuthenticated == true && !isMarketingPage ? "app-layout" : null)">
|
||||
<header class="@(isApplication ? "pd-application-header" : null)">
|
||||
@if (User.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
@ -343,6 +343,8 @@
|
||||
{
|
||||
<script src="https://cdn.jsdelivr.net/npm/@@microsoft/signalr@8.0.7/dist/browser/signalr.min.js"></script>
|
||||
}
|
||||
<script src="~/js/application-dialogs.js" asp-append-version="true"></script>
|
||||
<script src="~/js/workspace-bridge.js" asp-append-version="true"></script>
|
||||
<script src="~/js/site.js" asp-append-version="true"></script>
|
||||
@if (User.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
|
||||
34
PlotLine/Views/Shared/_WorkspaceLayout.cshtml
Normal file
34
PlotLine/Views/Shared/_WorkspaceLayout.cshtml
Normal file
@ -0,0 +1,34 @@
|
||||
@using System.Security.Claims
|
||||
@inject ApplicationNavigation Navigation
|
||||
@inject PlotLine.Data.IAppearanceRepository AppearancePreferences
|
||||
@{
|
||||
var userID = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
var appearance = await AppearancePreferences.GetAsync(userID);
|
||||
ViewData["ApplicationAppearance"] = appearance;
|
||||
var theme = appearance.ThemeKey ?? ApplicationAppearance.DefaultTheme;
|
||||
var tone = theme.EndsWith("-dark") ? "dark" : "light";
|
||||
var navigation = await Navigation.BuildAsync(ViewData.Model, "Maps", Context.Request);
|
||||
}
|
||||
<!doctype html>
|
||||
<html lang="en" data-workspace-detached="true" data-app-theme="@theme" data-bs-theme="@tone" data-theme="@tone">
|
||||
<head>
|
||||
<meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>@ViewData["Title"] · PlotDirector</title>
|
||||
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
|
||||
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
|
||||
<link rel="stylesheet" href="~/css/plotline-theme.css" asp-append-version="true" />
|
||||
<link rel="stylesheet" href="~/css/application-shell.css" asp-append-version="true" />
|
||||
<link rel="stylesheet" href="~/css/application-context-menu.css" asp-append-version="true" />
|
||||
<link rel="stylesheet" href="~/css/workspace-surface.css" asp-append-version="true" />
|
||||
</head>
|
||||
<body class="app-layout pd-detached-shell" data-pd-user-id="@User.FindFirstValue(ClaimTypes.NameIdentifier)" data-pd-project-id="@navigation.Project?.ProjectID">
|
||||
<div class="pd-workspace-command-catalog" aria-hidden="true"><partial name="_ApplicationShell" model="navigation" /></div>
|
||||
<main>@RenderBody()</main>
|
||||
<partial name="_ConfirmationDialog" />
|
||||
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script src="~/js/application-dialogs.js" asp-append-version="true"></script>
|
||||
<script src="~/js/workspace-bridge.js" asp-append-version="true"></script>
|
||||
<script src="~/js/application-context-menu.js" asp-append-version="true"></script>
|
||||
@await RenderSectionAsync("Scripts", required:false)
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because one or more lines are too long
1
PlotLine/wwwroot/css/workspace-surface.css
Normal file
1
PlotLine/wwwroot/css/workspace-surface.css
Normal file
@ -0,0 +1 @@
|
||||
.pd-workspace-maximised{position:fixed!important;inset:4px!important;margin:0!important;width:auto!important;height:auto!important;max-width:none!important;z-index:1040!important}html:not([data-standalone=true]):has(.pd-workspace-maximised) .pd-application-header{visibility:hidden}.pd-workspace-maximised:focus{outline:none}html[data-standalone=true] .pd-workspace-maximised.rw-app{top:var(--rw-ribbon-bottom,4px)!important;z-index:1010!important}.pd-detached-shell{margin:0;padding:4px;min-height:100dvh}.pd-detached-shell .maps-app{height:calc(100dvh - 8px)!important;min-height:350px}.pd-detached-shell .maps-toolbar{display:flex!important}.pd-detached-shell .maps-story-toolbar:not([hidden]){display:flex!important}.pd-detached-shell #mapsMaximise,.pd-detached-shell #mapsDetach{display:none!important}.pd-workspace-command-catalog{display:none!important}
|
||||
@ -1,11 +1,13 @@
|
||||
/* PWA command surface only. Availability, execution and confirmations belong to
|
||||
original controls. Discovery is bounded to the declared object / active ribbon. */
|
||||
/* Canonical context commands for the PWA shell and explicitly opted-in workspaces.
|
||||
Original controls/providers own availability, execution and confirmations. */
|
||||
(() => {
|
||||
const shell = document.querySelector('[data-ribbon-shell]');
|
||||
if (!shell) return;
|
||||
const semantic = window.PlotDirectorCommands;
|
||||
const icons = shell.querySelector('[data-pwa-icon-catalog]')?.content;
|
||||
const boundary = '[data-pd-context]';
|
||||
const providers=window.PlotDirectorContextProviders||[];window.PlotDirectorContextProviders=providers;
|
||||
window.PlotDirectorContextMenus={register(selector,provider){providers.push({selector,provider});},open:(target)=>open(target,0,0,true)};
|
||||
let popup = null, child = null, owner = null, invoker = null, pointerType = '', sequence = 0;
|
||||
const create = (tag, attributes = {}, text = '') => {
|
||||
const node = document.createElement(tag);
|
||||
@ -175,9 +177,12 @@
|
||||
function open(target, x, y, keyboard) {
|
||||
const start = performance.now(); close();
|
||||
const region = target.closest(boundary);
|
||||
const editing = editingCommands(target);
|
||||
let editing = editingCommands(target);
|
||||
invoker = target.closest('input,textarea,select,button,a,[tabindex]') || region?.querySelector('a[href],button:not(:disabled),[tabindex]') || document.activeElement;
|
||||
const commands = region ? objectCommands(region) : [];
|
||||
const provider=providers.find(p=>target.closest(p.selector));
|
||||
const supplied=provider?.provider(target);if(supplied)editing=[];
|
||||
if(supplied?.invoker)invoker=supplied.invoker;
|
||||
const commands = supplied?.commands || (region ? objectCommands(region) : []);
|
||||
if (!region && !editing.length) {
|
||||
const control = target.closest('a,button'); if (control) commands.push(...commandsFor([control]));
|
||||
}
|
||||
@ -198,13 +203,13 @@
|
||||
}
|
||||
document.addEventListener('contextmenu', event => {
|
||||
// Absolute escape hatch: do not invoke selection, menu composition or preventDefault.
|
||||
if (event.ctrlKey || !window.PlotDirectorPwa?.standalone || event.pointerType === 'touch' || pointerType === 'touch') return;
|
||||
if (event.ctrlKey || (!window.PlotDirectorPwa?.standalone&&!event.target.closest?.('[data-pd-context-web]')) || event.pointerType === 'touch' || pointerType === 'touch') return;
|
||||
const target = event.target instanceof Element ? event.target : event.target.parentElement;
|
||||
if (target.closest('.pd-context-popup')) { event.preventDefault(); return; }
|
||||
event.preventDefault(); open(target, event.clientX, event.clientY, event.clientX === 0 && event.clientY === 0);
|
||||
});
|
||||
document.addEventListener('keydown', event => {
|
||||
if (!window.PlotDirectorPwa?.standalone || event.ctrlKey) return;
|
||||
if ((!window.PlotDirectorPwa?.standalone&&!document.activeElement?.closest('[data-pd-context-web]')) || event.ctrlKey) return;
|
||||
if (event.key === 'ContextMenu' || (event.shiftKey && event.key === 'F10')) {
|
||||
event.preventDefault(); const target = document.activeElement;
|
||||
if (target instanceof Element) open(target, 0, 0, true);
|
||||
|
||||
15
PlotLine/wwwroot/js/application-dialogs.js
Normal file
15
PlotLine/wwwroot/js/application-dialogs.js
Normal file
@ -0,0 +1,15 @@
|
||||
(() => {
|
||||
if(window.PlotDirectorDialogs)return;
|
||||
let pending=null;
|
||||
window.PlotDirectorDialogs={choose(options){
|
||||
if(pending)return pending;
|
||||
const template=document.getElementById('pdApplicationDialogTemplate');if(!template||!window.bootstrap?.Modal)return Promise.resolve(null);
|
||||
const node=template.content.firstElementChild.cloneNode(true),id='pdApplicationDialog';node.classList.remove('fade');node.id=id;node.setAttribute('aria-labelledby',id+'Title');node.querySelector('[data-dialog-title]').id=id+'Title';node.querySelector('[data-dialog-title]').textContent=options.title;node.querySelector('[data-dialog-message]').textContent=options.message;
|
||||
if(options.input){node.querySelector('[data-dialog-field]').hidden=false;node.querySelector('[data-dialog-label]').textContent=options.input.label;node.querySelector('[data-dialog-input]').value=options.input.value||'';}
|
||||
const previousFocus=document.activeElement;let result=null,working=false;document.body.append(node);const modal=new bootstrap.Modal(node,{backdrop:'static',keyboard:true});
|
||||
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.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;
|
||||
}};
|
||||
})();
|
||||
@ -119,5 +119,15 @@
|
||||
result.forEach(f=>{if(movable(f)){f.isPlaced=true;if(!anchored.has(f.featureID)){f.x=Math.round(f.x*100)/100;f.y=Math.round(f.y*100)/100;}}});
|
||||
return {features:result,warnings};
|
||||
}
|
||||
return {library,directions,distances,copy,geometry,makeFeature,localToWorld,pathPoints,curve,coastline,suggestedDirection,arrange};
|
||||
function transformEndpoint(feature,index,point,features){
|
||||
const f=copy(feature),points=pathPoints(f,features),last=points.length-1;
|
||||
if(f.geometryClass!=='Path'||![0,last].includes(index)||(index===0?f.startFeatureID:f.endFeatureID))return f;
|
||||
const fixed=points[index===0?last:0],moving=points[index],oldLength=Math.hypot(moving[0]-fixed[0],moving[1]-fixed[1]);
|
||||
const nextLength=Math.hypot(point[0]-fixed[0],point[1]-fixed[1]);if(oldLength<.01||nextLength<10)return f;
|
||||
const angle=Math.atan2(point[1]-fixed[1],point[0]-fixed[0])-Math.atan2(moving[1]-fixed[1],moving[0]-fixed[0]),ratio=nextLength/oldLength;
|
||||
const x=f.x-fixed[0],y=f.y-fixed[1];f.x=fixed[0]+(x*Math.cos(angle)-y*Math.sin(angle))*ratio;f.y=fixed[1]+(x*Math.sin(angle)+y*Math.cos(angle))*ratio;
|
||||
f.width*=ratio;f.height*=ratio;f.rotation=normalAngle(f.rotation+angle*180/Math.PI);return f;
|
||||
}
|
||||
const normalAngle=value=>((value+180)%360+360)%360-180;
|
||||
return {transformEndpoint,normalAngle,library,directions,distances,copy,geometry,makeFeature,localToWorld,pathPoints,curve,coastline,suggestedDirection,arrange};
|
||||
});
|
||||
|
||||
@ -12,7 +12,8 @@
|
||||
const active=()=>W.mode==='story';
|
||||
const sceneLabel=s=>`${s.bookTitle} · Ch ${s.chapterNumber} · ${s.sceneNumber}: ${s.sceneTitle}`;
|
||||
const dateLabel=s=>s?.timePrecision?`${s.startDateTime.replace('T',' ').slice(0,s.timePrecision==='Day'?10:16)}${s.timePrecision==='Day'?' (date only)':''}`:s?.relativeTimeText||'Story time unknown';
|
||||
const mapURL=id=>`/Maps?projectId=${boot.projectId}&id=${id}&mode=story${state.sceneID?'&sceneId='+state.sceneID:''}${data?.scenarioID?'&scenarioId='+data.scenarioID:''}`;
|
||||
const windowParams=new URLSearchParams(location.search),detachedQuery=windowParams.get('detached')==='true'?'&detached=true'+(windowParams.get('workspace')?'&workspace='+encodeURIComponent(windowParams.get('workspace')):''):'';
|
||||
const mapURL=id=>`/Maps?projectId=${boot.projectId}&id=${id}&mode=story${state.sceneID?'&sceneId='+state.sceneID:''}${data?.scenarioID?'&scenarioId='+data.scenarioID:''}${detachedQuery}`;
|
||||
const stopDate=(scene,characterID)=>{const stop=data?.stops.find(s=>s.sceneID===scene.sceneID&&s.characterID===characterID);return stop?.timePrecision&&stop.observedAt?dateLabel({...scene,startDateTime:stop.observedAt,timePrecision:stop.timePrecision}):'Appearance time unknown';};
|
||||
function floorPlanURL(id,scene=scenes.get(state.sceneID)){return `/FloorPlans/Edit/${id}${active()&&scene?.floorPlanID===id?`?storySceneId=${scene.sceneID}&storyMapId=${W.document.map.mapID}${data?.scenarioID?'&storyScenarioId='+data.scenarioID:''}`:''}`;}
|
||||
const sceneLink=s=>`<a href="/Scenes/Edit/${s.sceneID}">Open / edit scene</a>`;
|
||||
@ -23,7 +24,7 @@
|
||||
const params=new URLSearchParams(location.search);if(!initialContextApplied&¶ms.has('sceneId')&&scenes.has(Number(params.get('sceneId')))){state.sceneID=Number(params.get('sceneId'));state.lens='scene';state.selection={kind:'scene',sceneID:state.sceneID};}initialContextApplied=true;
|
||||
$('mapStoryScenario').innerHTML=option(0,'Canonical manuscript')+data.scenarios.map(s=>option(s.scenarioID,s.scenarioName)).join('');$('mapStoryScenario').value=String(data.scenarioID||0);state.scenarioID=data.scenarioID||0;
|
||||
$('mapStoryBook').innerHTML=option(0,'All books')+[...new Map(data.scenes.map(s=>[s.bookID,s.bookTitle])).entries()].map(([id,name])=>option(id,name)).join('');$('mapStoryBook').value=String(state.bookID);
|
||||
for(let i=1;i<=3;i++){$('mapStoryCharacter'+i).innerHTML=option(0,i===1?'Choose character':'None')+data.characters.map(c=>option(c.characterID,c.name)).join('');$('mapStoryCharacter'+i).value=String(state.characterIDs[i-1]||0);$('mapStoryPlot'+i).innerHTML=option(0,i===1?'All Plot Lines':'None')+data.plotLines.map(p=>option(p.plotLineID,p.plotLineName)).join('');$('mapStoryPlot'+i).value=String(state.plotIDs[i-1]||0);}
|
||||
for(let i=1;i<=3;i++){$('mapStoryCharacter'+i).innerHTML=option(0,i===1?'Choose character':'None')+[...data.characters].sort((a,b)=>a.name.localeCompare(b.name,undefined,{sensitivity:'base'})||a.characterID-b.characterID).map(c=>option(c.characterID,c.name)).join('');$('mapStoryCharacter'+i).value=String(state.characterIDs[i-1]||0);$('mapStoryPlot'+i).innerHTML=option(0,i===1?'All Plot Lines':'None')+data.plotLines.map(p=>option(p.plotLineID,p.plotLineName)).join('');$('mapStoryPlot'+i).value=String(state.plotIDs[i-1]||0);}
|
||||
$('mapStoryLens').value=state.lens;scopeOptions();
|
||||
}
|
||||
function scopeOptions(){
|
||||
@ -60,7 +61,7 @@
|
||||
}
|
||||
function visibleScenes(){return data?E.filterScenes(data,state):[];}
|
||||
function refresh(){
|
||||
controls();if(!active()){layer.toggleAttribute('hidden',true);document.querySelectorAll('.map-story-muted').forEach(n=>n.classList.remove('map-story-muted'));return;}
|
||||
controls();$('mapStoryScrubberRow').hidden=!active()||!data||state.lens!=='scene';if(!active()){layer.toggleAttribute('hidden',true);document.querySelectorAll('.map-story-muted').forEach(n=>n.classList.remove('map-story-muted'));return;}
|
||||
$('mapsStory').hidden=false;
|
||||
if(!data){$('mapsStory').textContent=loading?'Loading manuscript geography…':error||'Choose Refresh story to load manuscript geography.';layer.toggleAttribute('hidden',true);$('mapsDetailContent').innerHTML=`<div class="maps-story-details"><p>${esc(loading?'Loading canonical story data…':error||'No story projection loaded.')}</p></div>`;return;}
|
||||
const selected=visibleScenes();if(state.lens==='scene'&&!selected.some(s=>s.sceneID===state.sceneID)){state.sceneID=selected[0]?.sceneID||0;$('mapStoryScene').value=String(state.sceneID);state.selection={kind:'overview'};}const mapped=selected.filter(s=>E.mapped(s.position)).length,unmapped=selected.filter(s=>s.position.status==='Unmapped').length,missing=selected.filter(s=>!s.primaryLocationID).length;
|
||||
@ -69,7 +70,12 @@
|
||||
if(state.lens==='time'){$('mapsStory').textContent=`Time · ${state.at?state.at.replace('T',' '):'No confirmed dated events'} · Last known Locations only. Positions between scenes are not established.`;}
|
||||
const sequence=state.lens==='time'?E.timeEvents(data,state.bookID):selected,index=state.lens==='time'?sequence.findIndex(s=>s.startDateTime===state.at):sequence.findIndex(s=>s.sceneID===state.sceneID);
|
||||
$('mapStoryPrevious').disabled=index<=0;$('mapStoryNext').disabled=index<0||index>=sequence.length-1;
|
||||
const current=scenes.get(state.sceneID),scrubber=$('mapStoryScrubber');scrubber.max=String(Math.max(0,selected.length-1));scrubber.value=String(Math.max(0,index));scrubber.disabled=!selected.length;
|
||||
const context=current?`${index+1} / ${selected.length} · Ch ${current.chapterNumber} · ${current.position.locationName||'No Location'} · ${current.position.status}`:'No scenes in this scope';scrubber.setAttribute('aria-valuetext',context);$('mapStoryScrubberContext').textContent=context;
|
||||
$('mapStoryCoverage').hidden=!unmapped;$('mapStoryCoverage').title='Story Mode can only place scenes whose Locations are represented on this map.';
|
||||
if(mapped<selected.length&&state.lens!=='time')$('mapsStory').textContent+=' Story Mode can only place scenes whose Locations are represented on this map.';
|
||||
redraw();renderDetails(W.selected[0]);remember();
|
||||
if(active())window.dispatchEvent(new CustomEvent('pd-map-story-state',{detail:{...state,selection:undefined,mapID:W.document.map.mapID}}));
|
||||
}
|
||||
function position(f){return [f.x,f.y];}
|
||||
function redraw(){
|
||||
@ -128,7 +134,7 @@
|
||||
if(!html&&state.lens==='time'){const positions=E.timePositions(data,state.at,state.characterIDs,state.bookID);html='<h3>Last known geography</h3><p>Confirmed dated evidence only. No positions are interpolated between scenes. Date-only appearances cannot establish an intraday position. Undated / estimated appearances are not positioned in time.</p>'+(!state.at?'<p>No confirmed dated events in this scope.</p>':`<p>As of ${esc(state.at.replace('T',' '))}. ${state.characterIDs.length?'Selected characters':'Markers show up to eight significant characters; the list includes everyone'}.</p>`)+positions.map(p=>`<h4>${esc(p.character.name)}</h4><p>${p.position?'Last known: '+esc(p.position.locationName)+' · '+esc(p.position.status):'Unknown'}${p.scene?' · '+esc(dateLabel(p.scene)):''}</p><p class="maps-hint">${esc(p.reason)}</p>${p.scene?sceneButton(p.scene,'Inspect evidence: '+p.scene.sceneTitle):''}${p.position?locationLinks(p.position,p.scene):''}`).join('');}
|
||||
if(!html&&state.lens==='scene'){const s=scenes.get(state.sceneID);html=s?sceneDetails(s):'<p>No scenes in this scope.</p>';}
|
||||
if(!html)html=overviewDetails(selected);
|
||||
$('mapsDetailContent').innerHTML=`<div class="maps-story-details">${html}</div>`;return true;
|
||||
const pane=$('mapsDetails'),scroll=pane.scrollTop;$('mapsDetailContent').innerHTML=`<div class="maps-story-details">${html}</div>`;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 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);}
|
||||
@ -162,9 +168,30 @@
|
||||
if(!response.ok||response.redirected)throw Error('Travel context could not be saved. Check access/subscription, then try again.');await load(true);
|
||||
}catch(error){const message=document.createElement('p');message.setAttribute('role','alert');message.textContent=error.message;e.target.append(message);}finally{button.disabled=false;}
|
||||
});
|
||||
let scrubFrame=null,scrubValue=0;
|
||||
function scrub(){scrubFrame=null;const s=visibleScenes()[scrubValue];if(s)chooseScene(s.sceneID);}
|
||||
$('mapStoryScrubber').addEventListener('input',e=>{scrubValue=Number(e.target.value);if(!scrubFrame)scrubFrame=requestAnimationFrame(scrub);});
|
||||
$('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-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};
|
||||
window.addEventListener('pd-workspace-message',async e=>{
|
||||
if(!['story-state','scene-selected'].includes(e.detail.type)||W.dirty)return;const incoming=e.detail.payload;
|
||||
if(incoming.mapID&&incoming.mapID!==W.document?.map.mapID)return;
|
||||
window.PlotDirectorWorkspaceBridge?.pause();
|
||||
try{W.setMode('story');if(!data)await load();if(!data)return;if(Number(incoming.scenarioID||0)!==Number(data.scenarioID||0)){if(incoming.scenarioID&&!data.scenarios.some(s=>s.scenarioID===incoming.scenarioID))return;state.scenarioID=Number(incoming.scenarioID)||0;await load(true);if(!data)return;}
|
||||
if(incoming.lens&&['overview','scene','character','chapter','plot','time'].includes(incoming.lens)){state.lens=incoming.lens;$('mapStoryLens').value=state.lens;}
|
||||
if(Array.isArray(incoming.characterIDs)){state.characterIDs=incoming.characterIDs.filter(id=>people.has(id)).slice(0,3);for(let i=1;i<=3;i++)$('mapStoryCharacter'+i).value=String(state.characterIDs[i-1]||0);}
|
||||
if(Number.isSafeInteger(incoming.bookID)&&data.scenes.some(s=>s.bookID===incoming.bookID))state.bookID=incoming.bookID;else state.bookID=0;$('mapStoryBook').value=String(state.bookID);scopeOptions();
|
||||
if(Array.isArray(incoming.plotIDs)){state.plotIDs=incoming.plotIDs.filter(id=>data.plotLines.some(p=>p.plotLineID===id)).slice(0,3);for(let i=1;i<=3;i++)$('mapStoryPlot'+i).value=String(state.plotIDs[i-1]||0);}
|
||||
state.chapterID=data.scenes.some(s=>s.chapterID===incoming.chapterID)?incoming.chapterID:0;$('mapStoryChapter').value=String(state.chapterID);
|
||||
if(['all','mapped','unmapped','missing','elsewhere'].includes(incoming.mapping))state.mapping=incoming.mapping;if(['all','planning','established'].includes(incoming.planning))state.planning=incoming.planning;
|
||||
if(typeof incoming.visible==='boolean')state.visible=incoming.visible;if(E.timeEvents(data,state.bookID).some(s=>s.startDateTime===incoming.at))state.at=incoming.at;$('mapStoryTime').value=state.at;
|
||||
$('mapStoryMapping').value=state.mapping;$('mapStoryPlanning').value=state.planning;
|
||||
if(scenes.has(incoming.sceneID)){if(e.detail.type==='scene-selected'){state.bookID=0;$('mapStoryBook').value='0';state.mapping='all';state.planning='all';$('mapStoryMapping').value='all';$('mapStoryPlanning').value='all';state.lens='scene';$('mapStoryLens').value='scene';scopeOptions();}if(state.lens==='scene')chooseScene(incoming.sceneID);else{state.sceneID=incoming.sceneID;state.selection={kind:'overview'};refresh();}}else refresh();
|
||||
}finally{window.PlotDirectorWorkspaceBridge?.resume();}
|
||||
});
|
||||
controls();if(new URLSearchParams(location.search).get('mode')==='story')W.setMode('story');
|
||||
})();
|
||||
|
||||
58
PlotLine/wwwroot/js/maps-symbols.js
Normal file
58
PlotLine/wwwroot/js/maps-symbols.js
Normal file
@ -0,0 +1,58 @@
|
||||
/* One semantic vector vocabulary for palette previews and map markers. */
|
||||
(function(root,factory){const api=factory();if(typeof module==='object'&&module.exports)module.exports=api;else root.PlotDirectorMapSymbols=api;})(globalThis,()=>{
|
||||
const path=d=>`<path d="${d}"/>`,rect=(x,y,w,h)=>`<rect x="${x}" y="${y}" width="${w}" height="${h}"/>`,circle=(x,y,r)=>`<circle cx="${x}" cy="${y}" r="${r}"/>`;
|
||||
const house=(x,y,w=8,h=8)=>path(`M${x} ${y+3}l${w/2}-${3} ${w/2} 3v${h-3}h-${w}z M${x+w/2} ${y+h}v-3`),pine=(x,y,h=10)=>path(`M${x} ${y}l-4 ${h-3}h8z M${x} ${y+h-3}v3`),water=path('M3 17q3-3 6 0t6 0t6 0 M3 21q3-3 6 0t6 0t6 0');
|
||||
const shapes={
|
||||
Capital:house(3,12,7,8)+house(13,12,8,8)+path('M7 4l2 2 3-4 3 4 2-2v5H7z'),
|
||||
City:rect(2,10,5,12)+rect(9,3,6,19)+rect(17,7,5,15)+path('M4 13h1m6-7h2m-2 4h2m-2 4h2m6-4h1'),
|
||||
Town:house(2,10,9,11)+house(13,6,9,15)+path('M16 11h3'),Village:house(2,12,8,9)+house(13,12,8,9)+house(8,3,8,8),Hamlet:house(3,11,8,10)+house(15,14,6,7),Settlement:house(6,8,12,13)+path('M2 22h20'),
|
||||
House:house(3,4,18,17)+path('M6 12h3m6 0h3'),Cottage:house(3,9,18,12)+path('M2 12q10-14 20 0 M17 8V3'),Farm:house(2,9,13,12)+path('M17 21V6q3-4 5 0v15 M2 23h20'),
|
||||
Manor:house(3,4,18,17)+path('M7 10v5m5-5v5m5-5v5 M2 22h20'),Palace:rect(3,9,18,12)+path('M2 9l10-7 10 7 M6 11v8m6-8v8m6-8v8 M1 22h22'),
|
||||
Castle:path('M2 21V6h3v3h3V6h3v15 M13 21V6h3v3h3V6h3v15 M10 13h4 M10 21v-5h4v5 M4 3v3m16-3v3'),
|
||||
Fortress:path('M3 3h5v4h8V3h5v5h-4v8h4v5h-5v-4H8v4H3v-5h4V8H3z'),Tower:rect(7,7,10,15)+path('M6 7V2h3v3h6V2h3v5 M11 12h2m-2 5h2'),
|
||||
Inn:house(2,9,13,12)+path('M18 3v18 M18 5h4v7h-4 M6 11v4h4v-4'),Ruin:path('M3 21V7l4 3 2-7 4 5v5l4-2 4 4v6 M2 22h20 M6 21v-4m10 4v-4'),
|
||||
Church:path('M2 21V11h5V7l4-5 4 5v14 M15 13l7 4v4 M8 10h6 M11 7v6 M9 21v-5h4v5'),
|
||||
Cathedral:path('M2 21V4h4v5h3V3h6v6h3V4h4v17 M8 21v-7l4-4 4 4v7 M11 4v5m-2-3h6'),
|
||||
Abbey:path('M2 21V7l4-4 4 4v14 M10 12h12v9 M13 21v-5a2 2 0 0 1 4 0v5 M6 6v6m-2-3h4'),
|
||||
Monastery:rect(2,7,20,15)+rect(8,12,8,6)+path('M1 7l11-5 11 5 M5 11v7m14-7v7'),
|
||||
Temple:path('M1 9l11-7 11 7 M3 10h18 M5 11v8m5-8v8m5-8v8m5-8v8 M2 22h20'),
|
||||
Shrine:path('M3 21V8l9-6 9 6v13 M7 21V10h10v11 M11 18l1-5 1 5'),
|
||||
'Sacred site':circle(12,12,8)+path('M12 1v5m0 12v5 M1 12h5m12 0h5 M9 12l3-4 3 4-3 4z'),
|
||||
Monument:path('M9 2h6l2 17H7z M4 19h16v3H4z'),
|
||||
Bridge:path('M1 17h22 M2 17V7m20 10V7 M2 7q10 12 20 0 M6 10v7m6-5v5m6-7v7')+path('M2 21q5-3 10 0t10 0'),
|
||||
Ford:water+path('M3 5h4m3 2h4m3-2h4 M5 2v9m14-9v9'),
|
||||
Port:path('M12 2v16 M8 6h8 M3 12q0 9 9 9t9-9 M3 12l-2 4m2-4 4 2 M21 12l2 4m-2-4-4 2')+circle(12,3,2),
|
||||
Harbour:water+path('M3 14V4h6 M21 14V4h-6 M8 10h8l-2 4h-4z M12 3v7'),
|
||||
Dock:water+path('M3 2v12h18 M3 7h18m-6-5v12m-6-5v5'),
|
||||
Station:rect(5,3,14,16)+rect(8,6,8,5)+path('M8 19l-3 4m11-4 3 4 M8 15h1m6 0h1'),
|
||||
Crossroads:path('M2 7h5V2h10v5h5v10h-5v5H7v-5H2z M10 2v6m0 8v6 M2 12h5m10 0h5'),
|
||||
Gate:path('M2 22V3h5v19 M17 22V3h5v19 M7 9q5-8 10 0 M9 10v11m3-13v13m3-11v11'),
|
||||
Airport:path('M12 1l2 8 9 5v3l-9-3v6l3 2H7l3-2v-6l-9 3v-3l9-5z'),
|
||||
Peak:path('M2 21L12 2l10 19z M8 9l4 2 4-2'),Cave:path('M2 21L7 5h10l5 16 M7 21v-7q5-9 10 0v7'),
|
||||
Waterfall:path('M2 5h11v15 M9 5v16m8-11v11 M2 10h4 M2 22h20 M18 4l3 3-3 3'),Spring:water+path('M7 14q-3-8 5-12 8 4 5 12 M10 12l2-6 2 6'),
|
||||
Volcano:path('M2 22l6-14h8l6 14 M8 8l4 3 4-3 M7 2l3 3m7-3-3 3 M11 1v3'),
|
||||
'Significant tree':path('M12 23v-9 M7 17q-9-1-4-8-1-6 6-5 4-6 8 0 7-1 6 6 5 6-4 7 M8 21h8'),Landmark:path('M6 22V2h13l-3 4 3 4H6 M3 22h6'),
|
||||
Mine:path('M3 22V10l9-7 9 7v12 M7 22v-9h10v9 M7 6l10 10 M4 6q6-6 12 1'),
|
||||
Quarry:path('M2 22l3-7h5l3-6h8 M3 5h8v6H3z M13 22h9v-8h-6v4h-3'),
|
||||
Forge:path('M3 11h18l-4 5h-5v4H6v-4z M8 9l2-6 2 6 M16 8V3'),
|
||||
Factory:path('M2 22V9l7 4V8l7 5V2h5v20 M5 17h3m4 0h3m3 0h1'),
|
||||
Mill:house(5,8,14,14)+circle(12,9,2)+path('M12 7V1m2 8h8 M12 11v9 M10 9H2 M12 7L6 1m8 8 7 7'),
|
||||
Warehouse:path('M2 21V7l10-5 10 5v14 M7 21V11h10v10 M7 15h10m-10 3h10'),
|
||||
Camp:path('M2 21L12 3l10 18z M12 3v18 M6 21l6-9 6 9 M4 2l3 3m13-3-3 3'),Custom:circle(12,12,9)+path('M12 6v12 M6 12h12')
|
||||
};
|
||||
const areas={
|
||||
'Land Mass':path('M2 10l3-5 5 1 4-4 7 5-2 6 3 5-7 4-5-3-6 2-3-6z'),Island:path('M5 10l4-5 6 1 5 7-5 4-7-1z')+water,
|
||||
'Mountain Range':path('M1 21L8 5l5 12 4-8 6 12 M5 12l3 2 3-2'),Hills:path('M1 20q5-15 11 0 M9 20q6-21 14 0'),
|
||||
Forest:pine(6,3,16)+pine(17,6,15),Marsh:water+path('M7 15V4m0 5L3 5m4 2 4-5 M17 16V7m0 4 4-3'),
|
||||
Desert:path('M1 18q7-9 13 0 M10 18q8-9 13 0 M4 5h1m7 1h1m7-3h1'),Plains:path('M1 18h22 M3 14l3-2 3 2m4-4 3-2 3 2 M6 20h12'),
|
||||
Farmland:path('M2 4h20v18H2z M2 10h20 M7 10v12m5-12v12m5-12v12 M4 6h4m6 0h4'),
|
||||
Lake:path('M2 11q4-8 10-6t10 8q-1 9-12 7T2 11z M6 12q3-3 6 0t6 0 M8 16h8')
|
||||
};
|
||||
Object.assign(shapes,areas);
|
||||
const paths={River:['#568ca1','M1 3Q20 6 10 12T23 21',4,''],Stream:['#568ca1','M1 3Q18 7 10 12T23 21',2,''],Canal:['#568ca1','M3 2v7l17 7v6 M7 2v5l17 7v8',1.5,''], 'Major road':['#90714b','M2 22L22 2',5,''],Road:['#90714b','M2 22L22 2',3,''],Track:['#90714b','M2 22L22 2',2,'5 3'],Trail:['#90714b','M2 22L22 2',2,'1 3'],Railway:['#4f625b','M4 22L22 4 M1 19L19 1 M2 15l7 7 M7 10l7 7 M12 5l7 7 M17 0l7 7',1.7,''],'Sea route':['#568ca1','M2 5Q17 4 10 12T22 21',2,'6 3'],Wall:['#6a7362','M2 21V7h4v4h4V7h4v4h4V7h4v14 M2 16h20 M7 16v5m8-5v5',1.5,''],'Mountain ridge':['#737c66','M1 20l4-8 4 5 4-13 4 8 5-6',2,'']};
|
||||
for(const[type,[color,d,width,dash]]of Object.entries(paths))shapes[type]=`<path d="${d}" fill="none" stroke="${color}" stroke-width="${width}" ${dash?`stroke-dasharray="${dash}"`:''}/>`;
|
||||
for(const[type,dash]of Object.entries({Kingdom:'',Province:'6 2',County:'2 2',Territory:'8 2', 'Faction area':'5 2 1 2','Disputed area':'1 3'}))shapes[type]=`<path d="M3 5l9-3 9 6-2 12-11 2-6-8z" fill="#ddd4bb" stroke-dasharray="${dash}"/>`+(type==='Kingdom'?path('M7 13l2 2 3-5 3 5 2-2v6H7z'):type==='Faction area'?path('M9 18V8h7l-2 3 2 3H9'):type==='County'?path('M5 12h14 M12 5v14'):type==='Province'?path('M5 10h13 M10 4v16'):type==='Territory'?path('M7 17l10-9'):path('M5 5l14 14 M19 5L5 19'));
|
||||
const content=type=>shapes[type]||shapes.Custom;
|
||||
const svg=type=>`<svg class="maps-asset-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">${content(type)}</svg>`;
|
||||
return {content,svg,types:Object.keys(shapes)};
|
||||
});
|
||||
@ -3,9 +3,10 @@
|
||||
const E=window.PlotDirectorMaps, boot=JSON.parse(document.getElementById('mapsBootstrap').textContent);
|
||||
const $=id=>document.getElementById(id),app=$('mapsApp'),svg=$('mapsCanvas'),scene=$('mapsScene'),handles=$('mapsHandles');
|
||||
const ns='http://www.w3.org/2000/svg',esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
const guid=()=>crypto.randomUUID(), clone=E.copy;
|
||||
const guid=()=>crypto.randomUUID(), clone=E.copy;const windowParams=new URLSearchParams(location.search),detachedQuery=windowParams.get('detached')==='true'?'&detached=true'+(windowParams.get('workspace')?'&workspace='+encodeURIComponent(windowParams.get('workspace')):''):'';
|
||||
let savedDocument=clone(boot.document),leavePending=null,rotationEdit=null;
|
||||
let doc=boot.document,mode='create',selected=new Set(),pending=null,dirty=false,busy=false,history=[],future=[],preview=null,shapeEdit=false,parentFeature=null;
|
||||
let view={x:-600,y:-400,w:1200,h:800},drag=null,clipboard=null,contextMenu=null;
|
||||
let view={x:-600,y:-400,w:1200,h:800},drag=null,clipboard=null;
|
||||
const hiddenLayers=new Set(),nodes=new Map();
|
||||
const token=document.querySelector('input[name="__RequestVerificationToken"]').value;
|
||||
function status(message,error=false){$('mapsStatus').textContent=message;$('mapsStatus').dataset.error=String(error);}
|
||||
@ -21,13 +22,13 @@
|
||||
if(!response.ok)throw new Error(content?.message||`Could not ${action.toLowerCase()} map (${response.status}). Your edits remain here.`);
|
||||
return content;
|
||||
}
|
||||
async function save(){
|
||||
if(!doc||busy||preview||mode!=='create')return false;
|
||||
async function save(options={}){
|
||||
if(!doc||busy||preview||(mode!=='create'&&!options.forNavigation))return false;
|
||||
busy=true;updateButtons();const sent=snapshot();status('Saving…');
|
||||
try{
|
||||
const saved=await request('Save',JSON.parse(sent),true);
|
||||
// Editing is disabled while saving; server-created Location links become canonical before further edits.
|
||||
doc=saved;dirty=false;
|
||||
doc=saved;savedDocument=clone(saved);dirty=false;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);
|
||||
@ -36,8 +37,29 @@
|
||||
}catch(error){status(error.message,true);return false;}finally{busy=false;updateButtons();}
|
||||
}
|
||||
function safeEdit(action){if(!busy)edit(action);}
|
||||
function url(id){return '/Maps?projectId='+boot.projectId+(id?'&id='+id:'')+(mode==='story'&&id?'&mode=story'+(window.PlotDirectorStoryOverlay?.state.sceneID?'&sceneId='+window.PlotDirectorStoryOverlay.state.sceneID:'')+(window.PlotDirectorStoryOverlay?.data?.scenarioID?'&scenarioId='+window.PlotDirectorStoryOverlay.data.scenarioID:''):'');}
|
||||
function navigate(id){if(dirty&&!confirm('Leave this map and discard unsaved changes?'))return;location.href=url(id);}
|
||||
function url(id){return '/Maps?projectId='+boot.projectId+(id?'&id='+id:'')+(mode==='story'&&id?'&mode=story'+(window.PlotDirectorStoryOverlay?.state.sceneID?'&sceneId='+window.PlotDirectorStoryOverlay.state.sceneID:'')+(window.PlotDirectorStoryOverlay?.data?.scenarioID?'&scenarioId='+window.PlotDirectorStoryOverlay.data.scenarioID:''):'')+detachedQuery;}
|
||||
async function requestLeave(action){
|
||||
if(leavePending||busy)return false;
|
||||
if(!dirty){await action();return true;}
|
||||
leavePending=action;
|
||||
try{
|
||||
const answer=await window.PlotDirectorDialogs.choose({title:'Unsaved map changes',message:"You have changes to this map that haven't been saved. What would you like to do?",actions:[
|
||||
{label:'Save and continue',value:'save',className:'btn-primary',run:()=>save({forNavigation:true})},
|
||||
{label:'Discard changes',value:'discard',className:'btn-outline-danger'},
|
||||
{label:'Keep editing',value:'keep'}]});
|
||||
if(!['save','discard'].includes(answer?.value))return false;
|
||||
if(answer.value==='discard'){doc=clone(savedDocument);dirty=false;history=[];future=[];preview=null;pending=null;selected=new Set([...selected].filter(id=>doc?.features.some(f=>f.featureID===id)));render();details();locations();updateButtons();}
|
||||
await action();return true;
|
||||
}finally{leavePending=null;}
|
||||
}
|
||||
function announceNavigation(destination){const next=new URL(destination,location.href),id=Number(next.searchParams.get('id'));if(next.pathname==='/Maps'&&Number(next.searchParams.get('projectId'))===boot.projectId&&boot.maps.some(m=>m.mapID===id))window.PlotDirectorWorkspaceBridge?.send('map-navigation',{mapID:id,mode:next.searchParams.get('mode')||'create'});}
|
||||
function navigate(id){const destination=url(id);return requestLeave(()=>{announceNavigation(destination);location.href=destination;});}
|
||||
document.addEventListener('click',e=>{
|
||||
if(e.defaultPrevented||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;
|
||||
const link=e.target.closest('a[href]');if(!link||link.hasAttribute('download')||(link.target&&link.target!=='_self'))return;
|
||||
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);
|
||||
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];}
|
||||
@ -57,12 +79,12 @@
|
||||
for(const f of ordered){
|
||||
if(affected&&!affected.has(f.featureID))continue;
|
||||
let g=nodes.get(f.featureID);if(!g){g=svgNode('g',{'data-feature-id':f.featureID,tabindex:'0',role:'button'});nodes.set(f.featureID,g);scene.append(g);}
|
||||
const isSelected=selected.has(f.featureID);g.setAttribute('class',`maps-feature${isSelected?' is-selected':''}${f.isProvisional?' is-provisional':''}`);g.setAttribute('aria-label',`${f.name}, ${f.type}${f.isProvisional?', planning':''}${childIDs.has(f.featureID)?', detailed map available':''}`);g.setAttribute('aria-pressed',String(isSelected));
|
||||
const isSelected=selected.has(f.featureID);g.setAttribute('class',`maps-feature${isSelected?' is-selected':''}${f.isProvisional?' is-provisional':''}${f.isLocked?' is-locked':''}`);g.setAttribute('aria-label',`${f.name}, ${f.type}${f.isProvisional?', planning':''}${childIDs.has(f.featureID)?', detailed map available':''}`);g.setAttribute('aria-pressed',String(isSelected));
|
||||
// Reconcile individual keyed pieces; the shell, canvas, focus and sidebars remain stable.
|
||||
let markup='';
|
||||
if(f.geometryClass==='Marker'){
|
||||
const symbol=E.library.find(a=>a.type===f.type)?.symbol||'◆',size=Math.min(46,Math.max(26,f.width/Math.max(.7,scale)))*scale;
|
||||
markup=`<g transform="translate(${f.x} ${f.y})"><circle class="map-shape" r="${size/2}" fill="#faf5df" stroke="#667d65" stroke-width="${1.5*scale}" vector-effect="non-scaling-stroke"/><text class="map-symbol" style="font-size:${size*.65}px" y="0">${esc(symbol)}</text></g>`;
|
||||
markup=`<g transform="translate(${f.x} ${f.y})"><circle class="map-shape" r="${size/2}" fill="#faf5df" stroke="#667d65" stroke-width="${1.5*scale}" vector-effect="non-scaling-stroke"/><g class="map-symbol" transform="translate(${-size*.39} ${-size*.39}) scale(${size*.78/24})" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">${window.PlotDirectorMapSymbols.content(f.type)}</g></g>`;
|
||||
}else if(f.geometryClass==='Path'){
|
||||
const water=['River','Stream','Canal'].includes(f.type),rail=f.type==='Railway',road=['Road','Major road'].includes(f.type);
|
||||
const d=E.curve(E.pathPoints(f,preview?.features||doc.features)),color=water?'#4c92ae':rail?'#5b635d':f.type==='Sea route'?'#557f94':'#99764b';
|
||||
@ -88,20 +110,23 @@
|
||||
window.PlotDirectorStoryOverlay?.redraw();
|
||||
}
|
||||
function renderHandles(scale){handles.replaceChildren();if(mode!=='create'||preview||selected.size!==1)return;const f=doc.features.find(f=>selected.has(f.featureID));if(!f||f.isLocked)return;
|
||||
const add=(p,type,index)=>handles.append(svgNode('circle',{cx:p[0],cy:p[1],r:6*scale,class:'maps-handle','data-handle':type,'data-index':index??'',tabindex:'0','aria-label':type==='point'?'Move shape point':'Resize selected feature'}));
|
||||
if(shapeEdit&&f.geometryClass!=='Marker'){
|
||||
const pts=E.geometry(f).points||[];pts.forEach((p,i)=>add(E.localToWorld(f,p),'point',i));
|
||||
}else if(f.geometryClass!=='Marker')add(E.localToWorld(f,[.5,.5]),'resize');
|
||||
const add=(p,type,index)=>handles.append(svgNode('circle',{cx:p[0],cy:p[1],r:9*scale,class:'maps-handle','data-handle':type,'data-index':index??'',tabindex:'0',role:'button','aria-label':type==='endpoint'?'Turn and extend path endpoint':type==='point'?'Move shape point':'Resize selected feature'}));
|
||||
const pts=E.geometry(f).points||[];
|
||||
if(f.geometryClass==='Path'){
|
||||
const actual=E.pathPoints(f,doc.features);if(!f.startFeatureID)add(actual[0],'endpoint',0);if(!f.endFeatureID)add(actual.at(-1),'endpoint',pts.length-1);
|
||||
if(shapeEdit)pts.forEach((p,i)=>{if(i>0&&i<pts.length-1)add(E.localToWorld(f,p),'point',i);});
|
||||
}else if(shapeEdit&&f.geometryClass!=='Marker')pts.forEach((p,i)=>add(E.localToWorld(f,p),'point',i));
|
||||
else if(f.geometryClass!=='Marker')add(E.localToWorld(f,[.5,.5]),'resize');
|
||||
}
|
||||
function select(id,extend=false){if(!extend)selected.clear();if(extend&&selected.has(id))selected.delete(id);else selected.add(id);shapeEdit=false;render();details();}
|
||||
function place(type,point,locationID=null){if(!doc||busy||mode!=='create')return;safeEdit(()=>{const f=E.makeFeature(type,point[0],point[1],guid());if(locationID){const l=boot.locations.find(l=>l.locationID===locationID);f.locationID=locationID;f.name=l.locationName;f.isProvisional=false;}doc.features.push(f);selected=new Set([f.featureID]);});pending=null;svg.classList.remove('placing');$('mapName')?.focus();}
|
||||
function place(type,point,locationID=null){if(!doc||busy||mode!=='create')return;safeEdit(()=>{const f=E.makeFeature(type,point[0],point[1],guid());if(locationID){const l=boot.locations.find(l=>l.locationID===locationID);f.locationID=locationID;f.name=l.locationName;f.isProvisional=false;}doc.features.push(f);selected=new Set([f.featureID]);shapeEdit=false;});pending=null;svg.classList.remove('placing');$('mapName')?.focus();}
|
||||
function library(){const categories=[...new Set(E.library.map(a=>a.category))];$('mapsCategory').innerHTML='<option value="">All categories</option>'+categories.map(c=>`<option>${esc(c)}</option>`).join('');
|
||||
for(const layer of ['Terrain','Water','Vegetation','Places','Routes','Regions','Labels']){const label=document.createElement('label');label.innerHTML=`<input type="checkbox" checked data-layer="${layer}" /> ${layer}`;$('mapsLayers').append(label);}assets();}
|
||||
function assets(){const q=$('mapsAssetSearch').value.toLowerCase(),category=$('mapsCategory').value;$('mapsAssets').innerHTML=E.library.filter(a=>(!q||a.type.toLowerCase().includes(q))&&(!category||a.category===category)).map(a=>`<button type="button" draggable="true" data-asset="${esc(a.type)}" title="Place ${esc(a.type)}"><span aria-hidden="true">${esc(a.symbol)}</span>${esc(a.type)}</button>`).join('');}
|
||||
function assets(){const q=$('mapsAssetSearch').value.toLowerCase(),category=$('mapsCategory').value;$('mapsAssets').innerHTML=E.library.filter(a=>(!q||a.type.toLowerCase().includes(q))&&(!category||a.category===category)).map(a=>`<button type="button" draggable="true" data-asset="${esc(a.type)}" title="Place ${esc(a.type)}">${window.PlotDirectorMapSymbols.svg(a.type)}${esc(a.type)}</button>`).join('');}
|
||||
function locations(){if(!doc){$('mapsLocations').textContent='Open a map to place story Locations.';return;}const q=$('mapsLocationSearch').value.toLowerCase(),placed=new Set(doc.features.map(f=>f.locationID));$('mapsLocations').innerHTML=boot.locations.filter(l=>!l.isArchived&&!placed.has(l.locationID)&&l.locationName.toLowerCase().includes(q)).map(l=>`<button type="button" draggable="true" data-location="${l.locationID}">${esc(l.locationName)}</button>`).join('')||'<p class="maps-hint">No unplaced Locations match.</p>';}
|
||||
function crumbs(){const list=[];let current=doc?.map,seen=new Set();while(current&&!seen.has(current.mapID)){seen.add(current.mapID);list.unshift(current);current=boot.maps.find(m=>m.mapID===current.parentMapID);} $('mapsBreadcrumbs').innerHTML=`<a href="${url()}">All maps</a>`+list.map(m=>`<span aria-hidden="true">›</span><a href="${url(m.mapID)}">${esc(m.name)}</a>`).join('');}
|
||||
function option(value,label,selectedValue){return `<option value="${esc(value)}" ${String(value??'')===String(selectedValue??'')?'selected':''}>${esc(label)}</option>`;}
|
||||
function field(label,key,value,type='text',attrs=''){return `<label>${label}<input data-field="${key}" type="${type}" value="${esc(value)}" ${attrs}/></label>`;}
|
||||
function field(label,key,value,type='text',attrs=''){if(['width','height','labelX','labelY'].includes(key)){value=Math.round(value);attrs+=' data-initial-display="'+value+'"';}return `<label>${label}<input data-field="${key}" type="${type}" value="${esc(value)}" ${attrs}/></label>`;}
|
||||
function check(label,key,value){return `<label><input data-field="${key}" type="checkbox" ${value?'checked':''}/> ${label}</label>`;}
|
||||
function details(){
|
||||
const content=$('mapsDetailContent');
|
||||
@ -124,9 +149,9 @@
|
||||
if(linked)html+=`<a href="/Locations/Details/${f.locationID}">Open ${esc(linked.locationName)}</a>`;
|
||||
html+='</details>';
|
||||
if(f.geometryClass!=='Marker'){
|
||||
html+=`<details open><summary>Shape</summary>${field('Width','width',f.width,'number','min="10" max="10000"')}${field('Height','height',f.height,'number','min="10" max="10000"')}${field('Rotate (degrees)','rotation',f.rotation,'number','min="-360" max="360"')}`;
|
||||
html+=`<details open><summary>Shape</summary>${field('Width','width',f.width,'number','min="10" max="10000"')}${field('Height','height',f.height,'number','min="10" max="10000"')}<label>Rotate <span class="maps-rotation"><input aria-label="Rotate" data-rotate type="range" min="-180" max="180" value="${Math.round(E.normalAngle(f.rotation))}" ${f.startFeatureID||f.endFeatureID?'disabled':''}/><input aria-label="Rotation degrees" data-rotate type="number" min="-180" max="180" value="${Math.round(E.normalAngle(f.rotation))}" ${f.startFeatureID||f.endFeatureID?'disabled':''}/><span>°</span><button type="button" data-reset-rotation ${f.startFeatureID||f.endFeatureID?'disabled':''}>Reset</button></span></label>`;
|
||||
if(['Land Mass','Island'].includes(f.type))html+=`<label>Coastline <select data-geometry="coast">${['Gentle','Natural','Rugged','Cliffs','Fjords','Marsh/Delta'].map(c=>option(c,c,E.geometry(f).coast)).join('')}</select></label>`;
|
||||
html+=`<div class="maps-inline"><button type="button" data-action="shape">${shapeEdit?'Finish shape':'Edit shape'}</button><button type="button" data-action="bend">Add ${f.geometryClass==='Path'?'bend':'shape point'}</button></div><p class="maps-hint">Drag the corner to resize, or edit a few shape points.</p></details>`;
|
||||
html+=`<div class="maps-inline"><button type="button" data-action="shape">${shapeEdit?'Finish shape':'Edit shape'}</button><button type="button" data-action="bend">Add ${f.geometryClass==='Path'?'bend':'shape point'}</button></div><p class="maps-hint">${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.'}</p></details>`;
|
||||
}
|
||||
if(f.geometryClass==='Path')html+=`<details open><summary>Connections</summary><p>Endpoints stay attached as places move.</p>${['startFeatureID','endFeatureID'].map((key,i)=>`<label>${i?'End':'Start'} <select data-field="${key}">${option('','Unattached',f[key])}${doc.features.filter(x=>x.geometryClass==='Marker').map(x=>option(x.featureID,x.name,f[key])).join('')}</select></label>`).join('')}</details>`;
|
||||
html+=`<details><summary>Labels & notes</summary>${field('Label across','labelX',f.labelX,'number')}${field('Label down','labelY',f.labelY,'number')}<label>Notes <textarea data-field="notes" maxlength="4000">${esc(f.notes)}</textarea></label></details>`;
|
||||
@ -166,8 +191,9 @@
|
||||
doc.features.push(f);selected=new Set([f.featureID]);
|
||||
});dialog.close();};
|
||||
}
|
||||
async function newMap(feature=null){if(busy)return;if(feature&&dirty&&!(await save()))return;parentFeature=feature?.featureID||null;const form=$('mapsNewForm');form.reset();form.elements.Name.value=feature?feature.name+' detail':'';form.elements.ParentMapID.value=feature?doc.map.mapID:'';$('mapsNewDialog').showModal();}
|
||||
async function createMap(e){e.preventDefault();const values=Object.fromEntries(new FormData(e.target));if(dirty&&!parentFeature&&!confirm('Leave this map and discard unsaved changes?'))return;
|
||||
async function newMap(feature=null){return requestLeave(()=>openNewMap(feature?.featureID));}
|
||||
function openNewMap(featureID){if(busy)return;const feature=doc?.features.find(f=>f.featureID===featureID);if(featureID&&!feature){status('Save this new feature before creating its detailed map.',true);return;}parentFeature=feature?.featureID||null;const form=$('mapsNewForm');form.reset();form.elements.Name.value=feature?feature.name+' detail':'';form.elements.ParentMapID.value=feature?doc.map.mapID:'';$('mapsNewDialog').showModal();}
|
||||
async function createMap(e){e.preventDefault();const values=Object.fromEntries(new FormData(e.target));
|
||||
const data={ProjectID:boot.projectId,Name:values.Name,Kind:values.Kind};if(values.ParentMapID)data.ParentMapID=values.ParentMapID;if(parentFeature)data.ParentFeatureID=parentFeature;
|
||||
const submit=e.target.querySelector('[type=submit]');submit.disabled=true;
|
||||
try{const result=await request('Create',data);let features=[];const add=(type,x,y,w,h)=>{const f=E.makeFeature(type,x,y,guid());f.width=w;f.height=h;features.push(f);};
|
||||
@ -179,16 +205,15 @@
|
||||
function previewArrange(){if(!doc||mode!=='create')return;preview=E.arrange(doc.features,doc.relationships,$('mapsOnlyNew').checked);$('mapsArrangeWarnings').textContent=preview.warnings.length?'Some intentions cannot all be represented exactly: '+preview.warnings.slice(0,5).join('; ')+'. You can still apply and adjust manually.':'Preview ready. Locked pieces and established anchors stay in place.';render();updateButtons();}
|
||||
// Delegated interaction continues to work after the PWA shell moves controls into its ribbon.
|
||||
document.addEventListener('click',e=>{
|
||||
const modeButton=e.target.closest('button[data-mode]');if(modeButton){if(preview)return;mode=modeButton.dataset.mode;app.dataset.mode=mode;for(const id of ['mapsSave','mapsUndo','mapsRedo','mapsArrange'])$(id).hidden=mode!=='create';document.querySelectorAll('button[data-mode]').forEach(b=>b.setAttribute('aria-pressed',String(b===modeButton)));$('mapsStory').hidden=mode!=='story';pending=null;svg.classList.remove('placing');render();details();updateButtons();window.dispatchEvent(new CustomEvent('pd-map-mode',{detail:mode}));return;}
|
||||
const modeButton=e.target.closest('button[data-mode]');if(modeButton){if(preview)return;if(modeButton.dataset.mode==='story'&&dirty){requestLeave(()=>modeButton.click());return;}mode=modeButton.dataset.mode;app.dataset.mode=mode;for(const id of ['mapsSave','mapsUndo','mapsRedo','mapsArrange'])$(id).hidden=mode!=='create';document.querySelectorAll('button[data-mode]').forEach(b=>b.setAttribute('aria-pressed',String(b===modeButton)));$('mapsStory').hidden=mode!=='story';pending=null;svg.classList.remove('placing');render();details();updateButtons();window.dispatchEvent(new CustomEvent('pd-map-mode',{detail:mode}));return;}
|
||||
const asset=e.target.closest('[data-asset]'),loc=e.target.closest('[data-location]');if(asset||loc){pending={type:asset?.dataset.asset||'Settlement',locationID:loc?Number(loc.dataset.location):null};svg.classList.add('placing');status('Click the map to place '+(asset?.dataset.asset||'this Location')+'. Escape cancels.');return;}
|
||||
const actionButton=e.target.closest('[data-action]');if(actionButton)action(actionButton.dataset.action);
|
||||
const rel=e.target.closest('[data-edit-rel]');if(rel)relationEditor(rel.dataset.editRel);
|
||||
const removeRel=e.target.closest('[data-remove-rel]');if(removeRel)safeEdit(()=>doc.relationships=doc.relationships.filter(r=>r.relationshipID!==removeRel.dataset.removeRel));
|
||||
const result=e.target.closest('[data-search-feature]');if(result){const f=doc.features.find(f=>f.featureID===result.dataset.searchFeature);select(f.featureID);fit([f]);$('mapsSearchResults').replaceChildren();}
|
||||
if(contextMenu&&!contextMenu.contains(e.target)){contextMenu.remove();contextMenu=null;}
|
||||
});
|
||||
document.addEventListener('change',e=>{
|
||||
if(e.target.matches('[data-field]')){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||busy)return;const key=e.target.dataset.field;let value=e.target.type==='checkbox'?e.target.checked:e.target.type==='number'?Number(e.target.value):e.target.value;if(['locationID','floorPlanID'].includes(key))value=value?Number(value):null;if(['startFeatureID','endFeatureID'].includes(key))value=value||null;if(['width','height'].includes(key)&&(!Number.isFinite(value)||value<1))return;safeEdit(()=>{f[key]=value;if(key==='createLocation'&&value)f.isProvisional=false;if(key==='isProvisional'&&value)f.createLocation=false;if(key==='locationID')f.createLocation=false;});}
|
||||
if(e.target.matches('[data-field]')){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||busy)return;const key=e.target.dataset.field;if(e.target.dataset.initialDisplay===e.target.value)return;let value=e.target.type==='checkbox'?e.target.checked:e.target.type==='number'?Number(e.target.value):e.target.value;if(['locationID','floorPlanID'].includes(key))value=value?Number(value):null;if(['startFeatureID','endFeatureID'].includes(key))value=value||null;if(['width','height'].includes(key)&&(!Number.isFinite(value)||value<1))return;safeEdit(()=>{f[key]=value;if(key==='createLocation'&&value)f.isProvisional=false;if(key==='isProvisional'&&value)f.createLocation=false;if(key==='locationID')f.createLocation=false;});}
|
||||
if(e.target.matches('[data-geometry]')){const f=doc.features.find(f=>selected.has(f.featureID));safeEdit(()=>{const g=E.geometry(f);g[e.target.dataset.geometry]=e.target.value;f.geometryJson=JSON.stringify(g);});}
|
||||
if(e.target.matches('[data-layer]')){if(e.target.checked)hiddenLayers.delete(e.target.dataset.layer);else hiddenLayers.add(e.target.dataset.layer);render();}
|
||||
});
|
||||
@ -197,28 +222,58 @@
|
||||
app.addEventListener('dragstart',e=>{const target=e.target.closest('[data-asset],[data-location]');if(!target)return;e.dataTransfer.setData('application/plotdirector-map',JSON.stringify({type:target.dataset.asset||'Settlement',locationID:Number(target.dataset.location)||null}));e.dataTransfer.effectAllowed='copy';});
|
||||
svg.addEventListener('dragover',e=>e.preventDefault());svg.addEventListener('drop',e=>{e.preventDefault();try{const data=JSON.parse(e.dataTransfer.getData('application/plotdirector-map'));place(data.type,world(e),data.locationID);}catch{status('Choose a map piece from the library.');}});
|
||||
svg.addEventListener('pointerdown',e=>{
|
||||
if(e.button!==0||!doc||busy||preview||e.target.closest('[data-story-key]'))return;contextMenu?.remove();const p=world(e),target=e.target.closest('[data-feature-id]'),handle=e.target.closest('[data-handle]');
|
||||
if(e.button!==0||!doc||busy||preview||e.target.closest('[data-story-key]'))return;const p=world(e),target=e.target.closest('[data-feature-id]'),handle=e.target.closest('[data-handle]');
|
||||
e.preventDefault();window.getSelection()?.removeAllRanges();
|
||||
if(pending){place(pending.type,p,pending.locationID);return;}
|
||||
if(handle){const f=doc.features.find(f=>selected.has(f.featureID));if(!f||mode!=='create')return;checkpoint();drag={kind:handle.dataset.handle,id:f.featureID,index:Number(handle.dataset.index),start:p,original:clone(f),moved:false};}
|
||||
else if(target){const id=target.dataset.featureId;if(!selected.has(id)||e.shiftKey)select(id,e.shiftKey);const f=doc.features.find(f=>f.featureID===id);if(mode==='create'&&!f.isLocked){checkpoint();drag={kind:'move',start:p,originals:clone(doc.features.filter(f=>selected.has(f.featureID)&&!f.isLocked)),moved:false};}}
|
||||
if(handle){const f=doc.features.find(f=>selected.has(f.featureID));if(!f||mode!=='create')return;const redo=future.slice();checkpoint();drag={redo,kind:handle.dataset.handle,id:f.featureID,index:Number(handle.dataset.index),start:p,original:clone(f),moved:false};}
|
||||
else if(target){const id=target.dataset.featureId;if(!selected.has(id)||e.shiftKey)select(id,e.shiftKey);const f=doc.features.find(f=>f.featureID===id);if(mode==='create'&&!f.isLocked){const redo=future.slice();checkpoint();drag={redo,kind:'move',start:p,originals:clone(doc.features.filter(f=>selected.has(f.featureID)&&!f.isLocked)),moved:false};}else drag={kind:'pan',start:p,original:{...view},client:[e.clientX,e.clientY],matrix:svg.getScreenCTM().inverse(),moved:false};}
|
||||
else{if(!e.shiftKey){selected.clear();shapeEdit=false;render();details();}drag={kind:'pan',start:p,original:{...view},client:[e.clientX,e.clientY],matrix:svg.getScreenCTM().inverse(),moved:false};}
|
||||
if(drag)svg.setPointerCapture(e.pointerId);
|
||||
if(drag){svg.classList.add('manipulating');svg.setPointerCapture(e.pointerId);}
|
||||
});
|
||||
svg.addEventListener('pointermove',e=>{if(!drag)return;const p=world(e),dx=p[0]-drag.start[0],dy=p[1]-drag.start[1];if(Math.abs(dx)+Math.abs(dy)>1)drag.moved=true;
|
||||
if(drag.kind==='pan'){view.x=drag.original.x-(e.clientX-drag.client[0])*drag.matrix.a;view.y=drag.original.y-(e.clientY-drag.client[1])*drag.matrix.d;svg.setAttribute('viewBox',`${view.x} ${view.y} ${view.w} ${view.h}`);return;}
|
||||
if(drag.kind==='move'){for(const o of drag.originals){const f=doc.features.find(f=>f.featureID===o.featureID);f.x=o.x+dx;f.y=o.y+dy;f.isPlaced=true;}}
|
||||
else{const f=doc.features.find(f=>f.featureID===drag.id),o=drag.original,a=-o.rotation*Math.PI/180,lx=(p[0]-o.x)*Math.cos(a)-(p[1]-o.y)*Math.sin(a),ly=(p[0]-o.x)*Math.sin(a)+(p[1]-o.y)*Math.cos(a);if(drag.kind==='resize'){f.width=Math.max(20,Math.abs(lx)*2);f.height=Math.max(20,Math.abs(ly)*2);}else{const g=E.geometry(f);g.points[drag.index]=[Math.max(-5,Math.min(5,lx/o.width)),Math.max(-5,Math.min(5,ly/o.height))];f.geometryJson=JSON.stringify(g);}}
|
||||
else{const f=doc.features.find(f=>f.featureID===drag.id),o=drag.original,a=-o.rotation*Math.PI/180,lx=(p[0]-o.x)*Math.cos(a)-(p[1]-o.y)*Math.sin(a),ly=(p[0]-o.x)*Math.sin(a)+(p[1]-o.y)*Math.cos(a);if(drag.kind==='endpoint'){Object.assign(f,E.transformEndpoint(o,drag.index,p,doc.features));}else if(drag.kind==='resize'){f.width=Math.max(20,Math.abs(lx)*2);f.height=Math.max(20,Math.abs(ly)*2);}else{const g=E.geometry(f);g.points[drag.index]=[Math.max(-5,Math.min(5,lx/o.width)),Math.max(-5,Math.min(5,ly/o.height))];f.geometryJson=JSON.stringify(g);}}
|
||||
if(!drag.frame)drag.frame=requestAnimationFrame(()=>{if(!drag)return;drag.frame=null;const moved=new Set(drag.originals?.map(f=>f.featureID)||[drag.id]);for(const f of doc.features)if(moved.has(f.startFeatureID)||moved.has(f.endFeatureID))moved.add(f.featureID);render(moved);});
|
||||
});
|
||||
svg.addEventListener('pointerup',e=>{if(!drag)return;const d=drag;drag=null;if(d.frame)cancelAnimationFrame(d.frame);if(svg.hasPointerCapture(e.pointerId))svg.releasePointerCapture(e.pointerId);if(d.kind!=='pan'){if(d.moved){changed();render();details();}else history.pop();updateButtons();}});
|
||||
svg.addEventListener('pointercancel',()=>{if(drag&&drag.kind!=='pan'&&history.length){doc=JSON.parse(history.pop());render();details();}drag=null;});
|
||||
svg.addEventListener('dblclick',e=>{const id=e.target.closest('[data-feature-id]')?.dataset.featureId;if(!id)return;const child=boot.maps.find(m=>m.parentMapID===doc.map.mapID&&m.parentFeatureID===id);if(child)navigate(child.mapID);else{const f=doc.features.find(f=>f.featureID===id);if(f.floorPlanID&&(!dirty||confirm('Leave and discard unsaved changes?')))location.href=window.PlotDirectorStoryOverlay?.floorPlanURL(f.floorPlanID)||'/FloorPlans/Edit/'+f.floorPlanID;}});
|
||||
svg.addEventListener('pointerup',e=>{if(!drag)return;const d=drag;drag=null;svg.classList.remove('manipulating');if(d.frame)cancelAnimationFrame(d.frame);if(svg.hasPointerCapture(e.pointerId))svg.releasePointerCapture(e.pointerId);if(d.kind!=='pan'){if(d.moved){changed();render();details();}else{history.pop();future=d.redo;}updateButtons();}});
|
||||
function cancelDrag(){svg.classList.remove('manipulating');if(drag&&drag.kind!=='pan'&&history.length){doc=JSON.parse(history.pop());future=drag.redo;render();details();}drag=null;}
|
||||
svg.addEventListener('pointercancel',cancelDrag);svg.addEventListener('lostpointercapture',cancelDrag);
|
||||
svg.addEventListener('dblclick',e=>{const id=e.target.closest('[data-feature-id]')?.dataset.featureId;if(!id)return;const child=boot.maps.find(m=>m.parentMapID===doc.map.mapID&&m.parentFeatureID===id);if(child)navigate(child.mapID);else{const f=doc.features.find(f=>f.featureID===id);if(f.floorPlanID){const destination=window.PlotDirectorStoryOverlay?.floorPlanURL(f.floorPlanID)||'/FloorPlans/Edit/'+f.floorPlanID;requestLeave(()=>{location.href=destination;});}}});
|
||||
svg.addEventListener('wheel',e=>{e.preventDefault();zoom(e.deltaY>0?1.12:1/1.12,world(e));},{passive:false});
|
||||
svg.addEventListener('contextmenu',e=>{e.preventDefault();const id=e.target.closest('[data-feature-id]')?.dataset.featureId;if(!id||mode!=='create')return;select(id);contextMenu?.remove();contextMenu=document.createElement('div');contextMenu.className='maps-context-menu';contextMenu.style.left=Math.min(e.clientX,window.innerWidth-180)+'px';contextMenu.style.top=Math.min(e.clientY,window.innerHeight-170)+'px';contextMenu.innerHTML='<button type="button" data-action="duplicate">Duplicate</button><button type="button" data-action="relationship">Add relationship</button><button type="button" data-action="child">Create detailed map</button><button type="button" data-action="remove">Delete</button>';app.append(contextMenu);});
|
||||
(window.PlotDirectorContextMenus?.register||((selector,provider)=>{(window.PlotDirectorContextProviders||=[]).push({selector,provider});}))('#mapsCanvas',target=>{
|
||||
const id=target.closest('[data-feature-id]')?.dataset.featureId;
|
||||
if(id&&!selected.has(id))select(id);
|
||||
const f=doc?.features.find(f=>f.featureID===id),items=doc?.features.filter(f=>selected.has(f.featureID))||[],commands=[];
|
||||
const add=(label,icon,run,disabled=false)=>commands.push({label,icon,run,disabled});
|
||||
if(!f){add('Fit map','focus',()=>fit());if(mode==='create')add('Paste','paste',()=>duplicate(clipboard),!clipboard?.length);}
|
||||
else{
|
||||
add('Details','details',()=>{$('mapsDetails').scrollIntoView({block:'nearest'});$('mapsDetailContent').querySelector('input,button,a')?.focus();});
|
||||
if(items.length===1){const child=boot.maps.find(m=>m.parentMapID===doc.map.mapID&&m.parentFeatureID===id);
|
||||
if(child)add('Open detailed map','map',()=>navigate(child.mapID));
|
||||
else if(mode==='create')add('Create detailed map','add',()=>newMap(f));
|
||||
if(f.locationID)add('Open Location','locations',()=>requestLeave(()=>{location.href='/Locations/Details/'+f.locationID;}));
|
||||
if(f.floorPlanID)add('Open Floor Plan','floorplans',()=>requestLeave(()=>{location.href=window.PlotDirectorStoryOverlay?.floorPlanURL(f.floorPlanID)||'/FloorPlans/Edit/'+f.floorPlanID;}));
|
||||
if(mode==='create'){add('Add relationship','relationships',()=>action('relationship'));if(f.geometryClass!=='Marker')add('Edit shape / bends','writer',()=>action('shape'),f.isLocked);}
|
||||
}
|
||||
if(mode==='create'){
|
||||
add('Copy','copy',()=>{clipboard=clone(items);});add('Duplicate','copy',()=>duplicate(items));
|
||||
add(items.every(f=>f.isLocked)?'Unlock position':'Lock position',items.every(f=>f.isLocked)?'unlock':'lock',()=>safeEdit(()=>{const locked=items.every(f=>f.isLocked);items.forEach(f=>f.isLocked=!locked);}));
|
||||
add('Mark as unplaced','hide-node',()=>safeEdit(()=>items.filter(f=>!f.isLocked).forEach(f=>f.isPlaced=false)),items.every(f=>f.isLocked));
|
||||
add('Delete','remove',remove,items.every(f=>f.isLocked));
|
||||
}
|
||||
}
|
||||
return {invoker:target.closest('[data-feature-id]')||svg,commands};
|
||||
});
|
||||
$('mapsDetach').hidden=!window.PlotDirectorWorkspaceBridge;
|
||||
$('mapsDetach').onclick=()=>{const destination=new URL(url(doc?.map.mapID),location.href);destination.searchParams.set('mode',mode);if(!window.PlotDirectorWorkspaceBridge?.detach(destination.href))status('The separate window could not open. Allow pop-ups for PlotDirector and try again.',true);};
|
||||
window.addEventListener('pd-workspace-message',e=>{if(e.detail.type==='map-navigation'&&e.detail.payload.mapID!==doc?.map.mapID&&boot.maps.some(m=>m.mapID===e.detail.payload.mapID)){if(dirty){status('The paired window opened another map. Your unsaved map stays open here.');return;}const next=new URL(url(e.detail.payload.mapID),location.href);if(['create','explore','story'].includes(e.detail.payload.mode))next.searchParams.set('mode',e.detail.payload.mode);location.href=next.href;return;}if(e.detail.type==='map-saved'&&e.detail.payload.mapID===doc?.map.mapID&&e.detail.payload.revision!==doc.map.revision)status('This map was saved in another window. Reload before editing further. Your current changes remain here.',true);});
|
||||
$('mapsContext').onclick=()=>window.PlotDirectorContextMenus?.open(nodes.get([...selected][0])||svg);
|
||||
document.addEventListener('keydown',e=>{
|
||||
if(e.defaultPrevented||document.querySelector('.modal.show'))return;
|
||||
if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'&&!e.target.closest('dialog')){e.preventDefault();if(e.target.matches('[data-field]'))e.target.dispatchEvent(new Event('change',{bubbles:true}));save();return;}
|
||||
if(e.target.matches('input,textarea,select')||e.target.isContentEditable)return;
|
||||
if(e.key==='Escape'){if(drag&&drag.kind!=='pan'){doc=JSON.parse(history.pop());drag=null;}pending=null;selected.clear();shapeEdit=false;contextMenu?.remove();svg.classList.remove('placing');render();details();return;}
|
||||
if(e.key==='Escape'){if(!drag&&!pending&&app.classList.contains('maps-maximised'))return;e.preventDefault();svg.classList.remove('manipulating');if(drag&&drag.kind!=='pan'){doc=JSON.parse(history.pop());future=drag.redo;drag=null;}pending=null;selected.clear();shapeEdit=false;svg.classList.remove('placing');render();details();return;}
|
||||
if(e.target.closest('dialog'))return;
|
||||
if(mode!=='create'||busy||preview)return;
|
||||
if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='z'){e.preventDefault();undo(e.shiftKey);}
|
||||
@ -226,29 +281,34 @@
|
||||
if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='c'){clipboard=clone(doc.features.filter(f=>selected.has(f.featureID)));}
|
||||
if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='v'&&clipboard?.length){e.preventDefault();duplicate(clipboard);}
|
||||
if(e.key==='Delete'||e.key==='Backspace'){e.preventDefault();remove();}
|
||||
const handle=e.target.closest('[data-handle]');if(handle&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){e.preventDefault();const f=doc.features.find(f=>selected.has(f.featureID));safeEdit(()=>{if(handle.dataset.handle==='point'){const g=E.geometry(f),p=g.points[Number(handle.dataset.index)],step=e.shiftKey?.05:.01;p[0]+=e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0;p[1]+=e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0;f.geometryJson=JSON.stringify(g);}else{f.width=Math.max(20,f.width+(e.key==='ArrowRight'?10:e.key==='ArrowLeft'?-10:0));f.height=Math.max(20,f.height+(e.key==='ArrowDown'?10:e.key==='ArrowUp'?-10:0));}});return;}
|
||||
const handle=e.target.closest('[data-handle]');if(handle&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){e.preventDefault();const f=doc.features.find(f=>selected.has(f.featureID));safeEdit(()=>{if(handle.dataset.handle==='endpoint'){const i=Number(handle.dataset.index),p=E.pathPoints(f,doc.features)[i],step=e.shiftKey?20:5;p[0]+=e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0;p[1]+=e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0;Object.assign(f,E.transformEndpoint(f,i,p,doc.features));}else if(handle.dataset.handle==='point'){const g=E.geometry(f),p=g.points[Number(handle.dataset.index)],step=e.shiftKey?.05:.01;p[0]+=e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0;p[1]+=e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0;f.geometryJson=JSON.stringify(g);}else{f.width=Math.max(20,f.width+(e.key==='ArrowRight'?10:e.key==='ArrowLeft'?-10:0));f.height=Math.max(20,f.height+(e.key==='ArrowDown'?10:e.key==='ArrowUp'?-10:0));}});return;}
|
||||
const focused=e.target.closest('[data-feature-id]');if(focused&&(e.key==='Enter'||e.key===' ')){e.preventDefault();select(focused.dataset.featureId,e.shiftKey);}
|
||||
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();}}
|
||||
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);});
|
||||
function undo(redo=false){if(busy||preview)return;const from=redo?future:history,to=redo?history:future;if(!from.length)return;to.push(snapshot());doc=JSON.parse(from.pop());selected.clear();changed();render();details();locations();}
|
||||
$('mapsSelectorForm').onsubmit=e=>e.preventDefault();$('mapsSearchForm').onsubmit=e=>e.preventDefault();
|
||||
$('mapsSave').onclick=save;$('mapsUndo').onclick=()=>undo();$('mapsRedo').onclick=()=>undo(true);$('mapsSelect').onchange=e=>navigate(Number(e.target.value));
|
||||
$('mapsSave').onclick=save;$('mapsUndo').onclick=()=>undo();$('mapsRedo').onclick=()=>undo(true);$('mapsSelect').onchange=e=>{const id=Number(e.target.value);e.target.value=doc?.map.mapID||'';navigate(id);};
|
||||
$('mapsDefine').onclick=definePlace;$('mapsNew').onclick=()=>newMap();$('mapsWelcomeNew').onclick=()=>newMap();$('mapsNewCancel').onclick=()=>$('mapsNewDialog').close();$('mapsNewForm').onsubmit=createMap;
|
||||
$('mapsRename').onclick=()=>{if(!doc)return;const name=prompt('Map name',doc.map.name);if(name?.trim())safeEdit(()=>{doc.map.name=name.trim().slice(0,200);crumbs();});};
|
||||
$('mapsDuplicate').onclick=async()=>{if(!doc||busy||preview)return;if(dirty&&!(await save()))return;try{const result=await request('Create',{ProjectID:boot.projectId,Name:doc.map.name+' copy',Kind:doc.map.kind,...(doc.map.parentMapID?{ParentMapID:doc.map.parentMapID}:{})});const d=clone(doc);d.map.mapID=result.id;d.map.name+=' copy';d.map.revision=0;d.features.forEach(f=>f.createLocation=false);await request('Save',d,true);dirty=false;location.href=url(result.id);}catch(error){status(error.message,true);}};
|
||||
$('mapsDelete').onclick=async()=>{if(!doc||busy||preview)return;if(!confirm(`Delete “${doc.map.name}”? Detailed child maps will become top-level maps. Story Locations and Floor Plans are kept.`))return;try{await request('Delete',{projectId:boot.projectId,id:doc.map.mapID,revision:doc.map.revision});dirty=false;location.href=url();}catch(error){status(error.message,true);}};
|
||||
$('mapsRename').onclick=async()=>{if(!doc)return;const answer=await window.PlotDirectorDialogs.choose({title:'Rename map',message:'Choose a name for this map.',input:{label:'Map name',value:doc.map.name},actions:[{label:'Rename',value:'rename',className:'btn-primary'},{label:'Cancel',value:'cancel'}]});if(answer?.value==='rename'&&answer.input.trim())safeEdit(()=>{doc.map.name=answer.input.trim().slice(0,200);crumbs();});};
|
||||
$('mapsDuplicate').onclick=async()=>{if(!doc||busy||preview)return;if(dirty){requestLeave(()=>$('mapsDuplicate').click());return;}try{const result=await request('Create',{ProjectID:boot.projectId,Name:doc.map.name+' copy',Kind:doc.map.kind,...(doc.map.parentMapID?{ParentMapID:doc.map.parentMapID}:{})});const d=clone(doc);d.map.mapID=result.id;d.map.name+=' copy';d.map.revision=0;d.features.forEach(f=>f.createLocation=false);await request('Save',d,true);dirty=false;location.href=url(result.id);}catch(error){status(error.message,true);}};
|
||||
$('mapsDelete').onclick=async()=>{if(!doc||busy||preview)return;const answer=await window.PlotDirectorDialogs.choose({title:'Delete map?',message:`Delete “${doc.map.name}”? Detailed child maps will become top-level maps. Story Locations and Floor Plans are kept.`,actions:[{label:'Delete map',value:'delete',className:'btn-danger'},{label:'Cancel',value:'cancel'}]});if(answer?.value!=='delete')return;try{await request('Delete',{projectId:boot.projectId,id:doc.map.mapID,revision:doc.map.revision});dirty=false;location.href=url();}catch(error){status(error.message,true);}};
|
||||
$('mapsArrange').onclick=()=>{if(!doc||busy||mode!=='create')return;previewArrange();$('mapsArrangeDialog').showModal();};$('mapsOnlyNew').onchange=previewArrange;
|
||||
function cancelArrange(){preview=null;$('mapsArrangeDialog').close();render();updateButtons();}
|
||||
$('mapsArrangeCancel').onclick=cancelArrange;$('mapsArrangeDialog').oncancel=e=>{e.preventDefault();cancelArrange();};
|
||||
$('mapsArrangeApply').onclick=()=>{const result=preview;preview=null;checkpoint();doc.features=result.features;changed(result.warnings.length?'Arrangement applied with observations; you can adjust manually.':'Arrangement applied. You can move any piece afterwards.');$('mapsArrangeDialog').close();render();details();updateButtons();};
|
||||
$('mapsFit').onclick=()=>fit();$('mapsFitSelection').onclick=()=>fit(doc?.features.filter(f=>selected.has(f.featureID)));$('mapsZoomIn').onclick=()=>zoom(1/1.25);$('mapsZoomOut').onclick=()=>zoom(1.25);
|
||||
$('mapsMaximise').onclick=e=>{const active=app.classList.toggle('maps-maximised');e.currentTarget.setAttribute('aria-pressed',String(active));e.currentTarget.textContent=active?'Restore workspace':'Maximise workspace';};
|
||||
window.PlotDirectorWorkspaceSurface.attach(app,$('mapsMaximise'),{className:'maps-maximised'});
|
||||
window.addEventListener('beforeunload',e=>{if(dirty){e.preventDefault();e.returnValue='';}});
|
||||
new ResizeObserver(()=>{const top=app.getBoundingClientRect().top;if(!app.classList.contains('maps-maximised'))app.style.setProperty('--maps-shell-top',Math.max(0,top)+'px');if(doc)render();}).observe(svg);
|
||||
const syncDisplayMode=()=>{$('mapsMaximise').hidden=!!window.PlotDirectorPwa?.standalone;};syncDisplayMode();window.matchMedia('(display-mode: standalone)').addEventListener('change',syncDisplayMode);
|
||||
app.dataset.mode=mode;library();locations();crumbs();details();updateButtons();
|
||||
$('mapsWelcome').hidden=!!doc;svg.style.visibility=doc?'visible':'hidden';$('mapsList').innerHTML=boot.maps.map(m=>`<a href="${url(m.mapID)}">${esc(m.name)} · ${esc(m.kind)}${m.parentMapID?' · detail of '+esc(boot.maps.find(p=>p.mapID===m.parentMapID)?.name||'parent map'):''}</a>`).join('');
|
||||
if(doc)fit();
|
||||
if(doc)fit();if(new URLSearchParams(location.search).get('mode')==='explore')document.querySelector('[data-mode=explore]').click();
|
||||
// Expose semantic operations for browser regression fixtures, never credentials or a bypass.
|
||||
window.PlotDirectorMapWorkspace={get document(){return doc;},get view(){return view;},get mode(){return mode;},get dirty(){return dirty;},get selected(){return [...selected];},setMode(value){document.querySelector(`button[data-mode="${value}"]`)?.click();},refreshDetails:details,clearSelection(){selected.clear();render();details();},focus(id){const f=doc?.features.find(f=>f.featureID===id);if(f){view.x=f.x-view.w/2;view.y=f.y-view.h/2;applyView();}},select,fit,save};
|
||||
window.PlotDirectorMapWorkspace={get document(){return doc;},get view(){return view;},get mode(){return mode;},get dirty(){return dirty;},get selected(){return [...selected];},setMode(value){document.querySelector(`button[data-mode="${value}"]`)?.click();},refreshDetails:details,clearSelection(){selected.clear();render();details();},focus(id){const f=doc?.features.find(f=>f.featureID===id);if(f){view.x=f.x-view.w/2;view.y=f.y-view.h/2;applyView();}},select,fit,save,requestLeave};
|
||||
})();
|
||||
|
||||
@ -23,18 +23,11 @@
|
||||
}
|
||||
document.getElementById('rwMapView').addEventListener('click', () => setView('map'));
|
||||
document.getElementById('rwListView').addEventListener('click', () => setView('list'));
|
||||
document.getElementById('rwMaximise').addEventListener('click', event => {
|
||||
const active = app.classList.toggle('rw-maximised');
|
||||
event.currentTarget.setAttribute('aria-pressed', String(active));
|
||||
event.currentTarget.setAttribute('aria-label', active ? 'Restore workspace' : 'Maximise workspace');
|
||||
event.currentTarget.title = event.currentTarget.getAttribute('aria-label');
|
||||
sizeWorkspace();
|
||||
});
|
||||
window.PlotDirectorWorkspaceSurface.attach(app,document.getElementById('rwMaximise'),{className:'rw-maximised',onChange:sizeWorkspace,allowPwa:true});
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.key === 'Escape' && app.querySelector('.rw-menu[open]')) {
|
||||
const menu = app.querySelector('.rw-menu[open]'); menu.open = false; menu.querySelector('summary').focus(); return;
|
||||
}
|
||||
if (event.key === 'Escape' && app.classList.contains('rw-maximised') && !document.querySelector('dialog[open]')) document.getElementById('rwMaximise').click();
|
||||
});
|
||||
document.addEventListener('click', event => app.querySelectorAll('.rw-menu[open]').forEach(menu => { if (!menu.contains(event.target)) menu.open = false; }));
|
||||
const workspace = window.PlotDirectorRelationshipWorkspace;
|
||||
|
||||
55
PlotLine/wwwroot/js/workspace-bridge.js
Normal file
55
PlotLine/wwwroot/js/workspace-bridge.js
Normal file
@ -0,0 +1,55 @@
|
||||
// Transient paired-window messages only. Server routes remain authoritative for access and writes.
|
||||
(() => {
|
||||
'use strict';
|
||||
if(window.PlotDirectorWorkspaceBridge||!window.BroadcastChannel)return;
|
||||
const params=new URLSearchParams(location.search),uid=Number(document.body.dataset.pdUserId),projectID=Number(document.body.dataset.pdProjectId||params.get('projectId'));
|
||||
const detached=params.get('detached')==='true',positive=n=>Number.isSafeInteger(n)&&n>0;
|
||||
const validToken=value=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value||'');
|
||||
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 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;
|
||||
token=value;channel?.close();channel=new BroadcastChannel(`pd-workspace:${uid}:${projectID}:${token}`);
|
||||
try{sessionStorage.setItem(`pd-workspace:${uid}:${projectID}`,token);}catch{}
|
||||
channel.onmessage=e=>{
|
||||
const m=e.data;
|
||||
if(!m||m.uid!==uid||m.projectID!==projectID||m.sender===sender||!validToken(m.sender)||!positive(m.sequence)||m.sequence<=(seen.get(m.sender)||0)||!allowed.has(m.type)||!m.payload||typeof m.payload!=='object')return;
|
||||
seen.set(m.sender,m.sequence);
|
||||
if(m.type==='open-scene'){
|
||||
if(detached||!positive(m.payload.sceneID)||!validToken(m.payload.requestID))return;
|
||||
// Acknowledgement means the main window owns this request, even when its unsaved modal cancels it.
|
||||
send('scene-opened',{requestID:m.payload.requestID});
|
||||
const go=()=>{location.href='/Scenes/Edit/'+m.payload.sceneID;};
|
||||
if(window.PlotDirectorMapWorkspace)window.PlotDirectorMapWorkspace.requestLeave(go);else go();return;
|
||||
}
|
||||
if(m.type==='scene-opened'){const timer=pendingOpen.get(m.payload.requestID);if(timer){clearTimeout(timer);pendingOpen.delete(m.payload.requestID);}return;}
|
||||
if(m.type==='ready'&&m.payload.detached===false)mainAvailable=true;
|
||||
if(m.type==='hello')send('ready',{detached});
|
||||
window.dispatchEvent(new CustomEvent('pd-workspace-message',{detail:{type:m.type,payload:m.payload}}));
|
||||
if(m.type==='hello'&&window.PlotDirectorStoryOverlay?.data)send('story-state',state());
|
||||
};
|
||||
send('hello');
|
||||
}
|
||||
window.PlotDirectorWorkspaceBridge={send,get mainAvailable(){return mainAvailable;},pause(){paused++;},resume(){paused=Math.max(0,paused-1);},detach(url){
|
||||
if(!channel)connect(crypto.randomUUID());if(!channel)return null;
|
||||
const destination=new URL(url,location.href);if(destination.origin!==location.origin)return null;
|
||||
destination.searchParams.set('detached','true');destination.searchParams.set('workspace',token);
|
||||
if(detachedWindow&&!detachedWindow.closed){detachedWindow.focus();return detachedWindow;}detachedWindow=window.open(destination.href,'_blank','popup,width=1400,height=900');return detachedWindow;
|
||||
}};
|
||||
try{const saved=params.get('workspace')||sessionStorage.getItem(`pd-workspace:${uid}:${projectID}`);if(validToken(saved))connect(saved);}catch{}
|
||||
window.addEventListener('pd-map-story-state',e=>send('story-state',e.detail));
|
||||
document.addEventListener('plotdirector:story-position-changed',e=>{if(Number(e.detail.projectId)===projectID&&positive(Number(e.detail.sceneId)))send('scene-selected',{sceneID:Number(e.detail.sceneId)});});
|
||||
document.addEventListener('click',e=>{
|
||||
const link=e.target.closest('a[href]');if(!link||!detached||!mainAvailable||e.defaultPrevented||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;
|
||||
const url=new URL(link.href),match=url.pathname.match(/^\/Scenes\/Edit\/(\d+)$/);if(url.origin!==location.origin||!match)return;
|
||||
e.preventDefault();const requestID=crypto.randomUUID();
|
||||
pendingOpen.set(requestID,setTimeout(()=>{pendingOpen.delete(requestID);mainAvailable=false;location.href=url.href;},900));
|
||||
send('open-scene',{sceneID:Number(match[1]),requestID});
|
||||
});
|
||||
window.addEventListener('pagehide',()=>channel?.close());
|
||||
window.addEventListener('pageshow',e=>{if(e.persisted&&token)connect(token);});
|
||||
document.addEventListener('DOMContentLoaded',()=>{const sceneID=Number(document.body.dataset.pdSceneId);if(positive(sceneID))send('scene-selected',{sceneID});});
|
||||
})();
|
||||
9
PlotLine/wwwroot/js/workspace-surface.js
Normal file
9
PlotLine/wwwroot/js/workspace-surface.js
Normal file
@ -0,0 +1,9 @@
|
||||
(() => {
|
||||
if(window.PlotDirectorWorkspaceSurface)return;
|
||||
window.PlotDirectorWorkspaceSurface={attach(app,button,{className='pd-workspace-maximised',onChange=()=>{},allowPwa=false}={}){
|
||||
function set(active){app.classList.toggle(className,active);app.classList.toggle('pd-workspace-maximised',active);button.setAttribute('aria-pressed',String(active));const label=active?'Restore workspace':'Maximise workspace';button.setAttribute('aria-label',label);button.title=label;button.dataset.ribbonIcon=active?'restore-workspace':'maximise';const text=button.querySelector('[data-workspace-caption]');if(text)text.textContent=label;onChange(active);window.dispatchEvent(new CustomEvent('pd-workspace-resize'));}
|
||||
button.addEventListener('click',()=>set(!app.classList.contains(className)));
|
||||
document.addEventListener('keydown',e=>{if(e.key==='Escape'&&!e.defaultPrevented&&app.classList.contains(className)&&!document.querySelector('dialog[open],.modal.show,.pd-context-popup')&&!app.querySelector('.rw-menu[open]'))set(false);});
|
||||
const sync=()=>{button.hidden=!allowPwa&&(!!window.PlotDirectorPwa?.standalone||document.documentElement.dataset.workspaceDetached==='true');};sync();window.addEventListener('plotdirector:pwa-mode-changed',sync);window.matchMedia('(display-mode: standalone)').addEventListener('change',sync);return {set,get active(){return app.classList.contains(className);}};
|
||||
}};
|
||||
})();
|
||||
Loading…
x
Reference in New Issue
Block a user