From 6e2716190c719bdc6d5aea557e24946df4f44fab Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Mon, 2 Nov 2026 17:43:18 +0000 Subject: [PATCH] Add Stage 1 Maps spatial writing workspace --- Docs/Maps_Stage1.md | 52 ++++ PlotLine.Tests/Browser/maps-dev-smoke.cjs | 58 +++++ PlotLine.Tests/Browser/maps-engine.cjs | 18 ++ PlotLine.Tests/Browser/maps-workspace.cjs | 75 ++++++ PlotLine.Tests/Browser/package.json | 3 +- PlotLine.Tests/MapTests.cs | 50 ++++ PlotLine.Tests/Program.cs | 1 + PlotLine.Tests/Sql/208_MapsRegression.sql | 121 +++++++++ PlotLine.Tests/ToolbarBrowserHost.cs | 14 +- PlotLine/Controllers/MapsController.cs | 61 +++++ PlotLine/Data/MapRepository.cs | 39 +++ PlotLine/Data/ProjectBackupRepository.cs | 10 + PlotLine/Models/MapModels.cs | 68 +++++ PlotLine/Models/ProjectBackupModels.cs | 3 + PlotLine/Program.cs | 1 + PlotLine/Services/ApplicationRibbon.cs | 4 +- PlotLine/Services/MapValidation.cs | 46 ++++ PlotLine/Sql/208_StoryMaps.sql | 170 ++++++++++++ PlotLine/Sql/209_StoryMapsBackupRestore.sql | 246 ++++++++++++++++++ PlotLine/Views/Maps/Index.cshtml | 58 +++++ .../Shared/_ApplicationSectionMenus.cshtml | 1 + PlotLine/wwwroot/css/maps-workspace.css | 4 + PlotLine/wwwroot/js/maps-engine.js | 123 +++++++++ PlotLine/wwwroot/js/maps-workspace.js | 241 +++++++++++++++++ 24 files changed, 1462 insertions(+), 5 deletions(-) create mode 100644 Docs/Maps_Stage1.md create mode 100644 PlotLine.Tests/Browser/maps-dev-smoke.cjs create mode 100644 PlotLine.Tests/Browser/maps-engine.cjs create mode 100644 PlotLine.Tests/Browser/maps-workspace.cjs create mode 100644 PlotLine.Tests/MapTests.cs create mode 100644 PlotLine.Tests/Sql/208_MapsRegression.sql create mode 100644 PlotLine/Controllers/MapsController.cs create mode 100644 PlotLine/Data/MapRepository.cs create mode 100644 PlotLine/Models/MapModels.cs create mode 100644 PlotLine/Services/MapValidation.cs create mode 100644 PlotLine/Sql/208_StoryMaps.sql create mode 100644 PlotLine/Sql/209_StoryMapsBackupRestore.sql create mode 100644 PlotLine/Views/Maps/Index.cshtml create mode 100644 PlotLine/wwwroot/css/maps-workspace.css create mode 100644 PlotLine/wwwroot/js/maps-engine.js create mode 100644 PlotLine/wwwroot/js/maps-workspace.js diff --git a/Docs/Maps_Stage1.md b/Docs/Maps_Stage1.md new file mode 100644 index 00000000..f9732e00 --- /dev/null +++ b/Docs/Maps_Stage1.md @@ -0,0 +1,52 @@ +# Maps Stage 1 + +Maps is a project-scoped spatial writing workspace. Open **World → Maps**, choose a map, or create one. The project selector supplies `projectId` to `/Maps`; selected maps add `id`. + +## Author workflows + +- Create a blank map or start with editable land, island, island group, two land masses, inland or local-area geometry. No place names or lore are generated. +- Search the piece library, pick a piece and click to place it, or drag it onto the canvas. Name it in Details. Marker, area and path pieces have different geometry and consistent default rendering. +- Terrain includes mountain ranges, hills, forests, marsh, desert, plains and farmland. Water includes lakes, rivers, streams and canals. Routes include roads, tracks, trails, railway, sea routes and walls. Region overlays have their own layer. +- Resize areas/paths by dragging their corner or changing dimensions. Rotate in Details. Edit Shape exposes simple points; Add Bend/Shape Point subdivides the longest segment. Coastline presets are deterministic. Rendering never changes saved control points. +- Existing unplaced story Locations have a separate searchable tray. Their placement links the existing ID. Appearance can be changed afterwards. A new feature offers explicit Location creation; checking it establishes the place. Provisional features do not silently create canonical Locations. Geographic features can remain unlinked. +- Define any pair of features as one north/east/etc. of another, with optional friendly relative distance, measured distance/unit and typical travel time. The visual geometry suggests the initial direction. Measured distance and travel time are independent data. +- Arrange from relationships is explicit and previewed. Cancel preserves the document. Apply is undoable. Locked pieces and established component anchors stay put; manual positions have a restoring weight. The unplaced-only option moves only pieces marked unplaced. Contradictions produce observations, not save failures. Measured distances never determine canvas spacing. +- Paths can attach each endpoint to a marker. Attached endpoints follow marker movement; the intervening author-controlled bends remain editable. Detach by choosing Unattached. +- Select, Shift-select, move, resize, rotate, duplicate, copy/paste, lock, delete, undo/redo and right-click actions are supported. Delete/Backspace deletes unlocked selections; arrow keys move selected pieces. Escape cancels placement/selection. Keyboard focus on pieces supports Enter/Space and movement. Shape handles also support arrow keys. +- Changes are explicitly saved; leaving with unsaved changes prompts. Revision checks prevent silent overwrites from another window. Save failures keep local edits visible. Undo/redo retains the current server revision and reconciles explicitly created Location links. +- Rename, duplicate and delete maps through Map Actions. Deleting a map promotes child maps to the project root and preserves Locations/Floor Plans. Removing a parent feature detaches its detail-map link while retaining the parent map relationship. +- Create a detailed map from a selected feature. Breadcrumbs navigate up, and double-click drills into its child map. Map selection and the all-maps list show the hierarchy. View zoom is separate from drill-down. +- Link an existing Floor Plan from a feature's Details. It can be opened directly and is a double-click destination when there is no child map. Floor Plan editing and occupancy/Story Mode are unchanged. + +## Modes and shell + +Create exposes editing. Explore hides the piece library and editing commands, keeping search, selection, inspection, pan/zoom and drill-down. Story currently provides the same geographical navigation with an explicit Stage 2 notice; there are no scene, journey or chronology overlays. + +Map selection, search, modes and high-level actions integrate with the existing PWA ribbon through contextual form/command bindings. Search results remain in the canvas surface. The web version has Maximise/Restore Workspace; the PWA hides this command and its empty ribbon group. Canvas zoom keeps markers/labels readable and simplifies distant labels. Layer visibility and overlap-aware automatic labels are presentation features, not changes to geography. + +The renderer uses a fixed readable working-map palette across application themes. Planning states use dashed outlines and a diamond, selection uses outlines, and labels use contrasting halos. Reduced motion requires no special animation path because navigation has no animated transitions. + +## Architecture and Stage 2 contract + +- `StoryMaps`: generic bounded document with project, kind, parent map, optional parent feature, name and optimistic revision. Hierarchy is assigned at creation; reparenting existing maps is not exposed. +- `MapFeatures`: queryable ID/name/type/layer/geometry class, author canvas placement/dimensions/rotation/order, placement/provisional/lock/label state, optional canonical Location/Floor Plan IDs and route endpoint IDs. Geometry-specific control points and coastline character live in deliberately scoped JSON. +- `MapRelationships`: a same-map directed graph, eight compass directions, five relative distance categories, independent decimal measured distance/unit and textual typical travel time. Unknown direction/distance is supported. +- `MapDocument` is the API editing unit. SQL Server stores rows rather than an opaque document blob. A save validates the document, locks/checks the revision and atomically updates features/relationships and explicitly requested Locations. +- `MapRepository` uses Dapper/stored procedures. `MapsController` checks project access on every action; procedures repeat the project access check. MVC authorization, antiforgery and the existing global subscription edit filter apply. Cross-project parent/Location/Floor Plan references and foreign route endpoints are rejected. +- SVG rendering is separate from canonical data. `maps-engine.js` supplies the semantic library, deterministic geometry, attached endpoint resolution and layout. The workspace uses keyed SVG groups and updates only moved pieces/attached paths during dragging. No new client framework or external map API is used. +- Structured Maps sets are included in project JSON backups. The existing restore transaction restores hierarchy/features/relationships and invalidates stale editor revisions. Older backups contain no Maps sets; the normal safety restore point captures the current map state before restoring them. Project deletion cascades Maps and their features/relationships, and Location/Floor Plan deletion clears optional links. +- Stage 2 should add Story projections against canonical Location IDs and independent travel/chronology data. It must not infer physical coordinates from canvas placement, silently arrange the map, or convert provisional map features into canonical story assertions. Political areas are overlays, leaving geography intact. Floor Plans remain a separate compatible workspace at building level. + +## Deliberate limits + +Imported image backgrounds, favourites/recent pieces, context-aware bridge/port/coast snapping, view/layer preference persistence, sophisticated label avoidance, map thumbnails and reparenting are deferred. Shapes use a small editable control-point set; there is no vector drawing editor. Arrangement is a practical deterministic compromise, not a geography solver. No detached workspace, procedural world generation, publication export, scene chronology, journey analysis or time-varying political ownership is included. + +## Verification + +- `dotnet build PlotLine.slnx` +- `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj` +- `node PlotLine.Tests/Browser/maps-engine.cjs` +- `PD_BROWSER_FIXTURE_URL=http://127.0.0.1:5246 dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj -- --toolbar-browser-host`, then `npm run test:maps` in `PlotLine.Tests/Browser` (or set `PD_MAPS_TEST_URL` to another fixture host). +- `PlotLine.Tests/Sql/208_MapsRegression.sql` requires migrations 208 and 209, checks the Development database and rolls back its new fixtures, including the restore test. It does not restore any existing project. + +Migrations are `208_StoryMaps.sql` and `209_StoryMapsBackupRestore.sql`. Apply only to a verified target after a successful backup. Stage 1 deployment is authorised for Development only. diff --git a/PlotLine.Tests/Browser/maps-dev-smoke.cjs b/PlotLine.Tests/Browser/maps-dev-smoke.cjs new file mode 100644 index 00000000..646ff523 --- /dev/null +++ b/PlotLine.Tests/Browser/maps-dev-smoke.cjs @@ -0,0 +1,58 @@ +/* Explicit Development-only smoke. Requires a dedicated identity from --dev-browser-identity. + It creates a project owned by that identity; clean up with the matching identity cleanup command. */ +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'); +const identityPath=process.argv[2]; +if(!identityPath?.startsWith('/tmp/pd-dev-browser-'))throw Error('A dedicated Development identity file is required.'); +const identity=JSON.parse(fs.readFileSync(identityPath,'utf8')); +if(identity.Database!=='PlotDirector_Development'||!identity.Email.startsWith('pwa-browser-'))throw Error('Development fixture identity required.'); +const base='https://dev.plotdirector.com'; +(async()=>{ + const browser=await chromium.launch(); + try{ + const context=await browser.newContext({viewport:{width:1700,height:1100}}),page=await context.newPage(),errors=[]; + page.on('pageerror',e=>errors.push(e.message)); + page.on('dialog',dialog=>dialog.accept()); + await page.goto(base+'/Account/Login');await page.locator('#Email').fill(identity.Email);await page.locator('#Password').fill(identity.Password); + await Promise.all([page.waitForURL('**/Projects'),page.locator('form[action="/Account/Login"] button[type=submit]').click()]); + await page.goto(base+'/Projects/Create');await page.locator('#ProjectName').fill('Maps Development smoke '+Date.now());await page.getByRole('button',{name:'Save project',exact:true}).click(); + await page.waitForURL(/\/Projects(?:\/Details)?\//);const projectId=Number(page.url().match(/\/(\d+)(?:\?|$)/)[1]); + await page.goto(base+'/Maps?projectId='+projectId);await page.locator('#mapsNew').click(); + await page.locator('#mapsNewForm [name=Name]').fill('Working world');await page.locator('#mapsNewForm [name=Kind]').selectOption('World');await page.locator('#mapsNewForm [name=Starter]').selectOption('island'); + await Promise.all([page.waitForURL(/&id=\d+/),page.locator('#mapsNewForm button[type=submit]').click()]); + await page.waitForFunction(()=>window.PlotDirectorMapWorkspace?.document?.features.length===1);const rootURL=page.url(); + async function place(type,x,y){await page.locator('#mapsAssetSearch').fill(type);await page.locator(`[data-asset="${type}"]`).click();const b=await page.locator('#mapsCanvas').boundingBox();await page.mouse.click(b.x+b.width*x,b.y+b.height*y);} + for(const[type,x,y]of[['Mountain Range',.55,.32],['Forest',.35,.48],['River',.6,.52],['Town',.35,.65],['Town',.7,.62],['Road',.5,.65]])await place(type,x,y); + assert.equal(await page.locator('.maps-feature').count(),7); + const features=await page.evaluate(()=>window.PlotDirectorMapWorkspace.document.features),towns=features.filter(f=>f.type==='Town'),road=features.find(f=>f.type==='Road'); + await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),towns[0].featureID);await page.locator('[data-field=name]').fill('Harbour town');await page.locator('[data-field=name]').blur(); + await page.locator('#mapsDetailContent details').filter({has:page.locator('summary:text-is("Story Location")')}).locator('summary').click();await page.locator('[data-field=createLocation]').check(); + await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),road.featureID);await page.locator('[data-field=startFeatureID]').selectOption(towns[0].featureID);await page.locator('[data-field=endFeatureID]').selectOption(towns[1].featureID); + await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),towns[0].featureID);await page.locator('[data-action=relationship]').click(); + const relation=page.locator('dialog[open]');await relation.locator('[name=targetID]').selectOption(towns[1].featureID);await relation.locator('[name=direction]').selectOption('NW');await relation.locator('[name=relativeDistance]').selectOption('Far'); + await relation.locator('summary').click();await relation.locator('[name=measuredDistance]').fill('126');await relation.locator('[name=unit]').fill('kilometres');await relation.locator('[name=typicalTravelTime]').fill('Two hours by car');await relation.getByRole('button',{name:'Keep relationship'}).click(); + await page.locator('#mapsArrange').click();await page.locator('#mapsArrangeApply').click();await page.locator('#mapsSave').click();await page.waitForFunction(()=>document.getElementById('mapsStatus').textContent==='Saved'); + const locationID=await page.evaluate(id=>window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id).locationID,towns[0].featureID);assert(locationID>0); + await page.reload();await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);assert.equal(await page.locator('.maps-feature').count(),7); + assert(await page.evaluate(({id,locationID})=>{const d=window.PlotDirectorMapWorkspace.document;return d.features.find(f=>f.featureID===id).locationID===locationID&&d.relationships[0].measuredDistance===126&&d.relationships[0].typicalTravelTime==='Two hours by car';},{id:towns[0].featureID,locationID})); + // A second save must keep the same canonical Location ID. + await page.locator('#mapsSave').click();await page.waitForFunction(()=>document.getElementById('mapsStatus').textContent==='Saved'); + await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),towns[0].featureID);await page.locator('[data-action=child]').click();await page.locator('#mapsNewForm [name=Name]').fill('Harbour detail'); + const rootID=new URL(rootURL).searchParams.get('id');await page.locator('#mapsNewForm button[type=submit]').click();await page.waitForURL(url=>url.searchParams.get('id')!==rootID&&url.pathname==='/Maps');await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace); + assert.equal(await page.locator('#mapsBreadcrumbs a').count(),3,'hierarchy breadcrumbs');const childURL=page.url(); + 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); + // 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'); + assert(await page.evaluate(id=>window.PlotDirectorMapWorkspace.document.features[0].locationID===id,locationID)); + // No anti-forgery token means no mutation. + const csrf=await context.request.post(base+'/Maps/Delete',{form:{projectId,id:Number(new URL(childURL).searchParams.get('id')),revision:1}});assert.equal(csrf.status(),400); + await page.goto(rootURL);await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);await page.locator('#mapsFit').click();await page.screenshot({path:'/tmp/maps-development-smoke.png'}); + const pwa=await browser.newContext({viewport:{width:1700,height:1100},storageState:await context.storageState()});await pwa.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));const app=await pwa.newPage();app.on('pageerror',e=>errors.push(e.message));await app.goto(rootURL);await app.waitForFunction(()=>!!window.PlotDirectorMapWorkspace); + assert(await app.locator('.maps-toolbar').isHidden());assert(await app.locator('#mapsMaximise').isHidden());await app.locator('[data-pwa-context-controls] input[aria-label="Find on map"]').fill('Harbour');await app.locator('[data-search-feature]').click();assert.equal(await app.locator('.maps-feature.is-selected').count(),1);await app.screenshot({path:'/tmp/maps-development-pwa.png'}); + assert.deepEqual(errors,[]);console.log('PASS authenticated Development Maps: create/starter, 7-piece geography, Location creation/reuse, relationships/distance/time, arrangement, save/reload, hierarchy/drill-down, duplication/deletion, CSRF and PWA search. Fixture project ID: '+projectId); + await context.close();await pwa.close(); + }finally{await browser.close();} +})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/Browser/maps-engine.cjs b/PlotLine.Tests/Browser/maps-engine.cjs new file mode 100644 index 00000000..0bca8b1d --- /dev/null +++ b/PlotLine.Tests/Browser/maps-engine.cjs @@ -0,0 +1,18 @@ +const assert=require('node:assert/strict'); +const E=require('../../PlotLine/wwwroot/js/maps-engine.js'); +const a=E.makeFeature('Town',0,0,'a'),b=E.makeFeature('Town',10,10,'b'),c=E.makeFeature('Village',30,0,'c'); +const rel=[{relationshipID:'r1',sourceID:'b',targetID:'a',direction:'NW',relativeDistance:'Far',measuredDistance:126},{relationshipID:'r2',sourceID:'c',targetID:'b',direction:'E',relativeDistance:'Very close',measuredDistance:2}]; +const first=E.arrange([a,b,c],rel),second=E.arrange([a,b,c],rel); +assert.deepEqual(first,second,'arrangement deterministic'); +assert.equal(E.suggestedDirection(first.features[1],first.features[0]),'NW'); +assert.equal(E.suggestedDirection(first.features[2],first.features[1]),'E'); +assert.deepEqual(first,E.arrange([a,b,c],rel.map(r=>({...r,measuredDistance:999999999}))), 'physical distance never drives canvas spacing'); +assert.equal(a.x,0,'preview never mutates author data'); +b.isPlaced=false;const partial=E.arrange([a,b,c],rel,true);assert.equal(partial.features[0].x,a.x);assert.equal(partial.features[2].x,c.x); +b.isLocked=true;assert.equal(E.arrange([a,b],rel).features[1].x,b.x);b.isLocked=false; +const conflicts=E.arrange([a,b],[{relationshipID:'1',sourceID:'a',targetID:'b',direction:'N'},{relationshipID:'2',sourceID:'b',targetID:'a',direction:'N'}]);assert(conflicts.warnings.length,'contradictions are observations'); +const route=E.makeFeature('Road',0,0,'road');route.startFeatureID='a';route.endFeatureID='b';a.x=150;b.x=700; +const points=E.pathPoints(route,[a,b]);assert.deepEqual(points[0],[150,0]);assert.deepEqual(points.at(-1),[700,10]); +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'); diff --git a/PlotLine.Tests/Browser/maps-workspace.cjs b/PlotLine.Tests/Browser/maps-workspace.cjs new file mode 100644 index 00000000..06422ef4 --- /dev/null +++ b/PlotLine.Tests/Browser/maps-workspace.cjs @@ -0,0 +1,75 @@ +const {chromium}=require('playwright'); +const assert=require('node:assert/strict'); +const base=process.env.PD_MAPS_TEST_URL||'http://127.0.0.1:5246'; +(async()=>{ + const browser=await chromium.launch(); + try{ + for(const pwa of [false,true]){ + 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.goto(base+'/fixture?page=maps');await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace); + const canvas=page.locator('#mapsCanvas'); + async function sourceClick(id){ + const proxy=page.locator(`[data-pwa-context-controls] [data-command-identity="handler:${id}"]`); + if(pwa&&await proxy.count()){ + const menu=proxy.locator('xpath=ancestor::details[1]'); + if(await menu.count()&&await menu.getAttribute('data-compact')==='true'&&await menu.getAttribute('open')===null)await menu.locator(':scope > summary').click(); + await proxy.click(); + }else await page.locator('#'+id).click(); + } + async function place(type,x,y){await page.locator('#mapsAssetSearch').fill(type);await page.locator(`[data-asset="${type}"]`).click();const b=await canvas.boundingBox();await page.mouse.click(b.x+b.width*x,b.y+b.height*y);} + for(const[type,x,y]of[['Island',.5,.5],['Mountain Range',.55,.32],['Forest',.35,.5],['River',.6,.55],['Town',.35,.65],['Town',.7,.62],['Road',.5,.65]])await place(type,x,y); + assert.equal(await page.locator('.maps-feature').count(),7,'five-minute map workflow'); + const f=await page.evaluate(()=>window.PlotDirectorMapWorkspace.document.features); + const towns=f.filter(f=>f.type==='Town'),road=f.find(f=>f.type==='Road'); + const island=f.find(f=>f.type==='Island'); + await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),island.featureID); + await page.locator('[data-field="width"]').fill('480');await page.locator('[data-field="width"]').blur(); + assert.equal(await page.evaluate(id=>window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id).width,island.featureID),480); + await page.locator('[data-action="shape"]').click();assert.equal(await page.locator('[data-handle="point"]').count(),8); + const point=await page.locator('[data-handle="point"]').first().boundingBox(),geometryBefore=await page.evaluate(id=>window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id).geometryJson,island.featureID); + await page.mouse.move(point.x+point.width/2,point.y+point.height/2);await page.mouse.down();await page.mouse.move(point.x+35,point.y+10,{steps:4});await page.mouse.up(); + assert.notEqual(await page.evaluate(id=>window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id).geometryJson,island.featureID),geometryBefore,'simple shape points are editable'); + const canvasBounds=await canvas.boundingBox(); + for(const piece of f){await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),piece.featureID);const current=await canvas.boundingBox();assert.deepEqual(current,canvasBounds,'selection does not shift the workspace');} + + await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),road.featureID); + await page.locator('[data-field="startFeatureID"]').selectOption(towns[0].featureID);await page.locator('[data-field="endFeatureID"]').selectOption(towns[1].featureID); + const roadBefore=await page.locator(`[data-feature-id="${road.featureID}"] .map-shape`).getAttribute('d'); + await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),towns[0].featureID); + await page.locator('[data-feature-id="'+towns[0].featureID+'"]').focus();await page.keyboard.press('ArrowRight'); + assert.notEqual(await page.locator(`[data-feature-id="${road.featureID}"] .map-shape`).getAttribute('d'),roadBefore,'roads follow moved places'); + await page.locator('[data-action="relationship"]').click(); + const dialog=page.locator('dialog[open]');await dialog.locator('[name="targetID"]').selectOption(towns[1].featureID);await dialog.locator('[name="direction"]').selectOption('NW');await dialog.locator('[name="relativeDistance"]').selectOption('Far');await dialog.getByRole('button',{name:'Keep relationship'}).click(); + const before=await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features)); + await sourceClick('mapsArrange');assert(await page.locator('#mapsArrangeDialog').isVisible());await sourceClick('mapsArrangeCancel'); + assert.equal(await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features)),before,'cancel preserves positions'); + await sourceClick('mapsArrange');await sourceClick('mapsArrangeApply');assert.notEqual(await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features)),before); + await sourceClick('mapsUndo');assert.equal(await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features)),before,'undo arrangement'); + await sourceClick('mapsRedo'); + + // Existing Location placement retains its canonical ID and removes it from the tray. + await page.locator('[data-location="11"]').click();let box=await canvas.boundingBox();await page.mouse.click(box.x+box.width*.5,box.y+box.height*.8);assert.equal(await page.locator('[data-location="11"]').count(),0); + assert(await page.evaluate(()=>window.PlotDirectorMapWorkspace.document.features.some(f=>f.locationID===11&&!f.createLocation))); + const bounds=await canvas.boundingBox(); + await page.evaluate(()=>document.querySelector('button[data-mode="explore"]').click());assert(await page.locator('#mapsLibrary').isHidden());assert(await page.locator('[data-action="remove"]').count()===0); + const find=page.locator('#mapsFind'); + 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(()=>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());} + else{await sourceClick('mapsMaximise');assert(await page.locator('#mapsApp').evaluate(el=>el.classList.contains('maps-maximised')));await sourceClick('mapsMaximise');} + // Pan is stable under repeated pointer moves; zoom and selection do not replace the SVG. + const same=await page.evaluate(()=>{window.__mapCanvas=document.getElementById('mapsCanvas');return true;}); + await sourceClick('mapsZoomIn');await sourceClick('mapsZoomOut');assert(await page.evaluate(()=>window.__mapCanvas===document.getElementById('mapsCanvas'))); + await page.screenshot({path:`/tmp/maps-${pwa?'pwa':'web'}.png`}); + const scale=await page.evaluate(()=>{const w=window.PlotDirectorMapWorkspace;for(let i=0;i<500;i++)w.document.features.push(window.PlotDirectorMaps.makeFeature('Village',(i%25)*110,Math.floor(i/25)*100,crypto.randomUUID()));const start=performance.now();w.fit();return {ms:performance.now()-start,count:document.querySelectorAll('.maps-feature').length};}); + assert(scale.count>500&&scale.ms<3000,'substantial maps render practically'); + assert.deepEqual(errors,[]);console.log(`PASS Maps ${pwa?'PWA':'web'}: 7-piece author workflow, Location tray, relationships, arrangement preview/cancel/apply/undo, attached roads, Explore search, Story boundary, stable canvas and maximise`); + await context.close(); + } + }finally{await browser.close();} +})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/Browser/package.json b/PlotLine.Tests/Browser/package.json index c90ef9f5..70bf2ccb 100644 --- a/PlotLine.Tests/Browser/package.json +++ b/PlotLine.Tests/Browser/package.json @@ -18,7 +18,8 @@ "test:record-workspaces": "node record-workspaces.cjs", "test:relationships": "node relationship-workspace.cjs", "test:relationships-ribbon": "node relationships-ribbon.cjs", - "test:relationship-focus": "node relationship-focus-stability.cjs" + "test:relationship-focus": "node relationship-focus-stability.cjs", + "test:maps": "node maps-engine.cjs && node maps-workspace.cjs" }, "devDependencies": { "chart.js": "4.4.9", diff --git a/PlotLine.Tests/MapTests.cs b/PlotLine.Tests/MapTests.cs new file mode 100644 index 00000000..c0337387 --- /dev/null +++ b/PlotLine.Tests/MapTests.cs @@ -0,0 +1,50 @@ +using Microsoft.AspNetCore.Mvc; +using PlotLine.Controllers; +using PlotLine.Models; +using PlotLine.Services; + +internal static class MapTests +{ + static void Check(bool value, string message) { if (!value) throw new InvalidOperationException(message); } + public static void ValidationAndAccess() + { + var a = new MapFeature { Name = "First town", LocationID = 42 }; + var b = new MapFeature { Name = "Other town", X = 30, Y = -20 }; + var d = new MapDocument { Map = new() { ProjectID = 7 }, Features = [a, b], Relationships = [new() { SourceID = a.FeatureID, TargetID = b.FeatureID, Direction = "N", RelativeDistance = "Far", MeasuredDistance = 126, Unit = "kilometres", TypicalTravelTime = "two hours" }] }; + Check(MapValidation.Validate(d) is null, "Rough geography with conflicting visual scale must be valid."); + d.Relationships.Add(new() { SourceID = b.FeatureID, TargetID = a.FeatureID, Direction = "N", RelativeDistance = "Close" }); + Check(MapValidation.Validate(d) is null, "Contradictory intentions must remain saveable."); + d.Relationships[0].TargetID = Guid.NewGuid(); + Check(MapValidation.Validate(d) is not null, "Cross-map relationships must fail."); + d.Relationships[0].TargetID = b.FeatureID; + b.GeometryClass = "Path"; b.StartFeatureID = Guid.NewGuid(); + Check(MapValidation.Validate(d) is not null, "Unknown route endpoints must fail."); + b.StartFeatureID = a.FeatureID; + Check(MapValidation.Validate(d) is null, "A route may attach to a marker."); + b.GeometryJson = "{\"points\":[[true,0],[0,1]]}"; + Check(MapValidation.Validate(d) is not null, "Non-numeric shape points must fail gracefully."); + b.GeometryJson = "{}"; b.Width = double.NaN; + Check(MapValidation.Validate(d) is not null, "Non-finite geometry must fail."); + b.Width = 20; b.CreateLocation = true; + Check(MapValidation.Validate(d) is not null, "Provisional geography must not silently become canonical Locations."); + b.IsProvisional = false; + Check(MapValidation.Validate(d) is null, "Explicit Location creation is supported."); + b.FeatureID = a.FeatureID; + Check(MapValidation.Validate(d) is not null, "Duplicate feature identifiers must fail."); + // 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.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."); + Check(controller.Delete(7, 1, 0).Result is NotFoundResult, "Delete must enforce access."); + var posts = typeof(MapsController).GetMethods().Where(m => m.GetCustomAttributes(typeof(HttpPostAttribute), true).Length > 0); + Check(posts.Count() == 3 && posts.All(m => m.GetCustomAttributes(typeof(ValidateAntiForgeryTokenAttribute), true).Length > 0), "Every mutation needs antiforgery and the shared subscription enforcement filter."); + } + private sealed class DeniedAccess : IProjectAccessService + { + public Task CanAccessProjectAsync(int id) => Task.FromResult(false); + public Task CanOwnProjectAsync(int id) => Task.FromResult(false); + public Task CanAccessEntityAsync(string type, int id) => Task.FromResult(false); + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 9ac3de07..e3909d2b 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -104,6 +104,7 @@ var tests = new (string Name, Action Test)[] ("Writing Solver scoring, multi-select, revision, fallback and graph routes", WritingSolverTests.RoutingAndRevision), ("Writing Solver import rejects invalid graphs and editorial identities", WritingSolverTests.Validation), ("Ribbon operation identity and semantic icons stay consistent", RibbonPresentationTests.SemanticMetadata), + ("Maps validate rough geometry, relationships, Location intent and access boundaries", MapTests.ValidationAndAccess), ("Subscription entitlement evaluates trials, paid access, overrides and real plan limits", SubscriptionEntitlementTests.EffectiveStateAndLimits), ("Subscription overrides control access and dashboard presentation without trial contradictions", SubscriptionEntitlementTests.OverridePrecedenceAndPresentation), ("Subscription enforcement is concurrent, audited and admin-authorised", SubscriptionEntitlementTests.EnforcementAndAdminSecurity), diff --git a/PlotLine.Tests/Sql/208_MapsRegression.sql b/PlotLine.Tests/Sql/208_MapsRegression.sql new file mode 100644 index 00000000..80c4f622 --- /dev/null +++ b/PlotLine.Tests/Sql/208_MapsRegression.sql @@ -0,0 +1,121 @@ +-- Development only. All fixtures roll back. Requires 208_StoryMaps.sql. +SET NOCOUNT ON; +IF DB_NAME() <> N'PlotDirector_Development' THROW 51000,'Maps regressions require Development.',1; +DECLARE @user int=(SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE AccessRole='Owner' AND IsActive=1); +IF @user IS NULL THROW 51000,'An existing development owner is required.',1; +DECLARE @name nvarchar(200)=N'Maps regression '+CONVERT(nvarchar(36),NEWID()); +BEGIN TRY + BEGIN TRAN; + EXEC dbo.Project_Save @ProjectName=@name,@UserID=@user; + DECLARE @project int=(SELECT ProjectID FROM dbo.Projects WHERE ProjectName=@name); + EXEC dbo.StoryMap_Create @ProjectID=@project,@UserID=@user,@Name=N'Root',@Kind=N'World'; + DECLARE @map int=(SELECT MapID FROM dbo.StoryMaps WHERE ProjectID=@project); + DECLARE @first uniqueidentifier=NEWID(),@second uniqueidentifier=NEWID(); + DECLARE @features nvarchar(max)=(SELECT @first AS FeatureID,'Town' AS Name,'Town' AS Type,'Marker' AS GeometryClass,'Places' AS Layer,0 AS X,0 AS Y,42 AS Width,42 AS Height,0 AS Rotation,40 AS ZOrder,1 AS IsPlaced,0 AS IsProvisional,0 AS IsLocked,1 AS ShowLabel,0 AS LabelX,0 AS LabelY,'{}' AS GeometryJson,1 AS CreateLocation FOR JSON PATH); + DECLARE @before int=(SELECT COUNT(*) FROM dbo.Locations WHERE ProjectID=@project); + EXEC dbo.StoryMap_Save @ProjectID=@project,@MapID=@map,@UserID=@user,@Revision=0,@Name='Renamed',@Kind='World',@Features=@features,@Relationships='[]'; + IF NOT EXISTS(SELECT 1 FROM dbo.StoryMaps WHERE MapID=@map AND Revision=1 AND Name='Renamed') THROW 51000,'Map save failed.',1; + DECLARE @location int=(SELECT LocationID FROM dbo.MapFeatures WHERE MapID=@map AND FeatureID=@first); + IF @location IS NULL OR (SELECT COUNT(*) FROM dbo.Locations WHERE ProjectID=@project)<>@before+1 THROW 51000,'Explicit Location creation failed.',1; + SET @features=JSON_MODIFY(@features,'$[0].LocationID',@location); + -- A linked feature never creates a second Location, even if the creation flag remains set. + EXEC dbo.StoryMap_Save @ProjectID=@project,@MapID=@map,@UserID=@user,@Revision=1,@Name='Renamed',@Kind='World',@Features=@features,@Relationships='[]'; + IF (SELECT COUNT(*) FROM dbo.Locations WHERE ProjectID=@project)<>@before+1 THROW 51000,'Duplicate Location created.',1; + EXEC dbo.StoryMap_Create @ProjectID=@project,@UserID=@user,@Name=N'Detail',@Kind=N'Local Area',@ParentMapID=@map,@ParentFeatureID=@first; + DECLARE @child int=(SELECT MapID FROM dbo.StoryMaps WHERE ProjectID=@project AND ParentMapID=@map); + IF @child IS NULL THROW 51000,'Child creation failed.',1; + -- A second feature can link the same canonical place without duplicating it. + DECLARE @copy nvarchar(max)=JSON_MODIFY(@features,'$[0].FeatureID',CONVERT(nvarchar(36),@second)); + SET @features=LEFT(@features,LEN(@features)-1)+','+SUBSTRING(@copy,2,LEN(@copy)); + DECLARE @rel nvarchar(max)=(SELECT NEWID() AS RelationshipID,@first AS SourceID,@second AS TargetID,'N' AS Direction,'Far' AS RelativeDistance,126 AS MeasuredDistance,'kilometres' AS Unit,'2 hours by car' AS TypicalTravelTime FOR JSON PATH); + EXEC dbo.StoryMap_Save @ProjectID=@project,@MapID=@map,@UserID=@user,@Revision=2,@Name='Renamed',@Kind='World',@Features=@features,@Relationships=@rel; + IF (SELECT COUNT(*) FROM dbo.MapFeatures WHERE MapID=@map)<>2 OR NOT EXISTS(SELECT 1 FROM dbo.MapRelationships WHERE MapID=@map AND MeasuredDistance=126 AND TypicalTravelTime='2 hours by car') THROW 51000,'Features or relationship persistence failed.',1; + -- Removing the parent feature detaches the drill-down association, preserving the child. + EXEC dbo.StoryMap_Save @ProjectID=@project,@MapID=@map,@UserID=@user,@Revision=3,@Name='Renamed',@Kind='World',@Features='[]',@Relationships='[]'; + IF NOT EXISTS(SELECT 1 FROM dbo.StoryMaps WHERE MapID=@child AND ParentMapID=@map AND ParentFeatureID IS NULL) THROW 51000,'Removed feature orphaned a child link.',1; + EXEC dbo.StoryMap_Delete @ProjectID=@project,@MapID=@map,@UserID=@user,@Revision=4; + IF NOT EXISTS(SELECT 1 FROM dbo.StoryMaps WHERE MapID=@child AND ParentMapID IS NULL) OR NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@location) THROW 51000,'Map deletion lost child maps or story Locations.',1; + -- The normal project hard-delete workflow must remove map data without FK conflicts. + EXEC dbo.Project_Archive @ProjectID=@project; + EXEC dbo.ProjectHardDelete_ForOwner @ProjectID=@project,@UserID=@user; + IF EXISTS(SELECT 1 FROM dbo.StoryMaps WHERE ProjectID=@project) THROW 51000,'Project deletion left maps.',1; + ROLLBACK; + SELECT 'PASS map CRUD, hierarchy, structured persistence, Location association/retry, measured distance, travel time and deletion integrity (rolled back)' AS Result; +END TRY +BEGIN CATCH + IF @@TRANCOUNT>0 ROLLBACK; + THROW; +END CATCH; +-- Authorisation is enforced within the stored procedures, independently of MVC. +BEGIN TRY + EXEC dbo.StoryMap_List @ProjectID=-1,@UserID=@user; + THROW 51001,'Unauthorised project was accepted.',1; +END TRY +BEGIN CATCH + IF ERROR_NUMBER()<>51000 THROW; +END CATCH; +SELECT 'PASS database project access enforcement; Development guard verified' AS Result; +-- Each rejected mutation gets a fresh rolled-back fixture because XACT_ABORT protects writes. +DECLARE @case int=0; +WHILE @case<4 +BEGIN + BEGIN TRY + BEGIN TRAN; + SET @name=N'Maps security '+CONVERT(nvarchar(36),NEWID()); + EXEC dbo.Project_Save @ProjectName=@name,@UserID=@user; + SELECT @project=ProjectID FROM dbo.Projects WHERE ProjectName=@name; + EXEC dbo.StoryMap_Create @ProjectID=@project,@UserID=@user,@Name='Root',@Kind='World'; + SELECT @map=MapID FROM dbo.StoryMaps WHERE ProjectID=@project; + IF @case=0 + EXEC dbo.StoryMap_Save @ProjectID=@project,@MapID=@map,@UserID=@user,@Revision=99,@Name='Stale',@Kind='World',@Features='[]',@Relationships='[]'; + IF @case=1 + EXEC dbo.StoryMap_Create @ProjectID=@project,@UserID=@user,@Name='Bad parent',@Kind='Region',@ParentMapID=-1; + IF @case=2 + EXEC dbo.StoryMap_Delete @ProjectID=@project,@MapID=@map,@UserID=@user,@Revision=99; + IF @case=3 + BEGIN + SET @features=(SELECT NEWID() AS FeatureID,'Town' AS Name,'Town' AS Type,'Marker' AS GeometryClass,'Places' AS Layer,0 AS X,0 AS Y,42 AS Width,42 AS Height,0 AS Rotation,40 AS ZOrder,1 AS IsPlaced,0 AS IsProvisional,0 AS IsLocked,1 AS ShowLabel,0 AS LabelX,0 AS LabelY,'{}' AS GeometryJson,-1 AS LocationID FOR JSON PATH); + EXEC dbo.StoryMap_Save @ProjectID=@project,@MapID=@map,@UserID=@user,@Revision=0,@Name='Bad Location',@Kind='World',@Features=@features,@Relationships='[]'; + END; + THROW 51001,'Expected rejected mutation was accepted.',1; + END TRY + BEGIN CATCH + IF @@TRANCOUNT>0 ROLLBACK; + IF ERROR_NUMBER()<>51000 THROW; + END CATCH; + SET @case+=1; +END; +SELECT 'PASS stale save/delete, foreign parent and foreign Location rejection (rolled back)' AS Result; +-- Additive map sets survive the same JSON restore workflow as Floor Plans and Locations. +-- Requires migration 209 as well. No Development project is restored: this fixture is new and rolled back. +BEGIN TRY + BEGIN TRAN; + SET @name=N'Maps roundtrip '+CONVERT(nvarchar(36),NEWID()); + EXEC dbo.Project_Save @ProjectName=@name,@UserID=@user; + SELECT @project=ProjectID FROM dbo.Projects WHERE ProjectName=@name; + EXEC dbo.StoryMap_Create @ProjectID=@project,@UserID=@user,@Name='Root',@Kind='World'; + SELECT @map=MapID FROM dbo.StoryMaps WHERE ProjectID=@project; + SET @first=NEWID(); + SET @features=(SELECT @first AS FeatureID,'Town' AS Name,'Town' AS Type,'Marker' AS GeometryClass,'Places' AS Layer,15 AS X,-30 AS Y,42 AS Width,42 AS Height,0 AS Rotation,40 AS ZOrder,1 AS IsPlaced,0 AS IsProvisional,0 AS IsLocked,1 AS ShowLabel,0 AS LabelX,0 AS LabelY,'{}' AS GeometryJson,1 AS CreateLocation FOR JSON PATH); + EXEC dbo.StoryMap_Save @ProjectID=@project,@MapID=@map,@UserID=@user,@Revision=0,@Name='Root',@Kind='World',@Features=@features,@Relationships='[]'; + EXEC dbo.StoryMap_Create @ProjectID=@project,@UserID=@user,@Name='Detail',@Kind='Region',@ParentMapID=@map,@ParentFeatureID=@first; + SET @location=(SELECT LocationID FROM dbo.MapFeatures WHERE MapID=@map AND FeatureID=@first); + DECLARE @json nvarchar(max)=(SELECT 'PlotDirector.ProjectBackup' AS Format,'1.1' AS FormatVersion, + JSON_QUERY((SELECT * FROM dbo.Projects WHERE ProjectID=@project FOR JSON PATH,WITHOUT_ARRAY_WRAPPER)) AS Project, + JSON_QUERY((SELECT + JSON_QUERY((SELECT * FROM dbo.StoryMaps WHERE ProjectID=@project FOR JSON PATH)) AS StoryMaps, + JSON_QUERY((SELECT f.* FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@project FOR JSON PATH)) AS MapFeatures, + JSON_QUERY((SELECT r.* FROM dbo.MapRelationships r JOIN dbo.StoryMaps m ON m.MapID=r.MapID WHERE m.ProjectID=@project FOR JSON PATH)) AS MapRelationships, + JSON_QUERY((SELECT * FROM dbo.Locations WHERE ProjectID=@project FOR JSON PATH)) AS Locations + FOR JSON PATH,WITHOUT_ARRAY_WRAPPER)) AS Data FOR JSON PATH,WITHOUT_ARRAY_WRAPPER); + EXEC dbo.ProjectRestore_ApplyFromJson @ProjectID=@project,@JsonData=@json; + IF NOT EXISTS(SELECT 1 FROM dbo.MapFeatures WHERE MapID=@map AND FeatureID=@first AND LocationID=@location AND X=15 AND Y=-30) THROW 51000,'Map restore lost geometry or canonical Location links.',1; + IF NOT EXISTS(SELECT 1 FROM dbo.StoryMaps WHERE ProjectID=@project AND ParentMapID=@map AND ParentFeatureID=@first) THROW 51000,'Map restore lost hierarchy.',1; + IF EXISTS(SELECT 1 FROM dbo.StoryMaps WHERE ProjectID=@project AND Revision<2) THROW 51000,'Restore must invalidate stale map editors.',1; + ROLLBACK; + SELECT 'PASS structured map backup/restore roundtrip with geometry, hierarchy, Location links and stale-editor invalidation (rolled back)' AS Result; +END TRY +BEGIN CATCH + IF @@TRANCOUNT>0 ROLLBACK; + THROW; +END CATCH; diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 74db343a..555f6ad6 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -91,7 +91,7 @@ internal static class ToolbarBrowserHost builder.Services.AddSingleton(new StoryCalendarService(new FakeTimelineRepository(CalendarNavigationTests.Data()))); var app = builder.Build(); app.UseWritingSolverReviewBoundary(); - app.Urls.Add("http://127.0.0.1:5238"); + app.Urls.Add(Environment.GetEnvironmentVariable("PD_BROWSER_FIXTURE_URL") ?? "http://127.0.0.1:5238"); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.GetFullPath("PlotLine/wwwroot")) }); app.Use(async (context, next) => { @@ -205,6 +205,7 @@ internal static class ToolbarBrowserHost model.Book = scene.Book; model.Books = scene.Book is null ? [] : [scene.Book]; } + if (context.Request.Query["page"] == "maps") { model.ActiveSection = "Maps"; route.Values["controller"] = "Maps"; } var menu = await Render("Shared/_ApplicationShell"); var toolbar = ""; var calendar = new StoryCalendarViewModel { Project = model.Project ?? new(), SelectedBookID = model.Book?.BookID, @@ -226,7 +227,7 @@ internal static class ToolbarBrowserHost calendar.EarliestStoryDate = new DateOnly(2026, 10, 3); calendar.LatestStoryDate = new DateOnly(2026, 10, 24); } - var surface = dashboardPage || context.Request.Query["page"] == "relationships" ? "" : await Render("StoryCalendar/_StoryCalendarSurface", calendar); + var surface = dashboardPage || context.Request.Query["page"] == "relationships" || context.Request.Query["page"] == "maps" ? "" : await Render("StoryCalendar/_StoryCalendarSurface", calendar); if (context.Request.Query["page"] == "calendar-test") surface = "
" + surface + "
"; if (timelinePage) @@ -343,6 +344,15 @@ internal static class ToolbarBrowserHost surface = await Render("RelationshipMap/Index", relationships); surface += await Render("RelationshipMap/_GraphScripts", relationships); } + if (context.Request.Query["page"] == "maps") + { + var map = new StoryMap { MapID = 1, ProjectID = 7, Name = "Working geography", Kind = "Region" }; + surface = await Render("Maps/Index", new MapsViewModel { + 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 += ""; + } surface += await Render("Shared/_ConfirmationDialog"); var initialTheme = appearance.ThemeKey ?? "warm-light"; var appearanceScript = ""; diff --git a/PlotLine/Controllers/MapsController.cs b/PlotLine/Controllers/MapsController.cs new file mode 100644 index 00000000..47699460 --- /dev/null +++ b/PlotLine/Controllers/MapsController.cs @@ -0,0 +1,61 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Data.SqlClient; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; +namespace PlotLine.Controllers; + +[Authorize] +public sealed class MapsController(MapRepository maps, IProjectRepository projects, ILocationRepository locations, + IFloorPlanRepository floorPlans, IProjectAccessService access, ICurrentUserService currentUser) : Controller +{ + private int UserID => currentUser.UserId!.Value; + public async Task Index(int projectId, int? id) + { + if (!await access.CanAccessProjectAsync(projectId)) return NotFound(); + var project = await projects.GetForUserAsync(projectId, UserID); + 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(); + return View(new MapsViewModel { Project = project, Maps = await maps.ListAsync(projectId, UserID), Document = document, + Locations = await locations.ListByProjectAsync(projectId), FloorPlans = await floorPlans.ListByProjectAsync(projectId) }); + } + [HttpGet] + public async Task State(int projectId, int id) + { + if (!await access.CanAccessProjectAsync(projectId)) return NotFound(); + var document = await maps.GetAsync(projectId, id, UserID); + return document is null ? NotFound() : Json(document); + } + [HttpPost, ValidateAntiForgeryToken] + public async Task Create(StoryMap model) + { + if (!await access.CanAccessProjectAsync(model.ProjectID)) return NotFound(); + if (!ModelState.IsValid || !MapValidation.Kinds.Contains(model.Kind)) return BadRequest("Choose a map name and kind."); + try { return Json(new { id = await maps.CreateAsync(model, UserID) }); } + catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); } + } + [HttpPost, ValidateAntiForgeryToken, RequestSizeLimit(8_000_000)] + public async Task Save([FromBody] MapDocument document) + { + if (document is null || document.Map is null) return BadRequest(new { message = "Choose a map." }); + if (!await access.CanAccessProjectAsync(document.Map.ProjectID)) return NotFound(); + if (!ModelState.IsValid) return BadRequest(new { message = "Check map fields." }); + var error = MapValidation.Validate(document); + if (error is not null) return BadRequest(new { message = error }); + try + { + await maps.SaveAsync(document, UserID); + return Json(await maps.GetAsync(document.Map.ProjectID, document.Map.MapID, UserID)); + } + catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); } + } + [HttpPost, ValidateAntiForgeryToken] + public async Task Delete(int projectId, int id, int revision) + { + if (!await access.CanAccessProjectAsync(projectId)) return NotFound(); + try { await maps.DeleteAsync(projectId, id, revision, UserID); return Json(new { ok = true }); } + catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); } + } +} diff --git a/PlotLine/Data/MapRepository.cs b/PlotLine/Data/MapRepository.cs new file mode 100644 index 00000000..367c3668 --- /dev/null +++ b/PlotLine/Data/MapRepository.cs @@ -0,0 +1,39 @@ +using System.Data; +using System.Text.Json; +using Dapper; +using PlotLine.Models; +namespace PlotLine.Data; + +public sealed class MapRepository(ISqlConnectionFactory connections) +{ + public async Task> ListAsync(int projectId, int userId) + { + using var db = connections.CreateConnection(); + return (await db.QueryAsync("dbo.StoryMap_List", new { ProjectID = projectId, UserID = userId }, commandType: CommandType.StoredProcedure)).ToList(); + } + public async Task GetAsync(int projectId, int mapId, int userId) + { + using var db = connections.CreateConnection(); + using var rows = await db.QueryMultipleAsync("dbo.StoryMap_Get", new { ProjectID = projectId, MapID = mapId, UserID = userId }, commandType: CommandType.StoredProcedure); + var map = await rows.ReadSingleOrDefaultAsync(); + var features = (await rows.ReadAsync()).ToList(); + var relationships = (await rows.ReadAsync()).ToList(); + return map is null ? null : new() { Map = map, Features = features, Relationships = relationships }; + } + public async Task CreateAsync(StoryMap map, int userId) + { + using var db = connections.CreateConnection(); + return await db.QuerySingleAsync("dbo.StoryMap_Create", new { map.ProjectID, UserID = userId, map.Name, map.Kind, map.ParentMapID, map.ParentFeatureID }, commandType: CommandType.StoredProcedure); + } + public async Task SaveAsync(MapDocument document, int userId) + { + using var db = connections.CreateConnection(); + await db.ExecuteAsync("dbo.StoryMap_Save", new { document.Map.ProjectID, document.Map.MapID, UserID = userId, document.Map.Revision, document.Map.Name, document.Map.Kind, + Features = JsonSerializer.Serialize(document.Features), Relationships = JsonSerializer.Serialize(document.Relationships) }, commandType: CommandType.StoredProcedure); + } + public async Task DeleteAsync(int projectId, int mapId, int revision, int userId) + { + using var db = connections.CreateConnection(); + await db.ExecuteAsync("dbo.StoryMap_Delete", new { ProjectID = projectId, MapID = mapId, Revision = revision, UserID = userId }, commandType: CommandType.StoredProcedure); + } +} diff --git a/PlotLine/Data/ProjectBackupRepository.cs b/PlotLine/Data/ProjectBackupRepository.cs index becdfa60..9a8a81e5 100644 --- a/PlotLine/Data/ProjectBackupRepository.cs +++ b/PlotLine/Data/ProjectBackupRepository.cs @@ -80,6 +80,13 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact return null; } + using (var mapRows = await connection.QueryMultipleAsync("dbo.StoryMap_Backup", new { ProjectID = projectId, UserID = userId }, commandType: CommandType.StoredProcedure)) + { + data.StoryMaps = (await mapRows.ReadAsync()).ToList(); + data.MapFeatures = (await mapRows.ReadAsync()).ToList(); + data.MapRelationships = (await mapRows.ReadAsync()).ToList(); + } + var bookMetadata = (await connection.QueryAsync( "dbo.ProjectBackup_BookMetadata_List", new { ProjectID = projectId }, @@ -141,6 +148,9 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact nameof(data.RelationshipEvents), nameof(data.Locations), nameof(data.LocationRelationships), + nameof(data.StoryMaps), + nameof(data.MapFeatures), + nameof(data.MapRelationships), nameof(data.FloorPlans), nameof(data.FloorPlanFloors), nameof(data.FloorPlanBlocks), diff --git a/PlotLine/Models/MapModels.cs b/PlotLine/Models/MapModels.cs new file mode 100644 index 00000000..32b97ac7 --- /dev/null +++ b/PlotLine/Models/MapModels.cs @@ -0,0 +1,68 @@ +using System.ComponentModel.DataAnnotations; +namespace PlotLine.Models; + +public sealed class StoryMap +{ + public int MapID { get; set; } + public int ProjectID { get; set; } + public int? ParentMapID { get; set; } + public Guid? ParentFeatureID { get; set; } + [Required, StringLength(200)] public string Name { get; set; } = "New map"; + [Required, StringLength(40)] public string Kind { get; set; } = "Region"; + public int Revision { get; set; } +} +public sealed class MapFeature +{ + public int MapID { get; set; } + public Guid FeatureID { get; set; } = Guid.NewGuid(); + [Required, StringLength(200)] public string Name { get; set; } = ""; + [Required, StringLength(60)] public string Type { get; set; } = "Custom"; + public string GeometryClass { get; set; } = "Marker"; + public string Layer { get; set; } = "Places"; + public double X { get; set; } + public double Y { get; set; } + public double Width { get; set; } = 48; + public double Height { get; set; } = 48; + public double Rotation { get; set; } + public int ZOrder { get; set; } + public bool IsPlaced { get; set; } = true; + public bool IsProvisional { get; set; } = true; + public bool IsLocked { get; set; } + public bool ShowLabel { get; set; } = true; + public double LabelX { get; set; } + public double LabelY { get; set; } + public int? LocationID { get; set; } + public bool CreateLocation { get; set; } + public int? FloorPlanID { get; set; } + public Guid? StartFeatureID { get; set; } + public Guid? EndFeatureID { get; set; } + public string GeometryJson { get; set; } = "{}"; + [StringLength(4000)] public string? Notes { get; set; } +} +public sealed class MapRelationship +{ + public int MapID { get; set; } + public Guid RelationshipID { get; set; } = Guid.NewGuid(); + public Guid SourceID { get; set; } + public Guid TargetID { get; set; } + public string? Direction { get; set; } + public string? RelativeDistance { get; set; } + public decimal? MeasuredDistance { get; set; } + [StringLength(30)] public string? Unit { get; set; } + [StringLength(120)] public string? TypicalTravelTime { get; set; } + [StringLength(1000)] public string? Notes { get; set; } +} +public sealed class MapDocument +{ + public StoryMap Map { get; set; } = new(); + public List Features { get; set; } = []; + public List Relationships { get; set; } = []; +} +public sealed class MapsViewModel +{ + public Project Project { get; set; } = new(); + public IReadOnlyList Maps { get; set; } = []; + public IReadOnlyList Locations { get; set; } = []; + public IReadOnlyList FloorPlans { get; set; } = []; + public MapDocument? Document { get; set; } +} diff --git a/PlotLine/Models/ProjectBackupModels.cs b/PlotLine/Models/ProjectBackupModels.cs index 603766fe..7cfde999 100644 --- a/PlotLine/Models/ProjectBackupModels.cs +++ b/PlotLine/Models/ProjectBackupModels.cs @@ -13,6 +13,9 @@ public sealed class ProjectBackupExport public sealed class ProjectBackupData { + public IReadOnlyList StoryMaps { get; set; } = []; + public IReadOnlyList MapFeatures { get; set; } = []; + public IReadOnlyList MapRelationships { get; set; } = []; public IReadOnlyList Books { get; init; } = []; public IReadOnlyList Chapters { get; init; } = []; public IReadOnlyList Scenes { get; init; } = []; diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index aa46f03f..71139f7c 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -141,6 +141,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/PlotLine/Services/ApplicationRibbon.cs b/PlotLine/Services/ApplicationRibbon.cs index 81a8f1ca..b042de17 100644 --- a/PlotLine/Services/ApplicationRibbon.cs +++ b/PlotLine/Services/ApplicationRibbon.cs @@ -33,7 +33,7 @@ public static class ApplicationRibbon new("Manuscript review", S("review")), new("Library", S("overview"), new("Add book", "bible", "Books", "Create"))), new("story", "Story", new("Story structure", S("timeline"), S("calendar"), S("plotlines"), S("threads"), S("point")), new("Analysis & planning", S("review"), S("scenarios"), S("continuity")), new("Writing", S("writer"))), new("characters", "Characters", new("Cast", S("characters"), S("names")), new("Connections", S("relationships"))), - new("world", "World", new("Setting", S("locations"), S("floorplans")), new("Story world", S("assets"))), + new("world", "World", new("Setting", S("locations"), new("Maps", "floorplans", "Maps", "Index"), S("floorplans")), new("Story world", S("assets"))), new("tools", "Tools", new("Reference", S("bible")), new("Insights", S("metrics"), S("health"), S("warnings")), new("Organisation", S("archive"))), new("help", "Help", new RibbonGroup("Support", new("Help Centre", "bible", "Help", "Index", "global"), new("Feature Requests", "review", "FeatureRequests", "Index", "global"))) ]; @@ -45,7 +45,7 @@ public static class ApplicationRibbon { "Timeline" or "Calendar" or "At This Point" or "Plot Lines" or "Threads" or "Scenarios" or "Continuity Explorer" => "story", "Characters" or "Names" or "Relationships" => "characters", - "Locations" or "Assets" or "Floor Plans" => "world", + "Locations" or "Assets" or "Maps" or "Floor Plans" => "world", "Story Bible" or "Metrics" or "Health" or "Warnings" or "Archive" => "tools", _ => "project" } }; diff --git a/PlotLine/Services/MapValidation.cs b/PlotLine/Services/MapValidation.cs new file mode 100644 index 00000000..fe0e05ed --- /dev/null +++ b/PlotLine/Services/MapValidation.cs @@ -0,0 +1,46 @@ +using System.Text.Json; +using PlotLine.Models; +namespace PlotLine.Services; + +public static class MapValidation +{ + public static readonly string[] Kinds = ["World", "Continent", "Region", "Country/Kingdom", "Island", "City/Town", "Local Area", "Other"]; + public static readonly string[] Directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]; + public static readonly string[] Distances = ["Very close", "Close", "Moderate", "Far", "Very far"]; + public static string? Validate(MapDocument d) + { + if (string.IsNullOrWhiteSpace(d.Map.Name) || d.Map.Name.Length > 200 || !Kinds.Contains(d.Map.Kind)) return "Choose a map name and kind."; + if (d.Features.Count > 3000 || d.Relationships.Count > 10000) return "This map has too many items. Consider a detailed child map."; + var ids = d.Features.Select(x => x.FeatureID).ToHashSet(); + if (ids.Contains(Guid.Empty) || ids.Count != d.Features.Count) return "Feature identifiers must be unique."; + var markers = d.Features.Where(x => x.GeometryClass == "Marker").Select(x => x.FeatureID).ToHashSet(); + foreach (var f in d.Features) + { + if (string.IsNullOrWhiteSpace(f.Name) || f.Name.Length > 200 || f.Type.Length > 60 || f.Layer.Length > 30 || f.Notes?.Length > 4000) return "Check feature names and notes."; + if (!new[] { "Marker", "Path", "Area" }.Contains(f.GeometryClass)) return "Unknown map piece shape."; + if (new[] { f.X, f.Y, f.Width, f.Height, f.Rotation, f.LabelX, f.LabelY }.Any(x => !double.IsFinite(x) || Math.Abs(x) > 100000) || f.Width < 1 || f.Height < 1) return "Check feature dimensions."; + if ((f.StartFeatureID.HasValue && !markers.Contains(f.StartFeatureID.Value)) || (f.EndFeatureID.HasValue && !markers.Contains(f.EndFeatureID.Value))) return "Choose route endpoints on this map."; + if (f.CreateLocation && f.LocationID is null && f.IsProvisional) return "Establish the place before creating a story Location, or leave it as a planning feature."; + if (f.GeometryJson.Length > 64000) return "Shape is too detailed."; + try + { + using var geometry = JsonDocument.Parse(f.GeometryJson); + if (geometry.RootElement.ValueKind != JsonValueKind.Object) return "Invalid shape data."; + if (geometry.RootElement.TryGetProperty("points", out var points)) + { + if (points.ValueKind != JsonValueKind.Array || points.GetArrayLength() is < 2 or > 64) return "Use between two and 64 shape points."; + foreach (var point in points.EnumerateArray()) + if (point.ValueKind != JsonValueKind.Array || point.GetArrayLength() != 2 || point.EnumerateArray().Any(v => v.ValueKind != JsonValueKind.Number || !v.TryGetDouble(out var n) || !double.IsFinite(n) || Math.Abs(n) > 10)) return "Invalid shape point."; + } + } + catch (JsonException) { return "Invalid shape data."; } + } + if (d.Relationships.Select(x => x.RelationshipID).Distinct().Count() != d.Relationships.Count) return "Relationship identifiers must be unique."; + foreach (var r in d.Relationships) + if (!ids.Contains(r.SourceID) || !ids.Contains(r.TargetID) || r.SourceID == r.TargetID + || (r.Direction is not null && !Directions.Contains(r.Direction)) || (r.RelativeDistance is not null && !Distances.Contains(r.RelativeDistance)) + || r.MeasuredDistance is < 0 or > 999999999999999m || r.Unit?.Length > 30 || r.TypicalTravelTime?.Length > 120 || r.Notes?.Length > 1000) + return "Check relationship endpoints, direction and distance."; + return null; + } +} diff --git a/PlotLine/Sql/208_StoryMaps.sql b/PlotLine/Sql/208_StoryMaps.sql new file mode 100644 index 00000000..5fe0e4de --- /dev/null +++ b/PlotLine/Sql/208_StoryMaps.sql @@ -0,0 +1,170 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +IF OBJECT_ID('dbo.StoryMaps','U') IS NULL +BEGIN + CREATE TABLE dbo.StoryMaps ( + MapID int IDENTITY PRIMARY KEY, ProjectID int NOT NULL REFERENCES dbo.Projects(ProjectID) ON DELETE CASCADE, + ParentMapID int NULL REFERENCES dbo.StoryMaps(MapID), ParentFeatureID uniqueidentifier NULL, + Name nvarchar(200) NOT NULL, Kind nvarchar(40) NOT NULL, Revision int NOT NULL DEFAULT 0, + ModifiedDate datetime2 NOT NULL DEFAULT SYSUTCDATETIME()); + CREATE INDEX IX_StoryMaps_Project ON dbo.StoryMaps(ProjectID); + CREATE INDEX IX_StoryMaps_Parent ON dbo.StoryMaps(ParentMapID); +END; +GO +IF OBJECT_ID('dbo.MapFeatures','U') IS NULL +BEGIN + CREATE TABLE dbo.MapFeatures (MapID int NOT NULL REFERENCES dbo.StoryMaps(MapID) ON DELETE CASCADE, + [FeatureID] uniqueidentifier NOT NULL, + [Name] nvarchar(200) NOT NULL, + [Type] nvarchar(60) NOT NULL, + [GeometryClass] nvarchar(12) NOT NULL, + [Layer] nvarchar(30) NOT NULL, + [X] float NOT NULL, + [Y] float NOT NULL, + [Width] float NOT NULL, + [Height] float NOT NULL, + [Rotation] float NOT NULL, + [ZOrder] int NOT NULL, + [IsPlaced] bit NOT NULL, + [IsProvisional] bit NOT NULL, + [IsLocked] bit NOT NULL, + [ShowLabel] bit NOT NULL, + [LabelX] float NOT NULL, + [LabelY] float NOT NULL, + [LocationID] int NULL, + [FloorPlanID] int NULL, + [StartFeatureID] uniqueidentifier NULL, + [EndFeatureID] uniqueidentifier NULL, + [GeometryJson] nvarchar(max) NOT NULL, + [Notes] nvarchar(4000) NULL, CONSTRAINT PK_MapFeatures PRIMARY KEY(MapID,FeatureID), CONSTRAINT CK_MapFeatures_Geometry CHECK(ISJSON(GeometryJson)=1 AND GeometryClass IN ('Marker','Path','Area') AND Width>0 AND Height>0), CONSTRAINT FK_MapFeatures_Location FOREIGN KEY(LocationID) REFERENCES dbo.Locations(LocationID) ON DELETE SET NULL, CONSTRAINT FK_MapFeatures_FloorPlan FOREIGN KEY(FloorPlanID) REFERENCES dbo.FloorPlans(FloorPlanID) ON DELETE SET NULL); +END; +GO +IF OBJECT_ID('dbo.MapRelationships','U') IS NULL +BEGIN + CREATE TABLE dbo.MapRelationships (MapID int NOT NULL REFERENCES dbo.StoryMaps(MapID) ON DELETE CASCADE, + [RelationshipID] uniqueidentifier NOT NULL, + [SourceID] uniqueidentifier NOT NULL, + [TargetID] uniqueidentifier NOT NULL, + [Direction] nvarchar(2) NULL, + [RelativeDistance] nvarchar(12) NULL, + [MeasuredDistance] decimal(18,3) NULL, + [Unit] nvarchar(30) NULL, + [TypicalTravelTime] nvarchar(120) NULL, + [Notes] nvarchar(1000) NULL, CONSTRAINT PK_MapRelationships PRIMARY KEY(MapID,RelationshipID), CONSTRAINT FK_MapRelationships_Source FOREIGN KEY(MapID,SourceID) REFERENCES dbo.MapFeatures(MapID,FeatureID), CONSTRAINT FK_MapRelationships_Target FOREIGN KEY(MapID,TargetID) REFERENCES dbo.MapFeatures(MapID,FeatureID), CONSTRAINT CK_MapRelationships_Distance CHECK(MeasuredDistance IS NULL OR MeasuredDistance>=0)); +END; +GO +CREATE OR ALTER PROCEDURE dbo.StoryMap_Authorize @ProjectID int, @UserID int +AS +BEGIN + SET NOCOUNT ON; + DECLARE @a table(Allowed bit); + INSERT @a EXEC dbo.ProjectAccess_UserCanAccess @ProjectID=@ProjectID,@UserID=@UserID; + IF NOT EXISTS(SELECT 1 FROM @a WHERE Allowed=1) THROW 51000,'Map project unavailable.',1; +END; +GO +CREATE OR ALTER PROCEDURE dbo.StoryMap_List @ProjectID int, @UserID int +AS +BEGIN + SET NOCOUNT ON; + EXEC dbo.StoryMap_Authorize @ProjectID,@UserID; + SELECT MapID,ProjectID,ParentMapID,ParentFeatureID,Name,Kind,Revision FROM dbo.StoryMaps WHERE ProjectID=@ProjectID ORDER BY Name,MapID; +END; +GO +CREATE OR ALTER PROCEDURE dbo.StoryMap_Get @ProjectID int, @MapID int, @UserID int +AS +BEGIN + SET NOCOUNT ON; + EXEC dbo.StoryMap_Authorize @ProjectID,@UserID; + SELECT MapID,ProjectID,ParentMapID,ParentFeatureID,Name,Kind,Revision FROM dbo.StoryMaps WHERE MapID=@MapID AND ProjectID=@ProjectID; + SELECT f.* FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.MapID=@MapID AND m.ProjectID=@ProjectID ORDER BY f.ZOrder,f.FeatureID; + SELECT r.* FROM dbo.MapRelationships r JOIN dbo.StoryMaps m ON m.MapID=r.MapID WHERE m.MapID=@MapID AND m.ProjectID=@ProjectID ORDER BY r.RelationshipID; +END; +GO +CREATE OR ALTER PROCEDURE dbo.StoryMap_Create @ProjectID int,@UserID int,@Name nvarchar(200),@Kind nvarchar(40),@ParentMapID int=NULL,@ParentFeatureID uniqueidentifier=NULL +AS +BEGIN + SET NOCOUNT ON; SET XACT_ABORT ON; + BEGIN TRAN; + EXEC dbo.StoryMap_Authorize @ProjectID,@UserID; + IF @ParentMapID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.StoryMaps WITH(UPDLOCK,HOLDLOCK) WHERE MapID=@ParentMapID AND ProjectID=@ProjectID) THROW 51000,'Choose a parent map in this project.',1; + IF @ParentFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.MapFeatures WHERE MapID=@ParentMapID AND FeatureID=@ParentFeatureID) THROW 51000,'Parent feature unavailable.',1; + INSERT dbo.StoryMaps(ProjectID,Name,Kind,ParentMapID,ParentFeatureID) VALUES(@ProjectID,@Name,@Kind,@ParentMapID,@ParentFeatureID); + DECLARE @id int=CONVERT(int,SCOPE_IDENTITY()); + COMMIT; + SELECT @id; +END; +GO +CREATE OR ALTER PROCEDURE dbo.StoryMap_Delete @ProjectID int,@MapID int,@UserID int,@Revision int +AS +BEGIN + SET NOCOUNT ON; SET XACT_ABORT ON; + BEGIN TRAN; + EXEC dbo.StoryMap_Authorize @ProjectID,@UserID; + IF NOT EXISTS(SELECT 1 FROM dbo.StoryMaps WITH(UPDLOCK,HOLDLOCK) WHERE MapID=@MapID AND ProjectID=@ProjectID AND Revision=@Revision) THROW 51000,'Map changed. Reload before deleting.',1; + -- Detailed maps survive; deleting a map never deletes story Locations or Floor Plans. + UPDATE dbo.StoryMaps SET ParentMapID=NULL,ParentFeatureID=NULL,Revision=Revision+1 WHERE ParentMapID=@MapID; + DELETE dbo.MapRelationships WHERE MapID=@MapID; + DELETE dbo.MapFeatures WHERE MapID=@MapID; + DELETE dbo.StoryMaps WHERE MapID=@MapID; + COMMIT; +END; +GO +CREATE OR ALTER PROCEDURE dbo.StoryMap_Save @ProjectID int,@MapID int,@UserID int,@Revision int,@Name nvarchar(200),@Kind nvarchar(40),@Features nvarchar(max),@Relationships nvarchar(max) +AS +BEGIN + SET NOCOUNT ON; SET XACT_ABORT ON; + BEGIN TRAN; + EXEC dbo.StoryMap_Authorize @ProjectID,@UserID; + IF NOT EXISTS(SELECT 1 FROM dbo.StoryMaps WITH(UPDLOCK,HOLDLOCK) WHERE MapID=@MapID AND ProjectID=@ProjectID AND Revision=@Revision) THROW 51000,'Map changed in another window. Reload before saving; your edits are still here.',1; + SELECT * INTO #f FROM OPENJSON(@Features) WITH ( +[FeatureID] uniqueidentifier '$.FeatureID', +[Name] nvarchar(200) '$.Name', +[Type] nvarchar(60) '$.Type', +[GeometryClass] nvarchar(12) '$.GeometryClass', +[Layer] nvarchar(30) '$.Layer', +[X] float '$.X', +[Y] float '$.Y', +[Width] float '$.Width', +[Height] float '$.Height', +[Rotation] float '$.Rotation', +[ZOrder] int '$.ZOrder', +[IsPlaced] bit '$.IsPlaced', +[IsProvisional] bit '$.IsProvisional', +[IsLocked] bit '$.IsLocked', +[ShowLabel] bit '$.ShowLabel', +[LabelX] float '$.LabelX', +[LabelY] float '$.LabelY', +[LocationID] int '$.LocationID', +[FloorPlanID] int '$.FloorPlanID', +[StartFeatureID] uniqueidentifier '$.StartFeatureID', +[EndFeatureID] uniqueidentifier '$.EndFeatureID', +[GeometryJson] nvarchar(max) '$.GeometryJson', +[Notes] nvarchar(4000) '$.Notes',CreateLocation bit '$.CreateLocation'); + IF EXISTS(SELECT 1 FROM #f f WHERE LocationID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Locations l WHERE l.LocationID=f.LocationID AND l.ProjectID=@ProjectID)) THROW 51000,'Choose Locations in this project.',1; + IF EXISTS(SELECT 1 FROM #f f WHERE FloorPlanID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.FloorPlans l WHERE l.FloorPlanID=f.FloorPlanID AND l.ProjectID=@ProjectID)) THROW 51000,'Choose Floor Plans in this project.',1; + IF EXISTS(SELECT 1 FROM #f f WHERE (StartFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM #f x WHERE x.FeatureID=f.StartFeatureID AND x.GeometryClass='Marker')) OR (EndFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM #f x WHERE x.FeatureID=f.EndFeatureID AND x.GeometryClass='Marker'))) THROW 51000,'Route endpoints must be places on this map.',1; + -- Create only on explicit request, atomically with the map revision. Retry cannot duplicate a Location. + DECLARE @fid uniqueidentifier,@label nvarchar(200),@lid int; + DECLARE @created table(ID int); + DECLARE places CURSOR LOCAL FAST_FORWARD FOR SELECT FeatureID,Name FROM #f WHERE CreateLocation=1 AND LocationID IS NULL; + OPEN places; FETCH NEXT FROM places INTO @fid,@label; + WHILE @@FETCH_STATUS=0 + BEGIN + DELETE FROM @created; + INSERT @created EXEC dbo.Location_Save @ProjectID=@ProjectID,@LocationName=@label; + SELECT @lid=ID FROM @created; + UPDATE #f SET LocationID=@lid WHERE FeatureID=@fid; + FETCH NEXT FROM places INTO @fid,@label; + END; + CLOSE places; DEALLOCATE places; + DELETE dbo.MapRelationships WHERE MapID=@MapID; + -- Detach links to removed parent features, preserving the detailed maps themselves. + UPDATE dbo.StoryMaps SET ParentFeatureID=NULL,Revision=Revision+1 WHERE ParentMapID=@MapID AND ParentFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM #f WHERE FeatureID=ParentFeatureID); + DELETE dbo.MapFeatures WHERE MapID=@MapID; + INSERT dbo.MapFeatures(MapID,[FeatureID],[Name],[Type],[GeometryClass],[Layer],[X],[Y],[Width],[Height],[Rotation],[ZOrder],[IsPlaced],[IsProvisional],[IsLocked],[ShowLabel],[LabelX],[LabelY],[LocationID],[FloorPlanID],[StartFeatureID],[EndFeatureID],[GeometryJson],[Notes]) SELECT @MapID,[FeatureID],[Name],[Type],[GeometryClass],[Layer],[X],[Y],[Width],[Height],[Rotation],[ZOrder],[IsPlaced],[IsProvisional],[IsLocked],[ShowLabel],[LabelX],[LabelY],[LocationID],[FloorPlanID],[StartFeatureID],[EndFeatureID],[GeometryJson],[Notes] FROM #f; + INSERT dbo.MapRelationships(MapID,[RelationshipID],[SourceID],[TargetID],[Direction],[RelativeDistance],[MeasuredDistance],[Unit],[TypicalTravelTime],[Notes]) SELECT @MapID,[RelationshipID],[SourceID],[TargetID],[Direction],[RelativeDistance],[MeasuredDistance],[Unit],[TypicalTravelTime],[Notes] FROM OPENJSON(@Relationships) WITH ([RelationshipID] uniqueidentifier '$.RelationshipID',[SourceID] uniqueidentifier '$.SourceID',[TargetID] uniqueidentifier '$.TargetID',[Direction] nvarchar(2) '$.Direction',[RelativeDistance] nvarchar(12) '$.RelativeDistance',[MeasuredDistance] decimal(18,3) '$.MeasuredDistance',[Unit] nvarchar(30) '$.Unit',[TypicalTravelTime] nvarchar(120) '$.TypicalTravelTime',[Notes] nvarchar(1000) '$.Notes'); + UPDATE dbo.StoryMaps SET Name=@Name,Kind=@Kind,Revision=Revision+1,ModifiedDate=SYSUTCDATETIME() WHERE MapID=@MapID; + COMMIT; +END; +GO diff --git a/PlotLine/Sql/209_StoryMapsBackupRestore.sql b/PlotLine/Sql/209_StoryMapsBackupRestore.sql new file mode 100644 index 00000000..596081f6 --- /dev/null +++ b/PlotLine/Sql/209_StoryMapsBackupRestore.sql @@ -0,0 +1,246 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.StoryMap_Backup @ProjectID int,@UserID int=NULL +AS +BEGIN + SET NOCOUNT ON; + -- Same internal/null-user convention as ProjectBackup_Export; public export checks ownership first. + IF @UserID IS NOT NULL EXEC dbo.StoryMap_Authorize @ProjectID,@UserID; + SELECT MapID,ProjectID,ParentMapID,ParentFeatureID,Name,Kind,Revision FROM dbo.StoryMaps WHERE ProjectID=@ProjectID ORDER BY MapID; + SELECT f.* FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@ProjectID ORDER BY f.MapID,f.FeatureID; + SELECT r.* FROM dbo.MapRelationships r JOIN dbo.StoryMaps m ON m.MapID=r.MapID WHERE m.ProjectID=@ProjectID ORDER BY r.MapID,r.RelationshipID; +END; +GO +CREATE OR ALTER PROCEDURE dbo.ProjectRestore_ApplyFromJson + @ProjectID int, + @SourceRestorePointID int = NULL, + @SafetyRestorePointID int = NULL, + @JsonData nvarchar(max) +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + + IF ISJSON(@JsonData) <> 1 + THROW 51001, 'Restore JSON is invalid.', 1; + + IF JSON_VALUE(@JsonData, '$.Format') <> N'PlotDirector.ProjectBackup' + THROW 51002, 'Restore JSON format is not recognised.', 1; + + IF JSON_VALUE(@JsonData, '$.FormatVersion') NOT IN (N'1.0', N'1.1') + THROW 51003, 'Restore JSON format version is not supported.', 1; + + IF TRY_CONVERT(int, JSON_VALUE(@JsonData, '$.Project.ProjectID')) <> @ProjectID + THROW 51004, 'Restore point does not belong to this project.', 1; + + DECLARE @RestoreTables table (TableName sysname NOT NULL PRIMARY KEY); + INSERT INTO @RestoreTables (TableName) + VALUES + (N'ProjectTimelineSettings'), (N'ProjectTimelineMetricSettings'), (N'TimelineViewPresets'), + (N'SceneMetricTypes'), (N'SceneMetricValues'), (N'Books'), (N'Chapters'), (N'Scenes'), + (N'ScenePurposes'), (N'SceneOutcomes'), (N'PlotLines'), (N'PlotThreads'), (N'ThreadEvents'), + (N'AssetStates'), (N'StoryAssets'), (N'AssetEvents'), (N'AssetDependencies'), + (N'AssetCustodyEvents'), (N'AssetCustodyEventCharacters'), (N'Characters'), (N'SceneCharacters'), + (N'CharacterAttributeTypes'), (N'CharacterAttributeEvents'), (N'CharacterKnowledge'), + (N'CharacterRelationships'), (N'RelationshipEvents'), (N'Locations'), (N'LocationRelationships'), + (N'StoryMaps'), (N'MapFeatures'), (N'MapRelationships'), + (N'FloorPlans'), (N'FloorPlanFloors'), (N'FloorPlanBlocks'), (N'FloorPlanTransitions'), + (N'SceneAssetLocations'), (N'SceneFloorPlanOccupancy'), (N'SceneDependencies'), (N'ValidationRuns'), (N'ContinuityWarnings'), + (N'SceneNotes'), (N'SceneWorkflow'), (N'SceneChecklistItems'), (N'SceneAttachments'), + (N'ChapterGoals'), (N'Scenarios'), (N'ScenarioSceneOrder'), (N'ScenarioValidationRuns'), + (N'ScenarioWarnings'); + + BEGIN TRANSACTION; + DECLARE @PreviousMapRevision int = ISNULL((SELECT MAX(Revision) FROM dbo.StoryMaps WHERE ProjectID=@ProjectID),0); + + + DECLARE @TableName sysname; + DECLARE DisableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables; + OPEN DisableCursor; + FETCH NEXT FROM DisableCursor INTO @TableName; + WHILE @@FETCH_STATUS = 0 + BEGIN + DECLARE @DisableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' NOCHECK CONSTRAINT ALL;'; + EXEC (@DisableSql); + FETCH NEXT FROM DisableCursor INTO @TableName; + END + CLOSE DisableCursor; + DEALLOCATE DisableCursor; + + DELETE r FROM dbo.MapRelationships r JOIN dbo.StoryMaps m ON m.MapID=r.MapID WHERE m.ProjectID=@ProjectID; + DELETE f FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@ProjectID; + DELETE dbo.StoryMaps WHERE ProjectID=@ProjectID; + + DELETE sw FROM dbo.ScenarioWarnings sw INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sw.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE svr FROM dbo.ScenarioValidationRuns svr INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = svr.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE sso FROM dbo.ScenarioSceneOrder sso INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sso.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE FROM dbo.Scenarios WHERE ProjectID = @ProjectID; + + DELETE FROM dbo.ContinuityWarnings WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ValidationRuns WHERE ProjectID = @ProjectID; + + DELETE sa FROM dbo.SceneAttachments sa INNER JOIN dbo.Scenes s ON s.SceneID = sa.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sci FROM dbo.SceneChecklistItems sci INNER JOIN dbo.Scenes s ON s.SceneID = sci.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sw FROM dbo.SceneWorkflow sw INNER JOIN dbo.Scenes s ON s.SceneID = sw.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sn FROM dbo.SceneNotes sn INNER JOIN dbo.Scenes s ON s.SceneID = sn.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE cg FROM dbo.ChapterGoals cg INNER JOIN dbo.Chapters c ON c.ChapterID = cg.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + + DELETE sfpo FROM dbo.SceneFloorPlanOccupancy sfpo + INNER JOIN dbo.Scenes s ON s.SceneID = sfpo.SceneID + INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID + INNER JOIN dbo.Books b ON b.BookID = c.BookID + WHERE b.ProjectID = @ProjectID; + + DELETE sd FROM dbo.SceneDependencies sd + LEFT JOIN dbo.Scenes ss ON ss.SceneID = sd.SourceSceneID + LEFT JOIN dbo.Chapters sc ON sc.ChapterID = ss.ChapterID + LEFT JOIN dbo.Books sb ON sb.BookID = sc.BookID + LEFT JOIN dbo.Scenes ts ON ts.SceneID = sd.TargetSceneID + LEFT JOIN dbo.Chapters tc ON tc.ChapterID = ts.ChapterID + LEFT JOIN dbo.Books tb ON tb.BookID = tc.BookID + WHERE sd.ProjectID = @ProjectID OR sb.ProjectID = @ProjectID OR tb.ProjectID = @ProjectID; + + DELETE re FROM dbo.RelationshipEvents re INNER JOIN dbo.CharacterRelationships cr ON cr.CharacterRelationshipID = re.CharacterRelationshipID WHERE cr.ProjectID = @ProjectID; + DELETE FROM dbo.CharacterRelationships WHERE ProjectID = @ProjectID; + DELETE ck FROM dbo.CharacterKnowledge ck INNER JOIN dbo.Characters ch ON ch.CharacterID = ck.CharacterID WHERE ch.ProjectID = @ProjectID; + DELETE cae FROM dbo.CharacterAttributeEvents cae INNER JOIN dbo.Characters ch ON ch.CharacterID = cae.CharacterID WHERE ch.ProjectID = @ProjectID; + DELETE sc FROM dbo.SceneCharacters sc INNER JOIN dbo.Characters ch ON ch.CharacterID = sc.CharacterID WHERE ch.ProjectID = @ProjectID; + + DELETE acec FROM dbo.AssetCustodyEventCharacters acec INNER JOIN dbo.AssetCustodyEvents ace ON ace.AssetCustodyEventID = acec.AssetCustodyEventID INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ace FROM dbo.AssetCustodyEvents ace INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ad FROM dbo.AssetDependencies ad INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ad.SourceAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ae FROM dbo.AssetEvents ae INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ae.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE sal FROM dbo.SceneAssetLocations sal INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = sal.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE FROM dbo.StoryAssets WHERE ProjectID = @ProjectID; + + DELETE fpt FROM dbo.FloorPlanTransitions fpt INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpt.FloorPlanFloorID INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE fpb FROM dbo.FloorPlanBlocks fpb INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpb.FloorPlanFloorID INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE fpf FROM dbo.FloorPlanFloors fpf INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE FROM dbo.FloorPlans WHERE ProjectID = @ProjectID; + + DELETE lr FROM dbo.LocationRelationships lr INNER JOIN dbo.Locations l ON l.LocationID = lr.FromLocationID WHERE l.ProjectID = @ProjectID; + DELETE FROM dbo.Locations WHERE ProjectID = @ProjectID; + + DELETE te FROM dbo.ThreadEvents te INNER JOIN dbo.PlotThreads pt ON pt.PlotThreadID = te.PlotThreadID INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID WHERE pl.ProjectID = @ProjectID; + DELETE pt FROM dbo.PlotThreads pt INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID WHERE pl.ProjectID = @ProjectID; + DELETE FROM dbo.PlotLines WHERE ProjectID = @ProjectID; + + DELETE FROM dbo.TimelineViewPresets WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ProjectTimelineMetricSettings WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ProjectTimelineSettings WHERE ProjectID = @ProjectID; + + DELETE smv FROM dbo.SceneMetricValues smv INNER JOIN dbo.Scenes s ON s.SceneID = smv.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE FROM dbo.SceneMetricTypes WHERE ProjectID = @ProjectID; + DELETE FROM dbo.CharacterAttributeTypes WHERE ProjectID = @ProjectID; + DELETE FROM dbo.AssetStates WHERE ProjectID = @ProjectID; + + DELETE sp FROM dbo.ScenePurposes sp INNER JOIN dbo.Scenes s ON s.SceneID = sp.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE so FROM dbo.SceneOutcomes so INNER JOIN dbo.Scenes s ON s.SceneID = so.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE s FROM dbo.Scenes s INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE c FROM dbo.Chapters c INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE FROM dbo.Books WHERE ProjectID = @ProjectID; + DELETE FROM dbo.Characters WHERE ProjectID = @ProjectID; + + UPDATE p + SET ProjectName = src.ProjectName, + Description = src.Description, + CreatedDate = src.CreatedDate, + UpdatedDate = SYSUTCDATETIME(), + IsArchived = src.IsArchived, + ArchivedDate = src.ArchivedDate, + ArchivedReason = src.ArchivedReason + FROM dbo.Projects p + CROSS APPLY OPENJSON(@JsonData, '$.Project') + WITH + ( + ProjectID int '$.ProjectID', + ProjectName nvarchar(200) '$.ProjectName', + Description nvarchar(max) '$.Description', + CreatedDate datetime2 '$.CreatedDate', + IsArchived bit '$.IsArchived', + ArchivedDate datetime2 '$.ArchivedDate', + ArchivedReason nvarchar(1000) '$.ArchivedReason' + ) src + WHERE p.ProjectID = @ProjectID AND src.ProjectID = @ProjectID; + + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneMetricTypes', N'$.Data.SceneMetricTypes', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetStates', N'$.Data.AssetStates', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAttributeTypes', N'$.Data.CharacterAttributeTypes', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'Books', N'$.Data.Books', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Chapters', N'$.Data.Chapters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Characters', N'$.Data.Characters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Locations', N'$.Data.Locations', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlans', N'$.Data.FloorPlans', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanFloors', N'$.Data.FloorPlanFloors', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanBlocks', N'$.Data.FloorPlanBlocks', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanTransitions', N'$.Data.FloorPlanTransitions', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Scenes', N'$.Data.Scenes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenePurposes', N'$.Data.ScenePurposes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneOutcomes', N'$.Data.SceneOutcomes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneMetricValues', N'$.Data.SceneMetricValues', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ProjectTimelineSettings', N'$.Data.TimelineSettings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ProjectTimelineMetricSettings', N'$.Data.TimelineMetricSettings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'TimelineViewPresets', N'$.Data.TimelineViewPresets', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'PlotLines', N'$.Data.PlotLines', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'PlotThreads', N'$.Data.PlotThreads', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ThreadEvents', N'$.Data.ThreadEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryAssets', N'$.Data.StoryAssets', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetEvents', N'$.Data.AssetEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetDependencies', N'$.Data.AssetDependencies', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetCustodyEvents', N'$.Data.AssetCustodyEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetCustodyEventCharacters', N'$.Data.AssetCustodyCharacters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneCharacters', N'$.Data.SceneCharacters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAttributeEvents', N'$.Data.CharacterAttributeEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterKnowledge', N'$.Data.CharacterKnowledge', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterRelationships', N'$.Data.CharacterRelationships', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'RelationshipEvents', N'$.Data.RelationshipEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'LocationRelationships', N'$.Data.LocationRelationships', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAssetLocations', N'$.Data.SceneAssetLocations', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneFloorPlanOccupancy', N'$.Data.SceneFloorPlanOccupancy', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneDependencies', N'$.Data.SceneDependencies', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ValidationRuns', N'$.Data.ValidationRuns', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ContinuityWarnings', N'$.Data.ContinuityWarnings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneNotes', N'$.Data.SceneNotes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneWorkflow', N'$.Data.SceneWorkflow', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneChecklistItems', N'$.Data.SceneChecklistItems', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAttachments', N'$.Data.SceneAttachments', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ChapterGoals', N'$.Data.ChapterGoals', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Scenarios', N'$.Data.Scenarios', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioSceneOrder', N'$.Data.ScenarioSceneOrder', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioValidationRuns', N'$.Data.ScenarioValidationRuns', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioWarnings', N'$.Data.ScenarioWarnings', @JsonData, @ProjectID, 0; + + -- Older backups contain no Maps sets. The automatic safety restore point preserves current geography. + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMaps', N'$.Data.StoryMaps', @JsonData, @ProjectID, 1; + IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapFeatures') WITH(MapID int '$.MapID') x WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=x.MapID AND m.ProjectID=@ProjectID)) + OR EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapRelationships') WITH(MapID int '$.MapID') x WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=x.MapID AND m.ProjectID=@ProjectID)) + THROW 51005,'Map backup contains features outside this project.',1; + EXEC dbo.ProjectRestore_InsertJsonTable N'MapFeatures', N'$.Data.MapFeatures', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'MapRelationships', N'$.Data.MapRelationships', @JsonData, @ProjectID, 0; + IF EXISTS(SELECT 1 FROM dbo.StoryMaps m JOIN dbo.StoryMaps parent ON parent.MapID=m.ParentMapID WHERE m.ProjectID=@ProjectID AND parent.ProjectID<>@ProjectID) + OR EXISTS(SELECT 1 FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID JOIN dbo.Locations l ON l.LocationID=f.LocationID WHERE m.ProjectID=@ProjectID AND l.ProjectID<>@ProjectID) + THROW 51005,'Map hierarchy or Location links cross projects.',1; + UPDATE dbo.StoryMaps SET Revision=CASE WHEN Revision>@PreviousMapRevision THEN Revision+1 ELSE @PreviousMapRevision+1 END WHERE ProjectID=@ProjectID; + + DECLARE EnableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables; + OPEN EnableCursor; + FETCH NEXT FROM EnableCursor INTO @TableName; + WHILE @@FETCH_STATUS = 0 + BEGIN + DECLARE @EnableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' WITH CHECK CHECK CONSTRAINT ALL;'; + EXEC (@EnableSql); + FETCH NEXT FROM EnableCursor INTO @TableName; + END + CLOSE EnableCursor; + DEALLOCATE EnableCursor; + + IF @SourceRestorePointID IS NOT NULL AND @SafetyRestorePointID IS NOT NULL + BEGIN + INSERT INTO dbo.ProjectRestoreHistory (ProjectID, SourceRestorePointID, SafetyRestorePointID, PerformedBy, Notes) + VALUES (@ProjectID, @SourceRestorePointID, @SafetyRestorePointID, SUSER_SNAME(), N'Project restored from saved restore point.'); + END; + + COMMIT TRANSACTION; +END; +GO diff --git a/PlotLine/Views/Maps/Index.cshtml b/PlotLine/Views/Maps/Index.cshtml new file mode 100644 index 00000000..cea4d93e --- /dev/null +++ b/PlotLine/Views/Maps/Index.cshtml @@ -0,0 +1,58 @@ +@model PlotLine.Models.MapsViewModel +@using System.Text.Json +@{ + ViewData["Title"] = Model.Document?.Map.Name ?? "Maps"; + ViewData["ProjectSection"] = "Maps"; + ViewData["ShellClass"] = "plotline-shell-wide maps-shell"; +} + + +
+
+

Maps

+
+
+
+ + +
Map actions
+
+ + +
+

Rough first. Detail later. Visual placement is never a physical scale.

+
+ +
+ +
+ + + + + + + + + + + +
100%Not to scale · N ↑
+
+ +
+

New map

Starter layouts contain editable shapes only. You name and define your world.

+

Arrange from relationships

Preview an arrangement using directions and relative distances. Known distances never control spacing.

+
+@Html.AntiForgeryToken() + +@section Scripts { + + +} diff --git a/PlotLine/Views/Shared/_ApplicationSectionMenus.cshtml b/PlotLine/Views/Shared/_ApplicationSectionMenus.cshtml index ea8eff6f..6b635a66 100644 --- a/PlotLine/Views/Shared/_ApplicationSectionMenus.cshtml +++ b/PlotLine/Views/Shared/_ApplicationSectionMenus.cshtml @@ -32,6 +32,7 @@
  • Assets
  • Locations
  • Floor Plans
  • +
  • Maps
  • @{ var toolsActive = Model.ActiveSection == "Story Bible" || Model.ActiveSection == "Metrics" || Model.ActiveSection == "Health" || Model.ActiveSection == "Warnings" || Model.ActiveSection == "Archive"; } diff --git a/PlotLine/wwwroot/css/maps-workspace.css b/PlotLine/wwwroot/css/maps-workspace.css new file mode 100644 index 00000000..89cb11ab --- /dev/null +++ b/PlotLine/wwwroot/css/maps-workspace.css @@ -0,0 +1,4 @@ +.maps-shell{max-width:none!important}.maps-app{--map-ink:#283f3c;--map-panel:#fbfaf4;--map-line:#c7cbbd;color:var(--map-ink);background:var(--map-panel);border:1px solid var(--map-line);border-radius:12px;display:flex;flex-direction:column;overflow:hidden;height:calc(100dvh - 210px);min-height:540px}.maps-app button,.maps-app input,.maps-app select,.maps-app textarea{font:inherit;color:#283f3c;background:#fffef9;border:1px solid #adb8ab;border-radius:5px;padding:6px 9px;max-width:100%;min-width:0}.maps-app button{cursor:pointer;line-height:1.3}.maps-app button:hover{background:#e4eddf}.maps-app button:disabled{opacity:.5;cursor:default}.maps-app button[aria-pressed=true]{background:#dce9d0;border-color:#526f55}.maps-app :focus-visible{outline:3px solid #176b89;outline-offset:2px}.maps-app h1{font-size:1.25rem;margin:0}.maps-app h2{font-size:1.05rem;margin:10px 0}.maps-app label{display:flex;flex-direction:column;gap:3px;margin:8px 0;font-size:.88rem}.maps-toolbar{display:flex;align-items:center;gap:8px;padding:10px;flex-wrap:wrap;border-bottom:1px solid var(--map-line)}.maps-toolbar label{flex-direction:row;align-items:center;margin:0}.maps-toolbar [role=group]{display:flex;gap:3px}.maps-toolbar details{position:relative}.maps-menu{position:absolute;z-index:8;background:#fffef9;padding:8px;width:180px;box-shadow:0 4px 12px #0003;display:grid;gap:5px}.maps-status{margin:0;padding:5px 12px;font-size:.82rem;min-height:30px;background:#edf0e5;border-bottom:1px solid var(--map-line)}.maps-status[data-error=true]{background:#ffe8d4;color:#752d16}.maps-body{display:grid;grid-template-columns:220px minmax(0,1fr) 280px;min-height:0;flex:1}.maps-library,.maps-details{padding:8px 12px;overflow:auto;background:var(--map-panel)}.maps-library{border-right:1px solid var(--map-line)}.maps-details{border-left:1px solid var(--map-line)}.maps-hint{font-size:.8rem;color:#58675e}.maps-assets{display:grid;grid-template-columns:1fr 1fr;gap:5px}.maps-assets button{text-align:left;font-size:.83rem}.maps-assets button span{display:block;color:#62765b;font-size:1.2rem}.maps-library #mapsLocations{display:grid;gap:4px}.maps-centre{position:relative;display:flex;flex-direction:column;overflow:hidden;min-width:0;background:#c9dfdf}.maps-centre nav{background:#f7f7eced;display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:6px 10px;font-size:.85rem;min-height:33px}.maps-centre nav a{color:#315b5a}.maps-centre svg{width:100%;flex:1;min-height:0;touch-action:none;cursor:grab}.maps-centre svg.placing{cursor:crosshair}.maps-canvas-tools{display:flex;gap:7px;align-items:center;padding:7px;background:#f7f7eced;font-size:.8rem;flex-wrap:wrap}.maps-canvas-tools span:last-child{margin-left:auto}.maps-feature{cursor:pointer}.maps-feature .map-shape{stroke-linejoin:round}.maps-feature.is-provisional .map-shape{stroke-dasharray:5 3}.maps-feature.is-selected .map-shape{stroke:#136883!important;stroke-width:3!important;filter:drop-shadow(0 0 3px #fff)}.maps-feature .map-label{font-family:system-ui,sans-serif;font-size:13px;font-weight:600;fill:#243f38;paint-order:stroke;stroke:#faf9ed;stroke-width:4px;stroke-linejoin:round}.maps-feature .map-symbol{fill:#314f48;font-size:22px;text-anchor:middle;dominant-baseline:central}.maps-handle{fill:#fff;stroke:#176b89;stroke-width:2;cursor:move}.maps-details details{border-top:1px solid #d4d8c9;margin-top:12px;padding-top:8px}.maps-details summary{cursor:pointer;font-weight:600}.maps-details .maps-inline{display:flex;gap:5px;flex-wrap:wrap}.maps-details .maps-inline button{font-size:.82rem}.maps-details label:has(input[type=checkbox]),.maps-library label:has(input[type=checkbox]){flex-direction:row;align-items:center}.maps-details select,.maps-details input:not([type=checkbox]),.maps-details textarea{width:100%}.maps-details .maps-rel{padding:6px 0;border-bottom:1px solid #ddd;font-size:.85rem}.maps-details a{color:#215b68}.maps-app dialog{color:#283f3c;background:#fbfaf4;border:1px solid #b7c3af;border-radius:12px;max-width:min(480px,94vw);padding:24px}.maps-app dialog::backdrop{background:#1c342b66}.maps-app dialog button{margin:6px 4px 0 0}.maps-app [hidden]{display:none!important}#mapsWelcome{position:absolute;inset:34px 0 0;background:#f5f3e7;z-index:2;padding:32px;overflow:auto}#mapsList{display:grid;gap:9px;margin-top:22px}#mapsList a{padding:12px;border:1px solid #bbc8b3;border-radius:8px;background:#fffdf4}#mapsStory{padding:10px;background:#f7eac6;font-size:.88rem}.maps-app[data-mode=explore] .maps-library,.maps-app[data-mode=story] .maps-library{display:none}.maps-app[data-mode=explore] .maps-body,.maps-app[data-mode=story] .maps-body{grid-template-columns:minmax(0,1fr) 280px}.maps-maximised{position:fixed;inset:8px;z-index:1040;height:auto!important}.maps-app[data-mode=explore] .maps-edit-only,.maps-app[data-mode=story] .maps-edit-only{display:none}html[data-standalone=true] #mapsMaximise{display:none}html[data-standalone=true] .maps-toolbar:has([data-pwa-accounted=true]){display:none}html[data-standalone=true] .maps-app{height:calc(100dvh - var(--maps-shell-top,180px) - 8px);min-height:350px}.maps-search-results{display:grid;gap:4px;max-height:210px;overflow:auto;margin:5px 0}.maps-search-results button{text-align:left}.maps-context-menu{position:fixed;z-index:1050;background:#fffef9;box-shadow:0 4px 18px #0004;padding:8px;display:grid;gap:4px}.maps-feature:focus{outline:none}.maps-feature:focus .map-shape{stroke:#136883;stroke-width:3}@media(max-width:1100px){.maps-body{grid-template-columns:180px minmax(0,1fr) 240px}.maps-app{height:calc(100dvh - 180px)}.maps-assets{grid-template-columns:1fr}}@media(max-width:760px){.maps-body{grid-template-columns:130px minmax(0,1fr)}.maps-details{grid-column:1/-1;max-height:230px;border-top:1px solid #bcc6b5}.maps-app[data-mode=explore] .maps-body,.maps-app[data-mode=story] .maps-body{grid-template-columns:1fr}.maps-library{padding:6px}.maps-app{min-height:760px}.maps-toolbar{font-size:.85rem}.maps-canvas-tools span:last-child{display:none}}@media(prefers-reduced-motion:reduce){.maps-app *{scroll-behavior:auto!important;transition:none!important}} +.maps-find{position:relative}.maps-find .maps-search-results:not(:empty){position:absolute;z-index:12;background:#fffef8;box-shadow:0 4px 14px #0003;padding:8px;min-width:240px}.maps-find input{width:180px} +#mapsSearchResults:not(:empty){position:absolute;top:34px;right:10px;z-index:10;width:min(320px,90%);padding:8px;background:#fffef8;box-shadow:0 4px 14px #0003}.maps-app h1,.maps-app h2,.maps-app h3{color:var(--map-ink)}.maps-toolbar form{margin:0} +html[data-standalone=true]:has(#mapsApp) [data-pwa-context-controls] .pd-context-group[aria-label=Workspace]{display:none} diff --git a/PlotLine/wwwroot/js/maps-engine.js b/PlotLine/wwwroot/js/maps-engine.js new file mode 100644 index 00000000..6d943b4a --- /dev/null +++ b/PlotLine/wwwroot/js/maps-engine.js @@ -0,0 +1,123 @@ +/* Canonical visual geometry is in author-controlled canvas units, never physical distance. */ +(function (root, factory) { + const api = factory(); + if (typeof module === 'object' && module.exports) module.exports = api; + else root.PlotDirectorMaps = api; +})(typeof globalThis !== 'undefined' ? globalThis : this, function () { + 'use strict'; + const library = []; + function group(category, names, geometryClass = 'Marker', layer = 'Places', symbol = '◆') { + names.split('|').forEach(type => library.push({ type, category, geometryClass, layer, symbol })); + } + group('Places', 'Capital|City|Town|Village|Hamlet|Settlement', 'Marker', 'Places', '⌂'); + group('Buildings', 'House|Cottage|Farm|Manor|Palace|Castle|Fortress|Tower|Inn|Ruin', 'Marker', 'Places', '▥'); + group('Culture', 'Church|Cathedral|Abbey|Monastery|Temple|Shrine|Sacred site|Monument', 'Marker', 'Places', '♜'); + group('Transport', 'Bridge|Ford|Port|Harbour|Dock|Station|Crossroads|Gate|Airport', 'Marker', 'Places', '⚑'); + group('Landmarks', 'Peak|Cave|Waterfall|Spring|Volcano|Significant tree|Landmark', 'Marker', 'Places', '▲'); + group('Working places', 'Mine|Quarry|Forge|Factory|Mill|Warehouse|Camp|Custom', 'Marker', 'Places', '◇'); + group('Land & terrain', 'Land Mass|Island|Mountain Range|Hills|Desert|Plains|Farmland', 'Area', 'Terrain', '▱'); + group('Vegetation', 'Forest|Marsh', 'Area', 'Vegetation', '♣'); + group('Water', 'Lake', 'Area', 'Water', '≈'); + group('Water', 'River|Stream|Canal', 'Path', 'Water', '≈'); + group('Routes', 'Major road|Road|Track|Trail|Railway|Sea route|Wall|Mountain ridge', 'Path', 'Routes', '↝'); + group('Borders & regions', 'Kingdom|Province|County|Territory|Faction area|Disputed area', 'Area', 'Regions', '▧'); + const directions = ['N','NE','E','SE','S','SW','W','NW']; + const distances = ['Very close','Close','Moderate','Far','Very far']; + const vectors = [[0,-1],[.707,-.707],[1,0],[.707,.707],[0,1],[-.707,.707],[-1,0],[-.707,-.707]]; + const copy = value => JSON.parse(JSON.stringify(value)); + function geometry(f) { try { return JSON.parse(f.geometryJson || '{}'); } catch { return {}; } } + function makeFeature(type, x, y, id) { + const a = library.find(a => a.type === type) || library.find(a => a.type === 'Custom'); + const area = a.geometryClass === 'Area', path = a.geometryClass === 'Path'; + const points = area ? [[-.48,-.22],[-.20,-.5],[.17,-.43],[.48,-.18],[.4,.26],[.1,.48],[-.26,.35],[-.5,.1]] : [[-.5,-.25],[-.18,.08],[.15,-.1],[.5,.25]]; + return { featureID: id, name: type, type, geometryClass:a.geometryClass, layer:a.layer, x,y,width:area?330:path?260:42,height:area?220:path?130:42,rotation:0,zOrder:area?(a.layer==='Regions'?20:0):path?30:40,isPlaced:true,isProvisional:true,isLocked:false,showLabel:true,labelX:0,labelY:0,locationID:null,createLocation:false,floorPlanID:null,startFeatureID:null,endFeatureID:null,geometryJson:JSON.stringify({points,coast:'Natural'}),notes:'' }; + } + function localToWorld(f,p) { + const a=f.rotation*Math.PI/180, x=p[0]*f.width,y=p[1]*f.height; + return [f.x+x*Math.cos(a)-y*Math.sin(a),f.y+x*Math.sin(a)+y*Math.cos(a)]; + } + function pathPoints(f,features) { + const points=(geometry(f).points || [[-.5,0],[.5,0]]).map(p=>localToWorld(f,p)); + for (const [index,key] of [[0,'startFeatureID'],[points.length-1,'endFeatureID']]) { + const end=features.find(x=>x.featureID===f[key]); + if(end) points[index]=[end.x,end.y]; + } + return points; + } + function curve(points,closed=false) { + if(!points.length) return ''; + let d=`M ${points[0][0]} ${points[0][1]}`; + const n=points.length; + for(let i=0;i<(closed?n:n-1);i++) { + const p0=points[(i-1+n)%n],p1=points[i],p2=points[(i+1)%n],p3=points[(i+2)%n]; + const a=(!closed&&i===0)?p1:p0,b=(!closed&&i===n-2)?p2:p3; + d+=` C ${p1[0]+(p2[0]-a[0])/6} ${p1[1]+(p2[1]-a[1])/6} ${p2[0]-(b[0]-p1[0])/6} ${p2[1]-(b[1]-p1[1])/6} ${p2[0]} ${p2[1]}`; + } + return d+(closed?' Z':''); + } + function coastline(f) { + const g=geometry(f),points=g.points || [],rough={Gentle:0,Natural:.018,Rugged:.045,Cliffs:.025,Fjords:.07,'Marsh/Delta':.035}[g.coast]??.018; + if(!['Land Mass','Island'].includes(f.type)) return points; + // Stable detail follows simple author control points; no random state or physical coordinates. + return points.flatMap((p,i)=>{ + const q=points[(i+1)%points.length],dx=q[0]-p[0],dy=q[1]-p[1]; + return Array.from({length:5},(_,k)=>{const t=k/5,w=Math.sin((i*5+k)*2.399)*rough*Math.sin(t*Math.PI);return [p[0]+dx*t-dy*w,p[1]+dy*t+dx*w];}); + }); + } + function suggestedDirection(a,b) { + const angle=Math.atan2(a.x-b.x,-(a.y-b.y)); + return directions[(Math.round(angle/(Math.PI/4))+8)%8]; + } + function arrange(features,relationships,onlyNew=false) { + const result=copy(features),byId=new Map(result.map(f=>[f.featureID,f])); + const movable=f=>!f.isLocked&&(!onlyNew||!f.isPlaced); + const original=new Map(features.map(f=>[f.featureID,f])); + const constraints=relationships.filter(r=>byId.has(r.sourceID)&&byId.has(r.targetID)).map(copy).sort((a,b)=>a.relationshipID.localeCompare(b.relationshipID)); + for(const route of result.filter(f=>f.geometryClass==='Path'&&f.startFeatureID&&f.endFeatureID)) { + if(!byId.has(route.startFeatureID)||!byId.has(route.endFeatureID)||constraints.some(r=>(r.sourceID===route.startFeatureID&&r.targetID===route.endFeatureID)||(r.targetID===route.startFeatureID&&r.sourceID===route.endFeatureID)))continue; + constraints.push({relationshipID:'route-'+route.featureID,sourceID:route.endFeatureID,targetID:route.startFeatureID,direction:suggestedDirection(byId.get(route.endFeatureID),byId.get(route.startFeatureID)),relativeDistance:'Moderate',connection:true}); + } + const adjacency=new Map(result.map(f=>[f.featureID,[]])); + for(const r of constraints){adjacency.get(r.sourceID).push(r.targetID);adjacency.get(r.targetID).push(r.sourceID);} + const spacing=(a,b,r)=>([100,180,290,430,600][distances.indexOf(r.relativeDistance)]||240)+Math.min(Math.max(a.width,a.height,b.width,b.height)/2,180); + const markers=result.filter(f=>f.geometryClass==='Marker'),cellSize=Math.max(120,...markers.map(f=>Math.max(f.width,f.height)+60)); + // An established anchor per component prevents drift. Unplaced pieces stay free. + const anchored=new Set(),visited=new Set(); + for(const seed of result) { + if(visited.has(seed.featureID))continue; + const queue=[seed],component=[];visited.add(seed.featureID); + while(queue.length){const f=queue.shift();component.push(f);for(const other of adjacency.get(f.featureID))if(!visited.has(other)){visited.add(other);queue.push(byId.get(other));}} + const anchor=component.find(f=>f.isLocked)||component.find(f=>f.isPlaced); + if(anchor)anchored.add(anchor.featureID); + } + for(let pass=0;pass<100;pass++) { + for(const r of constraints) { + const a=byId.get(r.sourceID),b=byId.get(r.targetID),v=vectors[directions.indexOf(r.direction||suggestedDirection(original.get(a.featureID),original.get(b.featureID)))]; + if(!r.direction&&!r.relativeDistance)continue; + const distance=spacing(a,b,r); + const dx=(a.x-b.x)-v[0]*distance,dy=(a.y-b.y)-v[1]*distance; + const ma=movable(a)&&!anchored.has(a.featureID),mb=movable(b)&&!anchored.has(b.featureID),n=Number(ma)+Number(mb); + if(ma){a.x-=dx*.35/n;a.y-=dy*.35/n;} + if(mb){b.x+=dx*.35/n;b.y+=dy*.35/n;} + } + // Existing manual placement has a persistent restoring weight. + for(const f of result)if(movable(f)&&!anchored.has(f.featureID)&&f.isPlaced){const o=original.get(f.featureID);f.x+=(o.x-f.x)*.012;f.y+=(o.y-f.y)*.012;} + const buckets=new Map(); + for(const a of markers){const cx=Math.floor(a.x/cellSize),cy=Math.floor(a.y/cellSize);for(let ox=-1;ox<=1;ox++)for(let oy=-1;oy<=1;oy++)for(const b of buckets.get(`${cx+ox},${cy+oy}`)||[]){ + const min=(Math.max(a.width,a.height)+Math.max(b.width,b.height))/2+30,dx=b.x-a.x,dy=b.y-a.y,len=Math.hypot(dx,dy); + if(len>=min)continue; + const shift=(min-len)*.5,ux=len?dx/len:1,uy=len?dy/len:0; + if(movable(b)&&!anchored.has(b.featureID)){b.x+=ux*shift;b.y+=uy*shift;} + if(movable(a)&&!anchored.has(a.featureID)){a.x-=ux*shift;a.y-=uy*shift;} + }const key=`${cx},${cy}`;if(!buckets.has(key))buckets.set(key,[]);buckets.get(key).push(a);} + } + const warnings=[]; + for(const r of constraints) { + const a=byId.get(r.sourceID),b=byId.get(r.targetID); + if(!r.connection&&((r.direction&&suggestedDirection(a,b)!==r.direction)||(r.relativeDistance&&Math.abs(Math.hypot(a.x-b.x,a.y-b.y)-spacing(a,b,r))>spacing(a,b,r)*.5)))warnings.push(`${a.name} ${r.direction} of ${b.name}`); + } + result.forEach(f=>{if(movable(f))f.isPlaced=true;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}; +}); diff --git a/PlotLine/wwwroot/js/maps-workspace.js b/PlotLine/wwwroot/js/maps-workspace.js new file mode 100644 index 00000000..f40a454e --- /dev/null +++ b/PlotLine/wwwroot/js/maps-workspace.js @@ -0,0 +1,241 @@ +(() => { + 'use strict'; + 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; + 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; + 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);} + function snapshot(){return JSON.stringify(doc);} + function checkpoint(){if(!doc)return;history.push(snapshot());if(history.length>70)history.shift();future=[];} + function changed(message='Unsaved changes'){dirty=true;status(message);updateButtons();} + function edit(action){if(!doc||mode!=='create'||preview||busy)return;checkpoint();action();changed();render();details();locations();} + function updateButtons(){ $('mapsUndo').disabled=!history.length||!!preview; $('mapsRedo').disabled=!future.length||!!preview; $('mapsSave').disabled=!doc||busy||!!preview; } + async function request(action,data,json=false){ + const response=await fetch('/Maps/'+action,{method:'POST',headers:{'RequestVerificationToken':token,...(json?{'Content-Type':'application/json'}:{})},body:json?JSON.stringify(data):new URLSearchParams(data)}); + if(response.redirected)throw new Error('Your session or subscription needs attention. Open your account in another tab; your edits remain here.'); + const content=await response.json().catch(()=>null); + 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)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; + 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); + for(const f of doc.features)if(f.locationID&&!boot.locations.some(l=>l.locationID===f.locationID))boot.locations.push({locationID:f.locationID,locationName:f.name,projectID:boot.projectId}); + $('mapsSelect').selectedOptions[0].textContent=doc.map.name;status('Saved');render();details();locations();return true; + }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:'');} + function navigate(id){if(dirty&&!confirm('Leave this map and discard unsaved changes?'))return;location.href=url(id);} + 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];} + function fit(items=doc?.features||[]){if(!items.length){view={x:-600,y:-400,w:1200,h:800};applyView();return;} + let left=Infinity,top=Infinity,right=-Infinity,bottom=-Infinity; + for(const f of items){let pts=f.geometryClass==='Path'?E.pathPoints(f,doc.features):[[f.x-f.width/2,f.y-f.height/2],[f.x+f.width/2,f.y+f.height/2]];for(const p of pts){left=Math.min(left,p[0]);right=Math.max(right,p[0]);top=Math.min(top,p[1]);bottom=Math.max(bottom,p[1]);}} + let w=Math.max(350,right-left+180),h=Math.max(250,bottom-top+180),ratio=svg.clientWidth/Math.max(1,svg.clientHeight);if(w/h!hiddenLayers.has(f.layer)); + const alive=new Set(visible.map(f=>f.featureID)),scale=view.w/Math.max(svg.clientWidth,1),labelBoxes=[]; + for(const[id,node]of nodes)if(!alive.has(id)){node.remove();nodes.delete(id);} + const childIDs=new Set(boot.maps.filter(m=>m.parentMapID===doc.map.mapID&&m.parentFeatureID).map(m=>m.parentFeatureID)); + const ordered=[...visible].sort((a,b)=>a.zOrder-b.zOrder||a.featureID.localeCompare(b.featureID)); + 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)); + // 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=`${esc(symbol)}`; + }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'; + const width=f.type==='Major road'?8:road?5:f.type==='Stream'?3:water?7:3; + markup=``; + if(rail)markup+=``; + markup+=``; + }else{ + const fills={'Forest':'url(#map-forest)','Mountain Range':'url(#map-mountains)','Hills':'url(#map-hills)','Marsh':'url(#map-marsh)','Farmland':'url(#map-farmland)','Lake':'#91c0d0','Desert':'#e9d499','Plains':'#d8dcb1'}; + const overlay=f.layer==='Regions',points=E.coastline(f).map(p=>[p[0]*f.width,p[1]*f.height]); + markup=``; + } + if(f.showLabel&&!hiddenLayers.has('Labels')&&(scale<4||isSelected||['Capital','City'].includes(f.type))){ + let x=f.x+f.labelX,y=f.y+f.labelY+(f.geometryClass==='Marker'?34*scale:0),text=f.name+(f.isProvisional?' ◇':'')+(childIDs.has(f.featureID)?' ↳':''),width=text.length*7*scale; + if(!f.labelX&&!f.labelY)for(let attempt=0;attempt<5;attempt++){if(!labelBoxes.some(b=>Math.abs(b.x-x)<(b.w+width)/2&&Math.abs(b.y-y)<18*scale))break;y+=19*scale;} + labelBoxes.push({x,y,w:width});markup+=`${esc(text)}`; + } + if(g.innerHTML!==markup)g.innerHTML=markup; + // append only when ordering changes, preserving DOM focus on normal updates + } + if(!affected)ordered.forEach((f,i)=>{const node=nodes.get(f.featureID);if(scene.children[i]!==node)scene.insertBefore(node,scene.children[i]||null);}); + renderHandles(scale); + } + 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'); + } + 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 library(){const categories=[...new Set(E.library.map(a=>a.category))];$('mapsCategory').innerHTML=''+categories.map(c=>``).join(''); + for(const layer of ['Terrain','Water','Vegetation','Places','Routes','Regions','Labels']){const label=document.createElement('label');label.innerHTML=` ${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=>``).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=>``).join('')||'

    No unplaced Locations match.

    ';} + 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=`All maps`+list.map(m=>`${esc(m.name)}`).join('');} + function option(value,label,selectedValue){return ``;} + function field(label,key,value,type='text',attrs=''){return ``;} + function check(label,key,value){return ``;} + function details(){ + const content=$('mapsDetailContent'); + if(!doc){content.textContent='Create or open a map to begin.';return;} + const search=''; + const f=doc.features.find(f=>selected.has(f.featureID)); + if(!f){content.innerHTML=search+`

    ${esc(doc.map.name)} · ${doc.features.length} pieces

    Pick a piece on the left, then click to place it. Drag the map background to pan.

    ◇ Planning pieces have dashed outlines. They become story Locations only when you choose.

    `;return;} + if(selected.size>1){content.innerHTML=search+`

    ${selected.size} pieces selected.

    `;return;} + const child=boot.maps.find(m=>m.parentMapID===doc.map.mapID&&m.parentFeatureID===f.featureID),linked=boot.locations.find(l=>l.locationID===f.locationID); + const readonly=mode!=='create'; + let html=search+`

    ${esc(f.name)}

    ${esc(f.type)}${f.isProvisional?' · ◇ Planning':''}${f.isLocked?' · Locked':''}

    `; + if(readonly){html+=f.notes?`

    ${esc(f.notes)}

    `:'';if(linked)html+=`Open story Location: ${esc(linked.locationName)}`;} + else{ + html+=`
    ${field('Name','name',f.name,'text','id="mapName" maxlength="200"')}`; + if(f.geometryClass==='Marker')html+=``; + html+=check('Planning / provisional','isProvisional',f.isProvisional)+check('Lock position','isLocked',f.isLocked)+check('Show label','showLabel',f.showLabel); + html+=`
    Story Location

    A map feature can exist without a story Location.

    `; + if(!f.locationID)html+=check('Create a story Location when saved (establishes this place)','createLocation',f.createLocation); + if(linked)html+=`Open ${esc(linked.locationName)}`; + html+='
    '; + if(f.geometryClass!=='Marker'){ + html+=`
    Shape${field('Width','width',f.width,'number','min="10" max="10000"')}${field('Height','height',f.height,'number','min="10" max="10000"')}${field('Rotate (degrees)','rotation',f.rotation,'number','min="-360" max="360"')}`; + if(['Land Mass','Island'].includes(f.type))html+=``; + html+=`

    Drag the corner to resize, or edit a few shape points.

    `; + } + if(f.geometryClass==='Path')html+=`
    Connections

    Endpoints stay attached as places move.

    ${['startFeatureID','endFeatureID'].map((key,i)=>``).join('')}
    `; + html+=`
    Labels & notes${field('Label across','labelX',f.labelX,'number')}${field('Label down','labelY',f.labelY,'number')}
    `; + html+=`
    Floor Plan
    `; + html+=`
    `; + } + if(child)html+=`

    Open detailed map: ${esc(child.name)} ↳

    `; + else if(!readonly)html+='

    '; + if(f.floorPlanID)html+=`

    Open Floor Plan

    `; + html+=`
    Spatial relationships

    Directions and distances describe intent; placement remains yours.

    `; + for(const r of doc.relationships.filter(r=>r.sourceID===f.featureID||r.targetID===f.featureID)){ + const a=doc.features.find(x=>x.featureID===r.sourceID),b=doc.features.find(x=>x.featureID===r.targetID); + html+=`
    ${esc(a?.name)} ${esc(r.direction||'relative to')} ${esc(b?.name)} · ${esc(r.relativeDistance||'distance unspecified')}${r.measuredDistance!=null?` · ${esc(r.measuredDistance)} ${esc(r.unit)}`:''}${r.typicalTravelTime?` · travel: ${esc(r.typicalTravelTime)}`:''}${!readonly?` `:''}
    `; + } + if(!readonly)html+=''; + html+='
    ';content.innerHTML=html; + } + function relationEditor(id){const f=doc.features.find(f=>selected.has(f.featureID));if(!f)return;const old=doc.relationships.find(r=>r.relationshipID===id),other=doc.features.find(x=>x.featureID!==f.featureID);if(!old&&!other){status('Place a second item to define a relationship.');return;} + const r=old||{relationshipID:guid(),sourceID:f.featureID,targetID:other.featureID,direction:E.suggestedDirection(f,other),relativeDistance:'Close',measuredDistance:null,unit:'',typicalTravelTime:'',notes:''}; + const dialog=document.createElement('dialog');dialog.innerHTML=`

    Spatial relationship

    Known distance / typical travel time
    `;app.append(dialog);dialog.showModal();dialog.querySelector('[data-cancel]').onclick=()=>dialog.close();dialog.onclose=()=>dialog.remove();dialog.querySelector('form').onsubmit=e=>{e.preventDefault();const values=Object.fromEntries(new FormData(e.target));if(values.sourceID===values.targetID){status('Choose two different places.',true);return;}safeEdit(()=>{Object.assign(r,values,{direction:values.direction||null,relativeDistance:values.relativeDistance||null,measuredDistance:values.measuredDistance===''?null:Number(values.measuredDistance)});if(!old)doc.relationships.push(r);});dialog.close();};} + function remove(){safeEdit(()=>{const ids=new Set([...selected].filter(id=>!doc.features.find(f=>f.featureID===id)?.isLocked));doc.features=doc.features.filter(f=>!ids.has(f.featureID));doc.relationships=doc.relationships.filter(r=>!ids.has(r.sourceID)&&!ids.has(r.targetID));for(const f of doc.features){if(ids.has(f.startFeatureID))f.startFeatureID=null;if(ids.has(f.endFeatureID))f.endFeatureID=null;}selected.clear();});} + function duplicate(items){safeEdit(()=>{const mapping=new Map(items.map(f=>[f.featureID,guid()]));const copies=clone(items).map(f=>({...f,featureID:mapping.get(f.featureID),name:f.name+' copy',x:f.x+50,y:f.y+50,isLocked:false,createLocation:false,startFeatureID:mapping.get(f.startFeatureID)||f.startFeatureID,endFeatureID:mapping.get(f.endFeatureID)||f.endFeatureID}));doc.features.push(...copies);selected=new Set(copies.map(f=>f.featureID));});} + function action(name){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f)return; + if(name==='remove')remove();if(name==='duplicate')duplicate(doc.features.filter(f=>selected.has(f.featureID))); + if(name==='relationship')relationEditor();if(name==='child')newMap(f);if(name==='shape'){shapeEdit=!shapeEdit;render();details();} + if(name==='unplace')safeEdit(()=>{f.isPlaced=false;}); + if(name==='bend')safeEdit(()=>{const g=E.geometry(f),pts=g.points||[];if(pts.length>=64)return;let index=0,longest=0;for(let i=0;ilongest){longest=len;index=i;}}const next=pts[(index+1)%pts.length];pts.splice(index+1,0,[(pts[index][0]+next[0])/2,(pts[index][1]+next[1])/2]);g.points=pts;f.geometryJson=JSON.stringify(g);shapeEdit=true;}); + } + 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; + 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);}; + if(['land','island','inland','local'].includes(values.Starter))add(values.Starter==='island'?'Island':'Land Mass',0,0,values.Starter==='local'?1000:850,650); + if(values.Starter==='two'){add('Land Mass',-290,0,480,600);add('Land Mass',300,40,430,570);} + if(values.Starter==='islands'){add('Island',-240,-100,370,300);add('Island',200,90,300,380);add('Island',-70,230,200,170);} + if(features.length){const created={map:{mapID:result.id,projectID:boot.projectId,name:values.Name,kind:values.Kind,revision:0},features,relationships:[]};await request('Save',created,true);}dirty=false;location.href=url(result.id); + }catch(error){status(error.message,true);}finally{submit.disabled=false;}} + 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();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-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();} + }); + document.addEventListener('input',e=>{if(e.target.id==='mapsFind'&&doc){const q=e.target.value.toLowerCase();$('mapsSearchResults').innerHTML=q?doc.features.filter(f=>(f.name+' '+(boot.locations.find(l=>l.locationID===f.locationID)?.locationName||'')).toLowerCase().includes(q)).slice(0,60).map(f=>``).join(''):'';}}); + $('mapsAssetSearch').oninput=assets;$('mapsCategory').onchange=assets;$('mapsLocationSearch').oninput=locations; + 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)return;contextMenu?.remove();const p=world(e),target=e.target.closest('[data-feature-id]'),handle=e.target.closest('[data-handle]'); + 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};}} + 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); + }); + 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);}} + 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='/FloorPlans/Edit/'+f.floorPlanID;}}); + 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='';app.append(contextMenu);}); + document.addEventListener('keydown',e=>{ + 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.target.closest('dialog'))return; + if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'){e.preventDefault();save();return;} + if(mode!=='create'||busy||preview)return; + if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='z'){e.preventDefault();undo(e.shiftKey);} + if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='y'){e.preventDefault();undo(true);} + 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 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 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)); + $('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);}}; + $('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.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=>`${esc(m.name)} · ${esc(m.kind)}${m.parentMapID?' · detail of '+esc(boot.maps.find(p=>p.mapID===m.parentMapID)?.name||'parent map'):''}`).join(''); + if(doc)fit(); + // Expose semantic operations for browser regression fixtures, never credentials or a bypass. + window.PlotDirectorMapWorkspace={get document(){return doc;},get view(){return view;},select,fit,save}; +})();